java applet fail when launched with server "incompatible magic value 1013478509" - java

I'm having a problem with my applet. I have a school project where I'm supposed to make a pong-online game. It runs fine offline but when I try to load it from a server I just get an empty frame with a red text in it. when I click the text I get the message:
incompatible magic value 1013478509
I'm using jetty-all-8.1.8.v20121106.jar, and servlet-api-3.0.jar
The class that starts up the server looks like this:
public class TheServer extends HttpServlet {
private static final long serialVersionUID = 1L;
private Scanner sc;
private String webSite;
private PrintWriter out;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html; charset=UTF-8");
resp.setStatus(HttpServletResponse.SC_OK);
out = resp.getWriter();
sc = new Scanner(new File("F:\\Users\\Johan\\Workspace Kurs 5\\PongOnline\\bin\\pong.html"));
webSite = "";
while(sc.hasNext())
webSite += sc.nextLine();
sc.close();
out.println(webSite);
System.out.println(webSite);
}
public static void main(String...args) throws Exception {
ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS);
context.addServlet(TheServer.class, "/");
Server server = new Server(666);
server.setHandler(context);
server.start();
server.join();
}
}

The magic value of a valid Java class is 0xCAFEBABE (the hex value of 3405691582), which is the first 4 bytes. But you're getting 0x3C68746D (the hex value of 1013478509) which in turn stands for the ASCII characters <, h, t and m. To see it yourself, run this piece of code:
int magic = 1013478509;
ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(magic);
System.out.println(new String(b.array()));
This in combination with the applet being served by a website suggests that it's the start of a <html> tag which in turn suggests that it's a HTML document.
So, the HTTP request to applet has apparently actually returned a HTML document. You should be able to see it yourself when you change the current request URI in browser address bar to point to applet's URL. Then you'll see what the browser actually retrieved when it tried to download the applet. Perhaps it's a simple HTTP 404 error document in flavor of a HTML page.
To fix it, just make sure that the URL in the <applet> or <object> tag is correct. It's relative to the current request URL as you see in browser address bar. The way how your servlet works is quite strange. You're streaming a HTML file from outside the deploy folder. This suggests that the applet is also outside the deploy folder and thus not reachable by a valid URL at all. You should put both the HTML page and the applet in the web content folder. This way you don't need that servlet anymore.

This means you have a file with the .class extension which is not a class. All classes have to start with magic number of 0xCAFEBABE
The first four bytes of your "class" reads
System.out.println(new String(BigInteger.valueOf(1013478509).toByteArray()));
prints
<htm
so I suspect it's a HTML file.

According to the Java Language Specification, a proper .class file has starts with the magic number :
The magic item supplies the magic number identifying the class file
format; it has the value 0xCAFEBABE.
If you open any compiled .class file with a hex editor and inspect its first bytes, they should be 0xCAFEBABE. 1013478509 in ASCII translates to <htm.
Make sure you've got the class properly compiled on the server. And more likely, as BalusC already pointed out in his answer, make sure URL's are correct. The <htm... bytes you're getting might be an HTML error document served by the server.

Related

Java webapp code returning with a path traversal problem when tested in a bot

So I have been given the task of fixing a path traversal problem in a basic Java web app, but I am quite stuck. We are meant to essentially make sure the code is secure, while maintaining functionality (which is the part i am struggling with)
So far I have looked online on how to fix the problems i am receiving, and i managed to fix them, but the bot that tests the code returns with a message saying the application no longer has functionality, but is secure.
The 2 errors I receive are the following:
1) PATH_TRAVERSAL_IN in FileDownload. java
Source File FileDownload. java
Class Name chatapp. FileDownload
Method Name doGet
Source Line 31
2) PT_RELATIVE_PATH_TRAVERSAL in FileDownload. java
Source File FileDownload. java
Class Name chatapp. FileDownload
Method Name doGet
Source Line 28
For reference this code is the original where it functions but it is not secure.
private String DOWNLOAD_PATH = new File(".").getCanonicalPath() +
"/webapps/webapp/app/download";
public FileDownload() throws IOException {
}
public void init() throws ServletException {
//To Do
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
!!!String file = request.getParameter("file");
String downloadPath = DOWNLOAD_PATH + "/" + file;
!!!File downloadFile = new File(FilenameUtils.getName(downloadPath));
if (downloadFile.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="+ downloadFile.getName());
FileInputStream fis = new FileInputStream(downloadFile);
byte[] data = new byte[(int) downloadFile.length()];
fis.read(data);
fis.close();
OutputStream out = response.getOutputStream();
out.write(data);
out.flush();
}
else
response.sendError(404);
}
Does anyone have experience in fixing these sorts of problems? I am sort of confused
Wikipedia's article on path traversal has a proposed method to prevent it:
Process URI requests that do not result in a file request, e.g., executing a hook into user code, before continuing below.
When a URI request for a file/directory is to be made, build a full path to the file/directory if it exists, and normalize all characters (e.g., %20 converted to spaces).
It is assumed that a 'Document Root' fully qualified, normalized, path is known, and this string has a length ''N''. Assume that no files outside this directory can be served.
Ensure that the first ''N'' characters of the fully qualified path to the requested file is exactly the same as the 'Document Root'.
If so, allow the file to be returned.
If not, return an error, since the request is clearly out of bounds from what the web-server should be allowed to serve.
So, you'd create a second file object from DOWNLOAD_PATH, then use getCanonicalPath to see that the path of the file to be downloaded starts with the path of the download directory.
With this done, you'd add a #SuppressWarnings annotation to the method to hide the warnings that are now properly handled.

Android: Showing Spanish (among other) characters read from file

I know there are a lot of questions similar to this all around SO, but they either provide a very case-specific solution that I don't get to adapt to my issue or simply don't seem to work at all.
I have a multi-language app that downloads certain information from the internet and stores it into a file for later usage. This is how the storage is done:
public static void writeStringToFile(String string, File file)
throws IOException {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(string.getBytes("UTF-8"));
outputStream.close();
}
But later, when the spanish version of the file is read, the app displays the special characters, like ñ, as the black diamond with the question mark inside I-ve tried to:
Download the information in my computer to check that the file is fine and put it manually in the app so that it reads from it instead of downloading it itself. The file is fine, but the app shows no change.
Replace the argument of getBytes by "ISO 8859-1", but the only difference in the result is that the weird character is this time the regular question mark.
Copy the file, once downloaded, from the device to the computer to check if it was fine, and it was already wrong (there are "empty square" characters shown in place of the question marks, that are not shown if I wget the file).
So I'm almost sure that the problem is in how I write the file since it gets out of the server fine but is stored wrong. But I have been so much time looking at the method and I can't find what the problem is...any clues?
EDIT: This is how I download the information.
public static InputStream performGetRequest(String uri)
throws IOException, URISyntaxException, ServerIsCheckingException {
HttpResponse response;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(uri));
response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 409) {
throw new ServerIsCheckingException();
}
else {
return response.getEntity().getContent();
}
}
To convert it to a String object that I later pass to the method writeStringToFile, I use
public static String inputStreamAsString(InputStream is) throws IOException {
java.util.Scanner s = new java.util.Scanner(is);
String ret;
ret = s.useDelimiter("\\A").hasNext() ? s.next() : "";
return ret;
}
I also thought that writeStringToFile could be the problem, but I tried another alternative which specifies UTF-8 to be used and didn't work either.
You'll have to make sure that the document you are trying to write is being read in the same charset. In your case, if the document you're downliading is in spanish, it will probably be written in UTF-8 or ISO-8859-1, so you'll have to set the corresponding enconding both in the reading and writing.
You might use HttpProtocolParams.setContentCharset() to set the corresponding charset to the BasicHttpParams object.
This might help:
Android Java UTF-8 HttpClient Problem

Generating a dynamic file and download it in GWT

I am developing a GWT application. This application is running in a server. Well, I implement a button which calls a method that generates a local file in server side. However I would like to download/generate this file in client side. How could I do this in GWT?
Thanks
In our project we created a file on server on demand. When the file has been successful created we send notification to browser and created a link.
See servlet code:
public class DownloadServlet extends HttpServlet {
private FileManager fileManager;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String encodedFileName = req.getRequestURI().substring(
req.getContextPath().length() + req.getServletPath().length() + 1);
String decodedFileName = URLDecoder.decode(encodedFileName, "utf-8");
File downloadableFile = fileManager.toFile(decodedFileName);
ServletOutputStream os = resp.getOutputStream();
try {
InputStream is = FileUtils.openInputStream(downloadableFile);
try {
IOUtils.copy(is, os);
} finally {
is.close();
}
} finally {
os.close();
}
}
}
private native void Download(String filename, String text)/*-{
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom); }-*/;
Use JSNI method inside GWT code , provide the file name you want to download in addition to JSON string as text (String) , this method will download a file with specified content in text variable to client browser.
Current situation is, that not all browsers are able to work with local file system, so there is no universal solution in GWT. Also as far as I know FilesSstem API is not finished.
As alternative you can keep using serverside generated files, or use Flash plugin to generate and store files (you will have to create a Flash app, and create some API to control it from GWT).
You should definitely have a look at Aki Miyazaki’s HTML5 file download code for GWT.
It works on the client side as you requested.
AFAIK, as of now, it only works in Chrome, but this is supposed to change as other browsers implement the download attribute.
You can do that using Data URIs:
Make your GWT RPC method return the file content or the data to generate the file.
On the client side, format a Data URI with the file content received or generate the data content.
Use Window.open to open a file save dialog passing the formatted DataURI.
Take a look at this reference, to understand the Data URI usage:
Export to csv in jQuery

Java URL problem

A webpage contains a link to an executable (i.e. If we click on the link, the browser will download the file on your local machine).
Is there any way to achieve the same functionality with Java?
Thank you
Yes there is.
Here a simple example:
You can have a JSF(Java Server Faces) page, with a supporting backing bean that contains a method annotated with #PostConstruct This means that any action(for example downloading), will occur when the page is created.
There is already a question very similar already, have a look at: Invoke JSF managed bean action on page load
You can use Java's, URL class to download a file, but it requires a little work. You will need to do the following:
Create the URL object point at the file
Call openStream() to get an InputStream
Open the file you want to write to (a FileOutputStream)
Read from the InputStream and write to the file, until there is no more data left to read
Close the input and output streams
It doesn't really matter what type of file you are downloading (the fact that it's an executable file is irrelevant) since the process is the same for any type of file.
Update: It sounds like what you actually want is to plug the URL of a webpage into the Java app, and have the Java app find the link in the page and then download that link. If that is the case, the wording of your question is very unclear, but here are the basic steps I would use:
First, use steps 1 and 2 above to get an InputStream for the page
Use something like TagSoup or jsoup to parse the HTML
Find the <a> element that you want and extract its href attribute to get the URL of the file you need to download (if it's a relative URL instead of absolute, you will need to resolve that URL against the URL of the original page)
Use the steps above to download that URL
Here's a slight shortcut, based on jsoup (which I've never used before, I'm just writing this from snippets stolen from their webpage). I've left out a lot of error checking, but hey, I usually charge for this:
Document doc = Jsoup.connect(pageUrl).get();
Element aElement = doc.getElementsByTag("a").first() // Obviously you may need to refine this
String newUrl = aElement.attr("abs:href"); // This is a piece of jsoup magic that ensures that the destination URL is absolute
// assert newUrl != null
URL fileUrl = new URL(newUrl);
String destPath = fileUrl.getPath();
int lastSlash = destPath.lastIndexOf('/');
if (lastSlash != -1) {
destPath = destPath.substring(lastSlash);
}
// Assert that this is really a valid filename
// Now just download fileUrl and save it to destPath
The proper way to determine what the destination filename should be (unless you hardcode it) is actually to look for the Content-Disposition header, and look for the bit after filename=. In that case, you can't use openStream() on the URL, you will need to use openConnection() instead, to get a URLConnection. Then you can use getInputStream() to get your InputStream and getRequestProperty("Content-Disposition") to get the header to figure out your filename. In case that header is missing or malformed, you should then fall-back to using the method above to determine the destination filename.
You can do this using apache commons IO FileUtils
http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html#copyURLToFile(java.net.URL, java.io.File)
Edit:
I was able to successfully download a zip file from source forge site (it is not empty), It did some thing like this
import java.io.File;
import java.net.URL;
import org.apache.commons.io.FileUtils;
public class Test
{
public static void main(String args[])
{
try {
URL url = new URL("http://sourceforge.net/projects/gallery/files/gallery3/3.0.2/gallery-3.0.2.zip/download");
FileUtils.copyURLToFile(url, new File("test.zip"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I was able successfully download tomcat.exe too
URL url = new URL("http://archive.apache.org/dist/tomcat/tomcat-6/v6.0.16/bin/apache-tomcat-6.0.16.exe");

How to get the result of executing an html file in your local hard disk from a java program?

I'm trying to get the result of executing an html file on my hard disk as a string (thats the type of whats displayed in running the file) form a java program for the first time and it seems i did not get it right.
here is the code:
import java.io.*;
import java.net.URL;
public class MapDir {
public static void main(String[] args) throws FileNotFoundException, IOException
{
String s = "file:///F:/Stuff/Muaz/Programming/Mobile Applications/J2ME/Ride Sharing System/RSS Server/routeDistance.html?addr1=30.065634,31.209473&addr2=29.984177,31.440052";
URL url = new URL("file", "Core", s);
BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream()));
while((s = r.readLine()) != null)
{
System.out.println(s);
}
}
}
when I run the code I get the following error:
java.net.ConnectException: Connection refused: connect....
Of-course Im sure of the string File (s). I ran it form a browser and it works perfectly. The host name is also correct. So whats wrong? Please reply back as soon as you can. Thanks in advance.
Check the documentation for URL, you are...
String s = "file://location";
URL url = new URL("file", "Core", s);
... initializing it incorrectly. Take a look at this link.
Cheers!
Edit: ok, this is a bit long for a comment.
First, the URL class has no method of executing an html file that I know of. Or any class, for that matter.
Second, your code is READING the file, and it would work if it wasn't for the error we pointed out. How am I supposed to know that's not actually want you want to do? I thought the title was just bad english.
Third, nobody is paying us to answer your questions, so instead of barking, try thanking. The same attitude as in "answer as soon as you can" in your original post won't get you support or help.
Ah. I just had to say that. I'll accept any downvotes as just punishment.
Edit 2:
(From my comment below) #Muaz an HTML is just data. Nobody "runs" an HTML file, the same way you don't run a .doc, or a .avi -- you run another program that knows how to interpret this data and what to do with it. That program can be a web browser, Microsoft Word, or the VLC media player; but whatever the case, it's not the data file the one that's being executed. –

Categories