Clover Coverage Report
Coverage timestamp: Fri May 24 2013 13:47:27 UTC
../../../../img/srcFileCovDistChart1.png 95% of files have more coverage
421   1,106   167   16.84
202   795   0.4   8.33
25     6.68  
3    
 
  NanoHTTPD       Line # 72 158 65 3.6% 0.036
  NanoHTTPD.Response       Line # 122 10 5 0% 0.0
  NanoHTTPD.HTTPSession       Line # 302 253 97 0% 0.0
 
  (1)
 
1    package org.qedeq.base.test;
2   
3    import java.io.BufferedReader;
4    import java.io.ByteArrayInputStream;
5    import java.io.File;
6    import java.io.FileInputStream;
7    import java.io.IOException;
8    import java.io.InputStream;
9    import java.io.InputStreamReader;
10    import java.io.OutputStream;
11    import java.io.PrintWriter;
12    import java.net.ServerSocket;
13    import java.net.Socket;
14    import java.net.URLEncoder;
15    import java.util.Date;
16    import java.util.Enumeration;
17    import java.util.Vector;
18    import java.util.Hashtable;
19    import java.util.Locale;
20    import java.util.Properties;
21    import java.util.StringTokenizer;
22    import java.util.TimeZone;
23   
24    import java.io.ByteArrayOutputStream;
25    import java.io.FileOutputStream;
26   
27    /**
28    * A simple, tiny, nicely embeddable HTTP 1.0 (partially 1.1) server in Java
29    *
30    * <p> NanoHTTPD version 1.24,
31    * Copyright &copy; 2001,2005-2011 Jarno Elonen (elonen@iki.fi, http://iki.fi/elonen/)
32    * and Copyright &copy; 2010 Konstantinos Togias (info@ktogias.gr, http://ktogias.gr)
33    *
34    * <p><b>Features + limitations: </b><ul>
35    *
36    * <li> Only one Java file </li>
37    * <li> Java 1.1 compatible </li>
38    * <li> Released as open source, Modified BSD licence </li>
39    * <li> No fixed config files, logging, authorization etc. (Implement yourself if you need them.) </li>
40    * <li> Supports parameter parsing of GET and POST methods </li>
41    * <li> Supports both dynamic content and file serving </li>
42    * <li> Supports file upload (since version 1.2, 2010) </li>
43    * <li> Supports partial content (streaming)</li>
44    * <li> Supports ETags</li>
45    * <li> Never caches anything </li>
46    * <li> Doesn't limit bandwidth, request time or simultaneous connections </li>
47    * <li> Default code serves files and shows all HTTP parameters and headers</li>
48    * <li> File server supports directory listing, index.html and index.htm</li>
49    * <li> File server supports partial content (streaming)</li>
50    * <li> File server supports ETags</li>
51    * <li> File server does the 301 redirection trick for directories without '/'</li>
52    * <li> File server supports simple skipping for files (continue download) </li>
53    * <li> File server serves also very long files without memory overhead </li>
54    * <li> Contains a built-in list of most common mime types </li>
55    * <li> All header names are converted lowercase so they don't vary between browsers/clients </li>
56    *
57    * </ul>
58    *
59    * <p><b>Ways to use: </b><ul>
60    *
61    * <li> Run as a standalone app, serves files and shows requests</li>
62    * <li> Subclass serve() and embed to your own program </li>
63    * <li> Call serveFile() from serve() with your own base directory </li>
64    *
65    * </ul>
66    *
67    * Homepage: http://iki.fi/elonen/code/nanohttpd/
68    *
69    * See the end of the source file for distribution license
70    * (Modified BSD licence)
71    */
 
72    public class NanoHTTPD
73    {
74    // ==================================================
75    // API parts
76    // ==================================================
77   
78    /**
79    * Override this to customize the server.<p>
80    *
81    * (By default, this delegates to serveFile() and allows directory listing.)
82    *
83    * @param uri Percent-decoded URI without parameters, for example "/index.cgi"
84    * @param method "GET", "POST" etc.
85    * @param parms Parsed, percent decoded parameters from URI and, in case of POST, data.
86    * @param header Header entries, percent decoded
87    * @return HTTP response, see class Response for details
88    */
 
89  0 toggle public Response serve( String uri, String method, Properties header, Properties parms, Properties files )
90    {
91  0 System.out.println( method + " '" + uri + "' " );
92   
93  0 Enumeration e = header.propertyNames();
94  0 while ( e.hasMoreElements())
95    {
96  0 String value = (String)e.nextElement();
97  0 System.out.println( " HDR: '" + value + "' = '" +
98    header.getProperty( value ) + "'" );
99    }
100  0 e = parms.propertyNames();
101  0 while ( e.hasMoreElements())
102    {
103  0 String value = (String)e.nextElement();
104  0 System.out.println( " PRM: '" + value + "' = '" +
105    parms.getProperty( value ) + "'" );
106    }
107  0 e = files.propertyNames();
108  0 while ( e.hasMoreElements())
109    {
110  0 String value = (String)e.nextElement();
111  0 System.out.println( " UPLOADED: '" + value + "' = '" +
112    files.getProperty( value ) + "'" );
113    }
114   
115  0 return serveFile( uri, header, myRootDir, true );
116    }
117   
118    /**
119    * HTTP response.
120    * Return one of these from serve().
121    */
 
122    public class Response
123    {
124    /**
125    * Default constructor: response = HTTP_OK, data = mime = 'null'
126    */
 
127  0 toggle public Response()
128    {
129  0 this.status = HTTP_OK;
130    }
131   
132    /**
133    * Basic constructor.
134    */
 
135  0 toggle public Response( String status, String mimeType, InputStream data )
136    {
137  0 this.status = status;
138  0 this.mimeType = mimeType;
139  0 this.data = data;
140    }
141   
142    /**
143    * Convenience method that makes an InputStream out of
144    * given text.
145    */
 
146  0 toggle public Response( String status, String mimeType, String txt )
147    {
148  0 this.status = status;
149  0 this.mimeType = mimeType;
150  0 try
151    {
152  0 this.data = new ByteArrayInputStream( txt.getBytes("UTF-8"));
153    }
154    catch ( java.io.UnsupportedEncodingException uee )
155    {
156  0 uee.printStackTrace();
157    }
158    }
159   
160    /**
161    * Adds given line to the header.
162    */
 
163  0 toggle public void addHeader( String name, String value )
164    {
165  0 header.put( name, value );
166    }
167   
168    /**
169    * HTTP status code after processing, e.g. "200 OK", HTTP_OK
170    */
171    public String status;
172   
173    /**
174    * MIME type of content, e.g. "text/html"
175    */
176    public String mimeType;
177   
178    /**
179    * Data of the response, may be null.
180    */
181    public InputStream data;
182   
183    /**
184    * Headers for the HTTP response. Use addHeader()
185    * to add lines.
186    */
187    public Properties header = new Properties();
188    }
189   
190    /**
191    * Some HTTP response status codes
192    */
193    public static final String
194    HTTP_OK = "200 OK",
195    HTTP_PARTIALCONTENT = "206 Partial Content",
196    HTTP_RANGE_NOT_SATISFIABLE = "416 Requested Range Not Satisfiable",
197    HTTP_REDIRECT = "301 Moved Permanently",
198    HTTP_FORBIDDEN = "403 Forbidden",
199    HTTP_NOTFOUND = "404 Not Found",
200    HTTP_BADREQUEST = "400 Bad Request",
201    HTTP_INTERNALERROR = "500 Internal Server Error",
202    HTTP_NOTIMPLEMENTED = "501 Not Implemented";
203   
204    /**
205    * Common mime types for dynamic content
206    */
207    public static final String
208    MIME_PLAINTEXT = "text/plain",
209    MIME_HTML = "text/html",
210    MIME_DEFAULT_BINARY = "application/octet-stream",
211    MIME_XML = "text/xml";
212   
213    // ==================================================
214    // Socket & server code
215    // ==================================================
216   
217    /**
218    * Starts a HTTP server to given port.<p>
219    * Throws an IOException if the socket is already in use
220    */
 
221  0 toggle public NanoHTTPD( int port, File wwwroot ) throws IOException
222    {
223  0 myTcpPort = port;
224  0 this.myRootDir = wwwroot;
225  0 myServerSocket = new ServerSocket( myTcpPort );
226  0 myThread = new Thread( new Runnable()
227    {
 
228  0 toggle public void run()
229    {
230  0 try
231    {
232  0 while( true )
233  0 new HTTPSession( myServerSocket.accept());
234    }
235    catch ( IOException ioe )
236    {}
237    }
238    });
239  0 myThread.setDaemon( true );
240  0 myThread.start();
241    }
242   
243    /**
244    * Stops the server.
245    */
 
246  0 toggle public void stop()
247    {
248  0 try
249    {
250  0 myServerSocket.close();
251  0 myThread.join();
252    }
253    catch ( IOException ioe ) {}
254    catch ( InterruptedException e ) {}
255    }
256   
257   
258    /**
259    * Starts as a standalone file server and waits for Enter.
260    */
 
261  0 toggle public static void main( String[] args )
262    {
263  0 System.out.println( "NanoHTTPD 1.24 (C) 2001,2005-2011 Jarno Elonen and (C) 2010 Konstantinos Togias\n" +
264    "(Command line options: [-p port] [-d root-dir] [--licence])\n" );
265   
266    // Defaults
267  0 int port = 80;
268  0 File wwwroot = new File(".").getAbsoluteFile();
269   
270    // Show licence if requested
271  0 for ( int i=0; i<args.length; ++i )
272  0 if(args[i].equalsIgnoreCase("-p"))
273  0 port = Integer.parseInt( args[i+1] );
274  0 else if(args[i].equalsIgnoreCase("-d"))
275  0 wwwroot = new File( args[i+1] ).getAbsoluteFile();
276  0 else if ( args[i].toLowerCase().endsWith( "licence" ))
277    {
278  0 System.out.println( LICENCE + "\n" );
279  0 break;
280    }
281   
282  0 try
283    {
284  0 new NanoHTTPD( port, wwwroot );
285    }
286    catch( IOException ioe )
287    {
288  0 System.err.println( "Couldn't start server:\n" + ioe );
289  0 System.exit( -1 );
290    }
291   
292  0 System.out.println( "Now serving files in port " + port + " from \"" + wwwroot + "\"" );
293  0 System.out.println( "Hit Enter to stop.\n" );
294   
295  0 try { System.in.read(); } catch( Throwable t ) {}
296    }
297   
298    /**
299    * Handles one session, i.e. parses the HTTP request
300    * and returns the response.
301    */
 
302    private class HTTPSession implements Runnable
303    {
 
304  0 toggle public HTTPSession( Socket s )
305    {
306  0 mySocket = s;
307  0 Thread t = new Thread( this );
308  0 t.setDaemon( true );
309  0 t.start();
310    }
311   
 
312  0 toggle public void run()
313    {
314  0 try
315    {
316  0 InputStream is = mySocket.getInputStream();
317  0 if ( is == null) return;
318   
319    // Read the first 8192 bytes.
320    // The full header should fit in here.
321    // Apache's default header limit is 8KB.
322  0 int bufsize = 8192;
323  0 byte[] buf = new byte[bufsize];
324  0 int rlen = is.read(buf, 0, bufsize);
325  0 if (rlen <= 0) return;
326   
327    // Create a BufferedReader for parsing the header.
328  0 ByteArrayInputStream hbis = new ByteArrayInputStream(buf, 0, rlen);
329  0 BufferedReader hin = new BufferedReader( new InputStreamReader( hbis ));
330  0 Properties pre = new Properties();
331  0 Properties parms = new Properties();
332  0 Properties header = new Properties();
333  0 Properties files = new Properties();
334   
335    // Decode the header into parms and header java properties
336  0 decodeHeader(hin, pre, parms, header);
337  0 String method = pre.getProperty("method");
338  0 String uri = pre.getProperty("uri");
339   
340  0 long size = 0x7FFFFFFFFFFFFFFFl;
341  0 String contentLength = header.getProperty("content-length");
342  0 if (contentLength != null)
343    {
344  0 try { size = Integer.parseInt(contentLength); }
345    catch (NumberFormatException ex) {}
346    }
347   
348    // We are looking for the byte separating header from body.
349    // It must be the last byte of the first two sequential new lines.
350  0 int splitbyte = 0;
351  0 boolean sbfound = false;
352  0 while (splitbyte < rlen)
353    {
354  0 if (buf[splitbyte] == '\r' && buf[++splitbyte] == '\n' && buf[++splitbyte] == '\r' && buf[++splitbyte] == '\n') {
355  0 sbfound = true;
356  0 break;
357    }
358  0 splitbyte++;
359    }
360  0 splitbyte++;
361   
362    // Write the part of body already read to ByteArrayOutputStream f
363  0 ByteArrayOutputStream f = new ByteArrayOutputStream();
364  0 if (splitbyte < rlen) f.write(buf, splitbyte, rlen-splitbyte);
365   
366    // While Firefox sends on the first read all the data fitting
367    // our buffer, Chrome and Opera sends only the headers even if
368    // there is data for the body. So we do some magic here to find
369    // out whether we have already consumed part of body, if we
370    // have reached the end of the data to be sent or we should
371    // expect the first byte of the body at the next read.
372  0 if (splitbyte < rlen)
373  0 size -= rlen - splitbyte +1;
374  0 else if (!sbfound || size == 0x7FFFFFFFFFFFFFFFl)
375  0 size = 0;
376   
377    // Now read all the body and write it to f
378  0 buf = new byte[512];
379  0 while ( rlen >= 0 && size > 0 )
380    {
381  0 rlen = is.read(buf, 0, 512);
382  0 size -= rlen;
383  0 if (rlen > 0)
384  0 f.write(buf, 0, rlen);
385    }
386   
387    // Get the raw body as a byte []
388  0 byte [] fbuf = f.toByteArray();
389   
390    // Create a BufferedReader for easily reading it as string.
391  0 ByteArrayInputStream bin = new ByteArrayInputStream(fbuf);
392  0 BufferedReader in = new BufferedReader( new InputStreamReader(bin));
393   
394    // If the method is POST, there may be parameters
395    // in data section, too, read it:
396  0 if ( method.equalsIgnoreCase( "POST" ))
397    {
398  0 String contentType = "";
399  0 String contentTypeHeader = header.getProperty("content-type");
400  0 StringTokenizer st = new StringTokenizer( contentTypeHeader , "; " );
401  0 if ( st.hasMoreTokens()) {
402  0 contentType = st.nextToken();
403    }
404   
405  0 if (contentType.equalsIgnoreCase("multipart/form-data"))
406    {
407    // Handle multipart/form-data
408  0 if ( !st.hasMoreTokens())
409  0 sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html" );
410  0 String boundaryExp = st.nextToken();
411  0 st = new StringTokenizer( boundaryExp , "=" );
412  0 if (st.countTokens() != 2)
413  0 sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary syntax error. Usage: GET /example/file.html" );
414  0 st.nextToken();
415  0 String boundary = st.nextToken();
416   
417  0 decodeMultipartData(boundary, fbuf, in, parms, files);
418    }
419    else
420    {
421    // Handle application/x-www-form-urlencoded
422  0 String postLine = "";
423  0 char pbuf[] = new char[512];
424  0 int read = in.read(pbuf);
425  0 while ( read >= 0 && !postLine.endsWith("\r\n") )
426    {
427  0 postLine += String.valueOf(pbuf, 0, read);
428  0 read = in.read(pbuf);
429    }
430  0 postLine = postLine.trim();
431  0 decodeParms( postLine, parms );
432    }
433    }
434   
435    // Ok, now do the serve()
436  0 Response r = serve( uri, method, header, parms, files );
437  0 if ( r == null )
438  0 sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: Serve() returned a null response." );
439    else
440  0 sendResponse( r.status, r.mimeType, r.header, r.data );
441   
442  0 in.close();
443  0 is.close();
444    }
445    catch ( IOException ioe )
446    {
447  0 try
448    {
449  0 sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
450    }
451    catch ( Throwable t ) {}
452    }
453    catch ( InterruptedException ie )
454    {
455    // Thrown by sendError, ignore and exit the thread.
456    }
457    }
458   
459    /**
460    * Decodes the sent headers and loads the data into
461    * java Properties' key - value pairs
462    **/
 
463  0 toggle private void decodeHeader(BufferedReader in, Properties pre, Properties parms, Properties header)
464    throws InterruptedException
465    {
466  0 try {
467    // Read the request line
468  0 String inLine = in.readLine();
469  0 if (inLine == null) return;
470  0 StringTokenizer st = new StringTokenizer( inLine );
471  0 if ( !st.hasMoreTokens())
472  0 sendError( HTTP_BADREQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html" );
473   
474  0 String method = st.nextToken();
475  0 pre.put("method", method);
476   
477  0 if ( !st.hasMoreTokens())
478  0 sendError( HTTP_BADREQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html" );
479   
480  0 String uri = st.nextToken();
481   
482    // Decode parameters from the URI
483  0 int qmi = uri.indexOf( '?' );
484  0 if ( qmi >= 0 )
485    {
486  0 decodeParms( uri.substring( qmi+1 ), parms );
487  0 uri = decodePercent( uri.substring( 0, qmi ));
488    }
489  0 else uri = decodePercent(uri);
490   
491    // If there's another token, it's protocol version,
492    // followed by HTTP headers. Ignore version but parse headers.
493    // NOTE: this now forces header names lowercase since they are
494    // case insensitive and vary by client.
495  0 if ( st.hasMoreTokens())
496    {
497  0 String line = in.readLine();
498  0 while ( line != null && line.trim().length() > 0 )
499    {
500  0 int p = line.indexOf( ':' );
501  0 if ( p >= 0 )
502  0 header.put( line.substring(0,p).trim().toLowerCase(), line.substring(p+1).trim());
503  0 line = in.readLine();
504    }
505    }
506   
507  0 pre.put("uri", uri);
508    }
509    catch ( IOException ioe )
510    {
511  0 sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
512    }
513    }
514   
515    /**
516    * Decodes the Multipart Body data and put it
517    * into java Properties' key - value pairs.
518    **/
 
519  0 toggle private void decodeMultipartData(String boundary, byte[] fbuf, BufferedReader in, Properties parms, Properties files)
520    throws InterruptedException
521    {
522  0 try
523    {
524  0 int[] bpositions = getBoundaryPositions(fbuf,boundary.getBytes());
525  0 int boundarycount = 1;
526  0 String mpline = in.readLine();
527  0 while ( mpline != null )
528    {
529  0 if (mpline.indexOf(boundary) == -1)
530  0 sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html" );
531  0 boundarycount++;
532  0 Properties item = new Properties();
533  0 mpline = in.readLine();
534  0 while (mpline != null && mpline.trim().length() > 0)
535    {
536  0 int p = mpline.indexOf( ':' );
537  0 if (p != -1)
538  0 item.put( mpline.substring(0,p).trim().toLowerCase(), mpline.substring(p+1).trim());
539  0 mpline = in.readLine();
540    }
541  0 if (mpline != null)
542    {
543  0 String contentDisposition = item.getProperty("content-disposition");
544  0 if (contentDisposition == null)
545    {
546  0 sendError( HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html" );
547    }
548  0 StringTokenizer st = new StringTokenizer( contentDisposition , "; " );
549  0 Properties disposition = new Properties();
550  0 while ( st.hasMoreTokens())
551    {
552  0 String token = st.nextToken();
553  0 int p = token.indexOf( '=' );
554  0 if (p!=-1)
555  0 disposition.put( token.substring(0,p).trim().toLowerCase(), token.substring(p+1).trim());
556    }
557  0 String pname = disposition.getProperty("name");
558  0 pname = pname.substring(1,pname.length()-1);
559   
560  0 String value = "";
561  0 if (item.getProperty("content-type") == null) {
562  0 while (mpline != null && mpline.indexOf(boundary) == -1)
563    {
564  0 mpline = in.readLine();
565  0 if ( mpline != null)
566    {
567  0 int d = mpline.indexOf(boundary);
568  0 if (d == -1)
569  0 value+=mpline;
570    else
571  0 value+=mpline.substring(0,d-2);
572    }
573    }
574    }
575    else
576    {
577  0 if (boundarycount> bpositions.length)
578  0 sendError( HTTP_INTERNALERROR, "Error processing request" );
579  0 int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount-2]);
580  0 String path = saveTmpFile(fbuf, offset, bpositions[boundarycount-1]-offset-4);
581  0 files.put(pname, path);
582  0 value = disposition.getProperty("filename");
583  0 value = value.substring(1,value.length()-1);
584  0 do {
585  0 mpline = in.readLine();
586  0 } while (mpline != null && mpline.indexOf(boundary) == -1);
587    }
588  0 parms.put(pname, value);
589    }
590    }
591    }
592    catch ( IOException ioe )
593    {
594  0 sendError( HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
595    }
596    }
597   
598    /**
599    * Find the byte positions where multipart boundaries start.
600    **/
 
601  0 toggle public int[] getBoundaryPositions(byte[] b, byte[] boundary)
602    {
603  0 int matchcount = 0;
604  0 int matchbyte = -1;
605  0 Vector matchbytes = new Vector();
606  0 for (int i=0; i<b.length; i++)
607    {
608  0 if (b[i] == boundary[matchcount])
609    {
610  0 if (matchcount == 0)
611  0 matchbyte = i;
612  0 matchcount++;
613  0 if (matchcount==boundary.length)
614    {
615  0 matchbytes.addElement(new Integer(matchbyte));
616  0 matchcount = 0;
617  0 matchbyte = -1;
618    }
619    }
620    else
621    {
622  0 i -= matchcount;
623  0 matchcount = 0;
624  0 matchbyte = -1;
625    }
626    }
627  0 int[] ret = new int[matchbytes.size()];
628  0 for (int i=0; i < ret.length; i++)
629    {
630  0 ret[i] = ((Integer)matchbytes.elementAt(i)).intValue();
631    }
632  0 return ret;
633    }
634   
635    /**
636    * Retrieves the content of a sent file and saves it
637    * to a temporary file.
638    * The full path to the saved file is returned.
639    **/
 
640  0 toggle private String saveTmpFile(byte[] b, int offset, int len)
641    {
642  0 String path = "";
643  0 if (len > 0)
644    {
645  0 String tmpdir = System.getProperty("java.io.tmpdir");
646  0 try {
647  0 File temp = File.createTempFile("NanoHTTPD", "", new File(tmpdir));
648  0 OutputStream fstream = new FileOutputStream(temp);
649  0 fstream.write(b, offset, len);
650  0 fstream.close();
651  0 path = temp.getAbsolutePath();
652    } catch (Exception e) { // Catch exception if any
653  0 System.err.println("Error: " + e.getMessage());
654    }
655    }
656  0 return path;
657    }
658   
659   
660    /**
661    * It returns the offset separating multipart file headers
662    * from the file's data.
663    **/
 
664  0 toggle private int stripMultipartHeaders(byte[] b, int offset)
665    {
666  0 int i = 0;
667  0 for (i=offset; i<b.length; i++)
668    {
669  0 if (b[i] == '\r' && b[++i] == '\n' && b[++i] == '\r' && b[++i] == '\n')
670  0 break;
671    }
672  0 return i+1;
673    }
674   
675    /**
676    * Decodes the percent encoding scheme. <br/>
677    * For example: "an+example%20string" -> "an example string"
678    */
 
679  0 toggle private String decodePercent( String str ) throws InterruptedException
680    {
681  0 try
682    {
683  0 StringBuffer sb = new StringBuffer();
684  0 for( int i=0; i<str.length(); i++ )
685    {
686  0 char c = str.charAt( i );
687  0 switch ( c )
688    {
689  0 case '+':
690  0 sb.append( ' ' );
691  0 break;
692  0 case '%':
693  0 sb.append((char)Integer.parseInt( str.substring(i+1,i+3), 16 ));
694  0 i += 2;
695  0 break;
696  0 default:
697  0 sb.append( c );
698  0 break;
699    }
700    }
701  0 return sb.toString();
702    }
703    catch( Exception e )
704    {
705  0 sendError( HTTP_BADREQUEST, "BAD REQUEST: Bad percent-encoding." );
706  0 return null;
707    }
708    }
709   
710    /**
711    * Decodes parameters in percent-encoded URI-format
712    * ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and
713    * adds them to given Properties. NOTE: this doesn't support multiple
714    * identical keys due to the simplicity of Properties -- if you need multiples,
715    * you might want to replace the Properties with a Hashtable of Vectors or such.
716    */
 
717  0 toggle private void decodeParms( String parms, Properties p )
718    throws InterruptedException
719    {
720  0 if ( parms == null )
721  0 return;
722   
723  0 StringTokenizer st = new StringTokenizer( parms, "&" );
724  0 while ( st.hasMoreTokens())
725    {
726  0 String e = st.nextToken();
727  0 int sep = e.indexOf( '=' );
728  0 if ( sep >= 0 )
729  0 p.put( decodePercent( e.substring( 0, sep )).trim(),
730    decodePercent( e.substring( sep+1 )));
731    }
732    }
733   
734    /**
735    * Returns an error message as a HTTP response and
736    * throws InterruptedException to stop further request processing.
737    */
 
738  0 toggle private void sendError( String status, String msg ) throws InterruptedException
739    {
740  0 sendResponse( status, MIME_PLAINTEXT, null, new ByteArrayInputStream( msg.getBytes()));
741  0 throw new InterruptedException();
742    }
743   
744    /**
745    * Sends given response to the socket.
746    */
 
747  0 toggle private void sendResponse( String status, String mime, Properties header, InputStream data )
748    {
749  0 try
750    {
751  0 if ( status == null )
752  0 throw new Error( "sendResponse(): Status can't be null." );
753   
754  0 OutputStream out = mySocket.getOutputStream();
755  0 PrintWriter pw = new PrintWriter( out );
756  0 pw.print("HTTP/1.0 " + status + " \r\n");
757   
758  0 if ( mime != null )
759  0 pw.print("Content-Type: " + mime + "\r\n");
760   
761  0 if ( header == null || header.getProperty( "Date" ) == null )
762  0 pw.print( "Date: " + gmtFrmt.format( new Date()) + "\r\n");
763   
764  0 if ( header != null )
765    {
766  0 Enumeration e = header.keys();
767  0 while ( e.hasMoreElements())
768    {
769  0 String key = (String)e.nextElement();
770  0 String value = header.getProperty( key );
771  0 pw.print( key + ": " + value + "\r\n");
772    }
773    }
774   
775  0 pw.print("\r\n");
776  0 pw.flush();
777   
778  0 if ( data != null )
779    {
780  0 int pending = data.available(); // This is to support partial sends, see serveFile()
781  0 byte[] buff = new byte[2048];
782  0 while (pending>0)
783    {
784  0 int read = data.read( buff, 0, ( (pending>2048) ? 2048 : pending ));
785  0 if (read <= 0) break;
786  0 out.write( buff, 0, read );
787  0 pending -= read;
788    }
789    }
790  0 out.flush();
791  0 out.close();
792  0 if ( data != null )
793  0 data.close();
794    }
795    catch( IOException ioe )
796    {
797    // Couldn't write? No can do.
798  0 try { mySocket.close(); } catch( Throwable t ) {}
799    }
800    }
801   
802    private Socket mySocket;
803    }
804   
805    /**
806    * URL-encodes everything between "/"-characters.
807    * Encodes spaces as '%20' instead of '+'.
808    */
 
809  0 toggle private String encodeUri( String uri )
810    {
811  0 String newUri = "";
812  0 StringTokenizer st = new StringTokenizer( uri, "/ ", true );
813  0 while ( st.hasMoreTokens())
814    {
815  0 String tok = st.nextToken();
816  0 if ( tok.equals( "/" ))
817  0 newUri += "/";
818  0 else if ( tok.equals( " " ))
819  0 newUri += "%20";
820    else
821    {
822  0 newUri += URLEncoder.encode( tok );
823    // For Java 1.4 you'll want to use this instead:
824    // try { newUri += URLEncoder.encode( tok, "UTF-8" ); } catch ( java.io.UnsupportedEncodingException uee ) {}
825    }
826    }
827  0 return newUri;
828    }
829   
830    private int myTcpPort;
831    private final ServerSocket myServerSocket;
832    private Thread myThread;
833    private File myRootDir;
834   
835    // ==================================================
836    // File server code
837    // ==================================================
838   
839    /**
840    * Serves file from homeDir and its' subdirectories (only).
841    * Uses only URI, ignores all headers and HTTP parameters.
842    */
 
843  0 toggle public Response serveFile( String uri, Properties header, File homeDir,
844    boolean allowDirectoryListing )
845    {
846  0 Response res = null;
847   
848    // Make sure we won't die of an exception later
849  0 if ( !homeDir.isDirectory())
850  0 res = new Response( HTTP_INTERNALERROR, MIME_PLAINTEXT,
851    "INTERNAL ERRROR: serveFile(): given homeDir is not a directory." );
852   
853  0 if ( res == null )
854    {
855    // Remove URL arguments
856  0 uri = uri.trim().replace( File.separatorChar, '/' );
857  0 if ( uri.indexOf( '?' ) >= 0 )
858  0 uri = uri.substring(0, uri.indexOf( '?' ));
859   
860    // Prohibit getting out of current directory
861  0 if ( uri.startsWith( ".." ) || uri.endsWith( ".." ) || uri.indexOf( "../" ) >= 0 )
862  0 res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT,
863    "FORBIDDEN: Won't serve ../ for security reasons." );
864    }
865   
866  0 File f = new File( homeDir, uri );
867  0 if ( res == null && !f.exists())
868  0 res = new Response( HTTP_NOTFOUND, MIME_PLAINTEXT,
869    "Error 404, file not found." );
870   
871    // List the directory, if necessary
872  0 if ( res == null && f.isDirectory())
873    {
874    // Browsers get confused without '/' after the
875    // directory, send a redirect.
876  0 if ( !uri.endsWith( "/" ))
877    {
878  0 uri += "/";
879  0 res = new Response( HTTP_REDIRECT, MIME_HTML,
880    "<html><body>Redirected: <a href=\"" + uri + "\">" +
881    uri + "</a></body></html>");
882  0 res.addHeader( "Location", uri );
883    }
884   
885  0 if ( res == null )
886    {
887    // First try index.html and index.htm
888  0 if ( new File( f, "index.html" ).exists())
889  0 f = new File( homeDir, uri + "/index.html" );
890  0 else if ( new File( f, "index.htm" ).exists())
891  0 f = new File( homeDir, uri + "/index.htm" );
892    // No index file, list the directory if it is readable
893  0 else if ( allowDirectoryListing && f.canRead() )
894    {
895  0 String[] files = f.list();
896  0 String msg = "<html><body><h1>Directory " + uri + "</h1><br/>";
897   
898  0 if ( uri.length() > 1 )
899    {
900  0 String u = uri.substring( 0, uri.length()-1 );
901  0 int slash = u.lastIndexOf( '/' );
902  0 if ( slash >= 0 && slash < u.length())
903  0 msg += "<b><a href=\"" + uri.substring(0, slash+1) + "\">..</a></b><br/>";
904    }
905   
906  0 if (files!=null)
907    {
908  0 for ( int i=0; i<files.length; ++i )
909    {
910  0 File curFile = new File( f, files[i] );
911  0 boolean dir = curFile.isDirectory();
912  0 if ( dir )
913    {
914  0 msg += "<b>";
915  0 files[i] += "/";
916    }
917   
918  0 msg += "<a href=\"" + encodeUri( uri + files[i] ) + "\">" +
919    files[i] + "</a>";
920   
921    // Show file size
922  0 if ( curFile.isFile())
923    {
924  0 long len = curFile.length();
925  0 msg += " &nbsp;<font size=2>(";
926  0 if ( len < 1024 )
927  0 msg += len + " bytes";
928  0 else if ( len < 1024 * 1024 )
929  0 msg += len/1024 + "." + (len%1024/10%100) + " KB";
930    else
931  0 msg += len/(1024*1024) + "." + len%(1024*1024)/10%100 + " MB";
932   
933  0 msg += ")</font>";
934    }
935  0 msg += "<br/>";
936  0 if ( dir ) msg += "</b>";
937    }
938    }
939  0 msg += "</body></html>";
940  0 res = new Response( HTTP_OK, MIME_HTML, msg );
941    }
942    else
943    {
944  0 res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT,
945    "FORBIDDEN: No directory listing." );
946    }
947    }
948    }
949   
950  0 try
951    {
952  0 if ( res == null )
953    {
954    // Get MIME type from file name extension, if possible
955  0 String mime = null;
956  0 int dot = f.getCanonicalPath().lastIndexOf( '.' );
957  0 if ( dot >= 0 )
958  0 mime = (String)theMimeTypes.get( f.getCanonicalPath().substring( dot + 1 ).toLowerCase());
959  0 if ( mime == null )
960  0 mime = MIME_DEFAULT_BINARY;
961   
962    // Calculate etag
963  0 String etag = Integer.toHexString((f.getAbsolutePath() + f.lastModified() + "" + f.length()).hashCode());
964   
965    // Support (simple) skipping:
966  0 long startFrom = 0;
967  0 long endAt = -1;
968  0 String range = header.getProperty( "range" );
969  0 if ( range != null )
970    {
971  0 if ( range.startsWith( "bytes=" ))
972    {
973  0 range = range.substring( "bytes=".length());
974  0 int minus = range.indexOf( '-' );
975  0 try {
976  0 if ( minus > 0 )
977    {
978  0 startFrom = Long.parseLong( range.substring( 0, minus ));
979  0 endAt = Long.parseLong( range.substring( minus+1 ));
980    }
981    }
982    catch ( NumberFormatException nfe ) {}
983    }
984    }
985   
986    // Change return code and add Content-Range header when skipping is requested
987  0 long fileLen = f.length();
988  0 if (range != null && startFrom >= 0)
989    {
990  0 if ( startFrom >= fileLen)
991    {
992  0 res = new Response( HTTP_RANGE_NOT_SATISFIABLE, MIME_PLAINTEXT, "" );
993  0 res.addHeader( "Content-Range", "bytes 0-0/" + fileLen);
994  0 res.addHeader( "ETag", etag);
995    }
996    else
997    {
998  0 if ( endAt < 0 )
999  0 endAt = fileLen-1;
1000  0 long newLen = endAt - startFrom + 1;
1001  0 if ( newLen < 0 ) newLen = 0;
1002   
1003  0 final long dataLen = newLen;
1004  0 FileInputStream fis = new FileInputStream( f ) {
 
1005  0 toggle public int available() throws IOException { return (int)dataLen; }
1006    };
1007  0 fis.skip( startFrom );
1008   
1009  0 res = new Response( HTTP_PARTIALCONTENT, mime, fis );
1010  0 res.addHeader( "Content-Length", "" + dataLen);
1011  0 res.addHeader( "Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
1012  0 res.addHeader( "ETag", etag);
1013    }
1014    }
1015    else
1016    {
1017  0 res = new Response( HTTP_OK, mime, new FileInputStream( f ));
1018  0 res.addHeader( "Content-Length", "" + fileLen);
1019  0 res.addHeader( "ETag", etag);
1020    }
1021    }
1022    }
1023    catch( IOException ioe )
1024    {
1025  0 res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed." );
1026    }
1027   
1028  0 res.addHeader( "Accept-Ranges", "bytes"); // Announce that the file server accepts partial content requestes
1029  0 return res;
1030    }
1031   
1032    /**
1033    * Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE
1034    */
1035    private static Hashtable theMimeTypes = new Hashtable();
 
1036  1 toggle static
1037    {
1038  1 StringTokenizer st = new StringTokenizer(
1039    "css text/css "+
1040    "htm text/html "+
1041    "html text/html "+
1042    "xml text/xml "+
1043    "txt text/plain "+
1044    "asc text/plain "+
1045    "gif image/gif "+
1046    "jpg image/jpeg "+
1047    "jpeg image/jpeg "+
1048    "png image/png "+
1049    "mp3 audio/mpeg "+
1050    "m3u audio/mpeg-url " +
1051    "mp4 video/mp4 " +
1052    "ogv video/ogg " +
1053    "flv video/x-flv " +
1054    "mov video/quicktime " +
1055    "swf application/x-shockwave-flash " +
1056    "js application/javascript "+
1057    "pdf application/pdf "+
1058    "doc application/msword "+
1059    "ogg application/x-ogg "+
1060    "zip application/octet-stream "+
1061    "exe application/octet-stream "+
1062    "class application/octet-stream " );
1063  25 while ( st.hasMoreTokens())
1064  24 theMimeTypes.put( st.nextToken(), st.nextToken());
1065    }
1066   
1067    /**
1068    * GMT date formatter
1069    */
1070    private static java.text.SimpleDateFormat gmtFrmt;
 
1071  1 toggle static
1072    {
1073  1 gmtFrmt = new java.text.SimpleDateFormat( "E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
1074  1 gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));
1075    }
1076   
1077    /**
1078    * The distribution licence
1079    */
1080    private static final String LICENCE =
1081    "Copyright (C) 2001,2005-2011 by Jarno Elonen <elonen@iki.fi>\n"+
1082    "and Copyright (C) 2010 by Konstantinos Togias <info@ktogias.gr>\n"+
1083    "\n"+
1084    "Redistribution and use in source and binary forms, with or without\n"+
1085    "modification, are permitted provided that the following conditions\n"+
1086    "are met:\n"+
1087    "\n"+
1088    "Redistributions of source code must retain the above copyright notice,\n"+
1089    "this list of conditions and the following disclaimer. Redistributions in\n"+
1090    "binary form must reproduce the above copyright notice, this list of\n"+
1091    "conditions and the following disclaimer in the documentation and/or other\n"+
1092    "materials provided with the distribution. The name of the author may not\n"+
1093    "be used to endorse or promote products derived from this software without\n"+
1094    "specific prior written permission. \n"+
1095    " \n"+
1096    "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"+
1097    "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"+
1098    "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"+
1099    "IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"+
1100    "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n"+
1101    "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"+
1102    "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"+
1103    "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"+
1104    "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"+
1105    "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.";
1106    }