acouchi 0.0.1

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