NanoHTTPD.java revision bc0de3e38a4edadd6704a6c8ccb0c5ee738b8f54
1package fi.iki.elonen; 2 3import java.io.*; 4import java.net.*; 5import java.nio.ByteBuffer; 6import java.nio.channels.FileChannel; 7import java.text.SimpleDateFormat; 8import java.util.*; 9 10/** 11 * A simple, tiny, nicely embeddable HTTP server in Java 12 * <p/> 13 * <p/> 14 * NanoHTTPD 15 * <p></p>Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias</p> 16 * <p/> 17 * <p/> 18 * <b>Features + limitations: </b> 19 * <ul> 20 * <p/> 21 * <li>Only one Java file</li> 22 * <li>Java 5 compatible</li> 23 * <li>Released as open source, Modified BSD licence</li> 24 * <li>No fixed config files, logging, authorization etc. (Implement yourself if you need them.)</li> 25 * <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT support in 1.25)</li> 26 * <li>Supports both dynamic content and file serving</li> 27 * <li>Supports file upload (since version 1.2, 2010)</li> 28 * <li>Supports partial content (streaming)</li> 29 * <li>Supports ETags</li> 30 * <li>Never caches anything</li> 31 * <li>Doesn't limit bandwidth, request time or simultaneous connections</li> 32 * <li>Default code serves files and shows all HTTP parameters and headers</li> 33 * <li>File server supports directory listing, index.html and index.htm</li> 34 * <li>File server supports partial content (streaming)</li> 35 * <li>File server supports ETags</li> 36 * <li>File server does the 301 redirection trick for directories without '/'</li> 37 * <li>File server supports simple skipping for files (continue download)</li> 38 * <li>File server serves also very long files without memory overhead</li> 39 * <li>Contains a built-in list of most common mime types</li> 40 * <li>All header names are converted lowercase so they don't vary between browsers/clients</li> 41 * <p/> 42 * </ul> 43 * <p/> 44 * <p/> 45 * <b>How to use: </b> 46 * <ul> 47 * <p/> 48 * <li>Subclass and implement serve() and embed to your own program</li> 49 * <p/> 50 * </ul> 51 * <p/> 52 * See the separate "LICENSE.md" file for the distribution license (Modified BSD licence) 53 */ 54public abstract class NanoHTTPD { 55 /** 56 * Common mime type for dynamic content: plain text 57 */ 58 public static final String MIME_PLAINTEXT = "text/plain"; 59 /** 60 * Common mime type for dynamic content: html 61 */ 62 public static final String MIME_HTML = "text/html"; 63 /** 64 * Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing. 65 */ 66 private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING"; 67 private final String hostname; 68 private final int myPort; 69 private ServerSocket myServerSocket; 70 private Thread myThread; 71 /** 72 * Pluggable strategy for asynchronously executing requests. 73 */ 74 private AsyncRunner asyncRunner; 75 /** 76 * Pluggable strategy for creating and cleaning up temporary files. 77 */ 78 private TempFileManagerFactory tempFileManagerFactory; 79 80 /** 81 * Constructs an HTTP server on given port. 82 */ 83 public NanoHTTPD(int port) { 84 this(null, port); 85 } 86 87 /** 88 * Constructs an HTTP server on given hostname and port. 89 */ 90 public NanoHTTPD(String hostname, int port) { 91 this.hostname = hostname; 92 this.myPort = port; 93 setTempFileManagerFactory(new DefaultTempFileManagerFactory()); 94 setAsyncRunner(new DefaultAsyncRunner()); 95 } 96 97 private static final void safeClose(ServerSocket serverSocket) { 98 if (serverSocket != null) { 99 try { 100 serverSocket.close(); 101 } catch (IOException e) { 102 } 103 } 104 } 105 106 private static final void safeClose(Socket socket) { 107 if (socket != null) { 108 try { 109 socket.close(); 110 } catch (IOException e) { 111 } 112 } 113 } 114 115 private static final void safeClose(Closeable closeable) { 116 if (closeable != null) { 117 try { 118 closeable.close(); 119 } catch (IOException e) { 120 } 121 } 122 } 123 124 /** 125 * Start the server. 126 * 127 * @throws IOException if the socket is in use. 128 */ 129 public void start() throws IOException { 130 myServerSocket = new ServerSocket(); 131 myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); 132 133 myThread = new Thread(new Runnable() { 134 @Override 135 public void run() { 136 do { 137 try { 138 final Socket finalAccept = myServerSocket.accept(); 139 final InputStream inputStream = finalAccept.getInputStream(); 140 if (inputStream == null) { 141 safeClose(finalAccept); 142 } else { 143 asyncRunner.exec(new Runnable() { 144 @Override 145 public void run() { 146 OutputStream outputStream = null; 147 try { 148 outputStream = finalAccept.getOutputStream(); 149 TempFileManager tempFileManager = tempFileManagerFactory.create(); 150 ParsingHTTPSession session = new ParsingHTTPSession(tempFileManager, inputStream, outputStream); 151 while (!finalAccept.isClosed()) { 152 session.execute(); 153 } 154 } catch (Exception e) { 155 // When the socket is closed by the client, we throw our own SocketException 156 // to break the "keep alive" loop above. 157 if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage()))) { 158 e.printStackTrace(); 159 } 160 } finally { 161 safeClose(outputStream); 162 safeClose(inputStream); 163 safeClose(finalAccept); 164 } 165 } 166 }); 167 } 168 } catch (IOException e) { 169 } 170 } while (!myServerSocket.isClosed()); 171 } 172 }); 173 myThread.setDaemon(true); 174 myThread.setName("NanoHttpd Main Listener"); 175 myThread.start(); 176 } 177 178 /** 179 * Stop the server. 180 */ 181 public void stop() { 182 try { 183 safeClose(myServerSocket); 184 myThread.join(); 185 } catch (Exception e) { 186 e.printStackTrace(); 187 } 188 } 189 190 191 public final int getListeningPort() { 192 return myServerSocket == null ? -1 : myServerSocket.getLocalPort(); 193 } 194 195 public final boolean wasStarted() { 196 return myServerSocket != null && myThread != null; 197 } 198 199 public final boolean isAlive() { 200 return wasStarted() && !myServerSocket.isClosed() && myThread.isAlive(); 201 } 202 203 /** 204 * Override this to customize the server. 205 * <p/> 206 * <p/> 207 * (By default, this delegates to serveFile() and allows directory listing.) 208 * 209 * @param uri Percent-decoded URI without parameters, for example "/index.cgi" 210 * @param method "GET", "POST" etc. 211 * @param parms Parsed, percent decoded parameters from URI and, in case of POST, data. 212 * @param headers Header entries, percent decoded 213 * @return HTTP response, see class Response for details 214 */ 215 @Deprecated 216 public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, 217 Map<String, String> files) { 218 return new Response(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found"); 219 } 220 221 /** 222 * Override this to customize the server. 223 * <p/> 224 * <p/> 225 * (By default, this delegates to serveFile() and allows directory listing.) 226 * 227 * @param session The HTTP session 228 * @return HTTP response, see class Response for details 229 */ 230 public Response serve(HTTPSession session) { 231 Map<String, String> files = new HashMap<String, String>(); 232 Method method = session.getMethod(); 233 if (Method.PUT.equals(method) || Method.POST.equals(method)) { 234 try { 235 session.parseBody(files); 236 } catch (IOException ioe) { 237 return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); 238 } catch (ResponseException re) { 239 return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); 240 } 241 } 242 243 return serve(session.getUri(), method, session.getHeaders(), session.getParms(), files); 244 } 245 246 /** 247 * Decode percent encoded <code>String</code> values. 248 * 249 * @param str the percent encoded <code>String</code> 250 * @return expanded form of the input, for example "foo%20bar" becomes "foo bar" 251 */ 252 protected String decodePercent(String str) { 253 String decoded = null; 254 try { 255 decoded = URLDecoder.decode(str, "UTF8"); 256 } catch (UnsupportedEncodingException ignored) { 257 } 258 return decoded; 259 } 260 261 /** 262 * Decode parameters from a URL, handing the case where a single parameter name might have been 263 * supplied several times, by return lists of values. In general these lists will contain a single 264 * element. 265 * 266 * @param parms original <b>NanoHttpd</b> parameters values, as passed to the <code>serve()</code> method. 267 * @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied). 268 */ 269 protected Map<String, List<String>> decodeParameters(Map<String, String> parms) { 270 return this.decodeParameters(parms.get(QUERY_STRING_PARAMETER)); 271 } 272 273 /** 274 * Decode parameters from a URL, handing the case where a single parameter name might have been 275 * supplied several times, by return lists of values. In general these lists will contain a single 276 * element. 277 * 278 * @param queryString a query string pulled from the URL. 279 * @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied). 280 */ 281 protected Map<String, List<String>> decodeParameters(String queryString) { 282 Map<String, List<String>> parms = new HashMap<String, List<String>>(); 283 if (queryString != null) { 284 StringTokenizer st = new StringTokenizer(queryString, "&"); 285 while (st.hasMoreTokens()) { 286 String e = st.nextToken(); 287 int sep = e.indexOf('='); 288 String propertyName = (sep >= 0) ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim(); 289 if (!parms.containsKey(propertyName)) { 290 parms.put(propertyName, new ArrayList<String>()); 291 } 292 String propertyValue = (sep >= 0) ? decodePercent(e.substring(sep + 1)) : null; 293 if (propertyValue != null) { 294 parms.get(propertyName).add(propertyValue); 295 } 296 } 297 } 298 return parms; 299 } 300 301 // ------------------------------------------------------------------------------- // 302 // 303 // Threading Strategy. 304 // 305 // ------------------------------------------------------------------------------- // 306 307 /** 308 * Pluggable strategy for asynchronously executing requests. 309 * 310 * @param asyncRunner new strategy for handling threads. 311 */ 312 public void setAsyncRunner(AsyncRunner asyncRunner) { 313 this.asyncRunner = asyncRunner; 314 } 315 316 // ------------------------------------------------------------------------------- // 317 // 318 // Temp file handling strategy. 319 // 320 // ------------------------------------------------------------------------------- // 321 322 /** 323 * Pluggable strategy for creating and cleaning up temporary files. 324 * 325 * @param tempFileManagerFactory new strategy for handling temp files. 326 */ 327 public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) { 328 this.tempFileManagerFactory = tempFileManagerFactory; 329 } 330 331 /** 332 * HTTP Request methods, with the ability to decode a <code>String</code> back to its enum value. 333 */ 334 public enum Method { 335 GET, PUT, POST, DELETE, HEAD; 336 337 static Method lookup(String method) { 338 for (Method m : Method.values()) { 339 if (m.toString().equalsIgnoreCase(method)) { 340 return m; 341 } 342 } 343 return null; 344 } 345 } 346 347 /** 348 * Pluggable strategy for asynchronously executing requests. 349 */ 350 public interface AsyncRunner { 351 void exec(Runnable code); 352 } 353 354 /** 355 * Factory to create temp file managers. 356 */ 357 public interface TempFileManagerFactory { 358 TempFileManager create(); 359 } 360 361 // ------------------------------------------------------------------------------- // 362 363 /** 364 * Temp file manager. 365 * <p/> 366 * <p>Temp file managers are created 1-to-1 with incoming requests, to create and cleanup 367 * temporary files created as a result of handling the request.</p> 368 */ 369 public interface TempFileManager { 370 TempFile createTempFile() throws Exception; 371 372 void clear(); 373 } 374 375 /** 376 * A temp file. 377 * <p/> 378 * <p>Temp files are responsible for managing the actual temporary storage and cleaning 379 * themselves up when no longer needed.</p> 380 */ 381 public interface TempFile { 382 OutputStream open() throws Exception; 383 384 void delete() throws Exception; 385 386 String getName(); 387 } 388 389 /** 390 * Default threading strategy for NanoHttpd. 391 * <p/> 392 * <p>By default, the server spawns a new Thread for every incoming request. These are set 393 * to <i>daemon</i> status, and named according to the request number. The name is 394 * useful when profiling the application.</p> 395 */ 396 public static class DefaultAsyncRunner implements AsyncRunner { 397 private long requestCount; 398 399 @Override 400 public void exec(Runnable code) { 401 ++requestCount; 402 Thread t = new Thread(code); 403 t.setDaemon(true); 404 t.setName("NanoHttpd Request Processor (#" + requestCount + ")"); 405 t.start(); 406 } 407 } 408 409 /** 410 * Default strategy for creating and cleaning up temporary files. 411 * <p/> 412 * <p></p>This class stores its files in the standard location (that is, 413 * wherever <code>java.io.tmpdir</code> points to). Files are added 414 * to an internal list, and deleted when no longer needed (that is, 415 * when <code>clear()</code> is invoked at the end of processing a 416 * request).</p> 417 */ 418 public static class DefaultTempFileManager implements TempFileManager { 419 private final String tmpdir; 420 private final List<TempFile> tempFiles; 421 422 public DefaultTempFileManager() { 423 tmpdir = System.getProperty("java.io.tmpdir"); 424 tempFiles = new ArrayList<TempFile>(); 425 } 426 427 @Override 428 public TempFile createTempFile() throws Exception { 429 DefaultTempFile tempFile = new DefaultTempFile(tmpdir); 430 tempFiles.add(tempFile); 431 return tempFile; 432 } 433 434 @Override 435 public void clear() { 436 for (TempFile file : tempFiles) { 437 try { 438 file.delete(); 439 } catch (Exception ignored) { 440 } 441 } 442 tempFiles.clear(); 443 } 444 } 445 446 /** 447 * Default strategy for creating and cleaning up temporary files. 448 * <p/> 449 * <p></p></[>By default, files are created by <code>File.createTempFile()</code> in 450 * the directory specified.</p> 451 */ 452 public static class DefaultTempFile implements TempFile { 453 private File file; 454 private OutputStream fstream; 455 456 public DefaultTempFile(String tempdir) throws IOException { 457 file = File.createTempFile("NanoHTTPD-", "", new File(tempdir)); 458 fstream = new FileOutputStream(file); 459 } 460 461 @Override 462 public OutputStream open() throws Exception { 463 return fstream; 464 } 465 466 @Override 467 public void delete() throws Exception { 468 safeClose(fstream); 469 file.delete(); 470 } 471 472 @Override 473 public String getName() { 474 return file.getAbsolutePath(); 475 } 476 } 477 478 /** 479 * HTTP response. Return one of these from serve(). 480 */ 481 public static class Response { 482 /** 483 * HTTP status code after processing, e.g. "200 OK", HTTP_OK 484 */ 485 private Status status; 486 /** 487 * MIME type of content, e.g. "text/html" 488 */ 489 private String mimeType; 490 /** 491 * Data of the response, may be null. 492 */ 493 private InputStream data; 494 /** 495 * Headers for the HTTP response. Use addHeader() to add lines. 496 */ 497 private Map<String, String> header = new HashMap<String, String>(); 498 /** 499 * The request method that spawned this response. 500 */ 501 private Method requestMethod; 502 /** 503 * Use chunkedTransfer 504 */ 505 private boolean chunkedTransfer; 506 507 /** 508 * Default constructor: response = HTTP_OK, mime = MIME_HTML and your supplied message 509 */ 510 public Response(String msg) { 511 this(Status.OK, MIME_HTML, msg); 512 } 513 514 /** 515 * Basic constructor. 516 */ 517 public Response(Status status, String mimeType, InputStream data) { 518 this.status = status; 519 this.mimeType = mimeType; 520 this.data = data; 521 } 522 523 /** 524 * Convenience method that makes an InputStream out of given text. 525 */ 526 public Response(Status status, String mimeType, String txt) { 527 this.status = status; 528 this.mimeType = mimeType; 529 try { 530 this.data = txt != null ? new ByteArrayInputStream(txt.getBytes("UTF-8")) : null; 531 } catch (java.io.UnsupportedEncodingException uee) { 532 uee.printStackTrace(); 533 } 534 } 535 536 /** 537 * Adds given line to the header. 538 */ 539 public void addHeader(String name, String value) { 540 header.put(name, value); 541 } 542 543 /** 544 * Sends given response to the socket. 545 */ 546 private void send(OutputStream outputStream) { 547 String mime = mimeType; 548 SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); 549 gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT")); 550 551 try { 552 if (status == null) { 553 throw new Error("sendResponse(): Status can't be null."); 554 } 555 PrintWriter pw = new PrintWriter(outputStream); 556 pw.print("HTTP/1.1 " + status.getDescription() + " \r\n"); 557 558 if (mime != null) { 559 pw.print("Content-Type: " + mime + "\r\n"); 560 } 561 562 if (header == null || header.get("Date") == null) { 563 pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n"); 564 } 565 566 if (header != null) { 567 for (String key : header.keySet()) { 568 String value = header.get(key); 569 pw.print(key + ": " + value + "\r\n"); 570 } 571 } 572 573 pw.print("Connection: keep-alive\r\n"); 574 575 if (requestMethod != Method.HEAD && chunkedTransfer) { 576 sendAsChunked(outputStream, pw); 577 } else { 578 sendAsFixedLength(outputStream, pw); 579 } 580 outputStream.flush(); 581 safeClose(data); 582 } catch (IOException ioe) { 583 // Couldn't write? No can do. 584 } 585 } 586 587 private void sendAsChunked(OutputStream outputStream, PrintWriter pw) throws IOException { 588 pw.print("Transfer-Encoding: chunked\r\n"); 589 pw.print("\r\n"); 590 pw.flush(); 591 int BUFFER_SIZE = 16 * 1024; 592 byte[] CRLF = "\r\n".getBytes(); 593 byte[] buff = new byte[BUFFER_SIZE]; 594 int read; 595 while ((read = data.read(buff)) > 0) { 596 outputStream.write(String.format("%x\r\n", read).getBytes()); 597 outputStream.write(buff, 0, read); 598 outputStream.write(CRLF); 599 } 600 outputStream.write(String.format("0\r\n\r\n").getBytes()); 601 } 602 603 private void sendAsFixedLength(OutputStream outputStream, PrintWriter pw) throws IOException { 604 int pending = data != null ? data.available() : 0; // This is to support partial sends, see serveFile() 605 pw.print("Content-Length: "+pending+"\r\n"); 606 607 pw.print("\r\n"); 608 pw.flush(); 609 610 if (requestMethod != Method.HEAD && data != null) { 611 int BUFFER_SIZE = 16 * 1024; 612 byte[] buff = new byte[BUFFER_SIZE]; 613 while (pending > 0) { 614 int read = data.read(buff, 0, ((pending > BUFFER_SIZE) ? BUFFER_SIZE : pending)); 615 if (read <= 0) { 616 break; 617 } 618 outputStream.write(buff, 0, read); 619 620 pending -= read; 621 } 622 } 623 } 624 625 public Status getStatus() { 626 return status; 627 } 628 629 public void setStatus(Status status) { 630 this.status = status; 631 } 632 633 public String getMimeType() { 634 return mimeType; 635 } 636 637 public void setMimeType(String mimeType) { 638 this.mimeType = mimeType; 639 } 640 641 public InputStream getData() { 642 return data; 643 } 644 645 public void setData(InputStream data) { 646 this.data = data; 647 } 648 649 public Method getRequestMethod() { 650 return requestMethod; 651 } 652 653 public void setRequestMethod(Method requestMethod) { 654 this.requestMethod = requestMethod; 655 } 656 657 public void setChunkedTransfer(boolean chunkedTransfer) { 658 this.chunkedTransfer = chunkedTransfer; 659 } 660 661 /** 662 * Some HTTP response status codes 663 */ 664 public enum Status { 665 OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), PARTIAL_CONTENT(206, "Partial Content"), REDIRECT(301, 666 "Moved Permanently"), NOT_MODIFIED(304, "Not Modified"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401, 667 "Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), RANGE_NOT_SATISFIABLE(416, 668 "Requested Range Not Satisfiable"), INTERNAL_ERROR(500, "Internal Server Error"); 669 private final int requestStatus; 670 private final String description; 671 672 Status(int requestStatus, String description) { 673 this.requestStatus = requestStatus; 674 this.description = description; 675 } 676 677 public int getRequestStatus() { 678 return this.requestStatus; 679 } 680 681 public String getDescription() { 682 return "" + this.requestStatus + " " + description; 683 } 684 } 685 } 686 687 public static final class ResponseException extends Exception { 688 689 private final Response.Status status; 690 691 public ResponseException(Response.Status status, String message) { 692 super(message); 693 this.status = status; 694 } 695 696 public ResponseException(Response.Status status, String message, Exception e) { 697 super(message, e); 698 this.status = status; 699 } 700 701 public Response.Status getStatus() { 702 return status; 703 } 704 } 705 706 /** 707 * Default strategy for creating and cleaning up temporary files. 708 */ 709 private class DefaultTempFileManagerFactory implements TempFileManagerFactory { 710 @Override 711 public TempFileManager create() { 712 return new DefaultTempFileManager(); 713 } 714 } 715 716 /** 717 * Handles one session, i.e. parses the HTTP request and returns the response. 718 */ 719 public interface HTTPSession { 720 void execute() throws IOException; 721 722 Map<String, String> getParms(); 723 724 Map<String, String> getHeaders(); 725 726 /** 727 * @return the path part of the URL. 728 */ 729 String getUri(); 730 731 Method getMethod(); 732 733 InputStream getInputStream(); 734 735 CookieHandler getCookies(); 736 737 /** 738 * Adds the files in the request body to the files map. 739 * @arg files - map to modify 740 */ 741 void parseBody(Map<String, String> files) throws IOException, ResponseException; 742 } 743 744 protected class ParsingHTTPSession implements HTTPSession { 745 int BUFSIZE = 8192; 746 747 private final TempFileManager tempFileManager; 748 private final OutputStream outputStream; 749 private InputStream inputStream; 750 private int splitbyte; 751 private int rlen; 752 private String uri; 753 private Method method; 754 private Map<String, String> parms; 755 private Map<String, String> headers; 756 private CookieHandler cookies; 757 758 public ParsingHTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) { 759 this.tempFileManager = tempFileManager; 760 this.inputStream = inputStream; 761 this.outputStream = outputStream; 762 } 763 764 @Override 765 public void execute() throws IOException { 766 try { 767 // Read the first 8192 bytes. 768 // The full header should fit in here. 769 // Apache's default header limit is 8KB. 770 // Do NOT assume that a single read will get the entire header at once! 771 byte[] buf = new byte[BUFSIZE]; 772 splitbyte = 0; 773 rlen = 0; 774 { 775 int read = inputStream.read(buf, 0, BUFSIZE); 776 if (read == -1) { 777 // socket was been closed 778 throw new SocketException("NanoHttpd Shutdown"); 779 } 780 while (read > 0) { 781 rlen += read; 782 splitbyte = findHeaderEnd(buf, rlen); 783 if (splitbyte > 0) 784 break; 785 read = inputStream.read(buf, rlen, BUFSIZE - rlen); 786 } 787 } 788 789 if (splitbyte < rlen) { 790 ByteArrayInputStream splitInputStream = new ByteArrayInputStream(buf, splitbyte, rlen - splitbyte); 791 SequenceInputStream sequenceInputStream = new SequenceInputStream(splitInputStream, inputStream); 792 inputStream = sequenceInputStream; 793 } 794 795 parms = new HashMap<String, String>(); 796 headers = new HashMap<String, String>(); 797 798 // Create a BufferedReader for parsing the header. 799 BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen))); 800 801 // Decode the header into parms and header java properties 802 Map<String, String> pre = new HashMap<String, String>(); 803 decodeHeader(hin, pre, parms, headers); 804 805 method = Method.lookup(pre.get("method")); 806 if (method == null) { 807 throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error."); 808 } 809 810 uri = pre.get("uri"); 811 812 cookies = new CookieHandler(headers); 813 814 // Ok, now do the serve() 815 Response r = serve(this); 816 if (r == null) { 817 throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response."); 818 } else { 819 cookies.unloadQueue(r); 820 r.setRequestMethod(method); 821 r.send(outputStream); 822 } 823 } catch (SocketException e) { 824 // throw it out to close socket object (finalAccept) 825 throw e; 826 } catch (IOException ioe) { 827 Response r = new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); 828 r.send(outputStream); 829 safeClose(outputStream); 830 } catch (ResponseException re) { 831 Response r = new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); 832 r.send(outputStream); 833 safeClose(outputStream); 834 } finally { 835 tempFileManager.clear(); 836 } 837 } 838 839 @Override 840 public void parseBody(Map<String, String> files) throws IOException, ResponseException { 841 RandomAccessFile randomAccessFile = null; 842 BufferedReader in = null; 843 try { 844 845 randomAccessFile = getTmpBucket(); 846 847 long size; 848 if (headers.containsKey("content-length")) { 849 size = Integer.parseInt(headers.get("content-length")); 850 } else if (splitbyte < rlen) { 851 size = rlen - splitbyte; 852 } else { 853 size = 0; 854 } 855 856 // Now read all the body and write it to f 857 byte[] buf = new byte[512]; 858 while (rlen >= 0 && size > 0) { 859 rlen = inputStream.read(buf, 0, 512); 860 size -= rlen; 861 if (rlen > 0) { 862 randomAccessFile.write(buf, 0, rlen); 863 } 864 } 865 866 // Get the raw body as a byte [] 867 ByteBuffer fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length()); 868 randomAccessFile.seek(0); 869 870 // Create a BufferedReader for easily reading it as string. 871 InputStream bin = new FileInputStream(randomAccessFile.getFD()); 872 in = new BufferedReader(new InputStreamReader(bin)); 873 874 // If the method is POST, there may be parameters 875 // in data section, too, read it: 876 if (Method.POST.equals(method)) { 877 String contentType = ""; 878 String contentTypeHeader = headers.get("content-type"); 879 880 StringTokenizer st = null; 881 if (contentTypeHeader != null) { 882 st = new StringTokenizer(contentTypeHeader, ",; "); 883 if (st.hasMoreTokens()) { 884 contentType = st.nextToken(); 885 } 886 } 887 888 if ("multipart/form-data".equalsIgnoreCase(contentType)) { 889 // Handle multipart/form-data 890 if (!st.hasMoreTokens()) { 891 throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html"); 892 } 893 894 String boundaryStartString = "boundary="; 895 int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length(); 896 String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length()); 897 if (boundary.startsWith("\"") && boundary.endsWith("\"")) { 898 boundary = boundary.substring(1, boundary.length() - 1); 899 } 900 901 decodeMultipartData(boundary, fbuf, in, parms, files); 902 } else { 903 // Handle application/x-www-form-urlencoded 904 String postLine = ""; 905 char pbuf[] = new char[512]; 906 int read = in.read(pbuf); 907 while (read >= 0 && !postLine.endsWith("\r\n")) { 908 postLine += String.valueOf(pbuf, 0, read); 909 read = in.read(pbuf); 910 } 911 postLine = postLine.trim(); 912 decodeParms(postLine, parms); 913 } 914 } else if (Method.PUT.equals(method)) { 915 files.put("content", saveTmpFile(fbuf, 0, fbuf.limit())); 916 } 917 } finally { 918 safeClose(randomAccessFile); 919 safeClose(in); 920 } 921 } 922 923 /** 924 * Decodes the sent headers and loads the data into Key/value pairs 925 */ 926 private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers) 927 throws ResponseException { 928 try { 929 // Read the request line 930 String inLine = in.readLine(); 931 if (inLine == null) { 932 return; 933 } 934 935 StringTokenizer st = new StringTokenizer(inLine); 936 if (!st.hasMoreTokens()) { 937 throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html"); 938 } 939 940 pre.put("method", st.nextToken()); 941 942 if (!st.hasMoreTokens()) { 943 throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html"); 944 } 945 946 String uri = st.nextToken(); 947 948 // Decode parameters from the URI 949 int qmi = uri.indexOf('?'); 950 if (qmi >= 0) { 951 decodeParms(uri.substring(qmi + 1), parms); 952 uri = decodePercent(uri.substring(0, qmi)); 953 } else { 954 uri = decodePercent(uri); 955 } 956 957 // If there's another token, it's protocol version, 958 // followed by HTTP headers. Ignore version but parse headers. 959 // NOTE: this now forces header names lowercase since they are 960 // case insensitive and vary by client. 961 if (st.hasMoreTokens()) { 962 String line = in.readLine(); 963 while (line != null && line.trim().length() > 0) { 964 int p = line.indexOf(':'); 965 if (p >= 0) 966 headers.put(line.substring(0, p).trim().toLowerCase(), line.substring(p + 1).trim()); 967 line = in.readLine(); 968 } 969 } 970 971 pre.put("uri", uri); 972 } catch (IOException ioe) { 973 throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe); 974 } 975 } 976 977 /** 978 * Decodes the Multipart Body data and put it into Key/Value pairs. 979 */ 980 private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms, 981 Map<String, String> files) throws ResponseException { 982 try { 983 int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes()); 984 int boundarycount = 1; 985 String mpline = in.readLine(); 986 while (mpline != null) { 987 if (!mpline.contains(boundary)) { 988 throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html"); 989 } 990 boundarycount++; 991 Map<String, String> item = new HashMap<String, String>(); 992 mpline = in.readLine(); 993 while (mpline != null && mpline.trim().length() > 0) { 994 int p = mpline.indexOf(':'); 995 if (p != -1) { 996 item.put(mpline.substring(0, p).trim().toLowerCase(), mpline.substring(p + 1).trim()); 997 } 998 mpline = in.readLine(); 999 } 1000 if (mpline != null) { 1001 String contentDisposition = item.get("content-disposition"); 1002 if (contentDisposition == null) { 1003 throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html"); 1004 } 1005 StringTokenizer st = new StringTokenizer(contentDisposition, "; "); 1006 Map<String, String> disposition = new HashMap<String, String>(); 1007 while (st.hasMoreTokens()) { 1008 String token = st.nextToken(); 1009 int p = token.indexOf('='); 1010 if (p != -1) { 1011 disposition.put(token.substring(0, p).trim().toLowerCase(), token.substring(p + 1).trim()); 1012 } 1013 } 1014 String pname = disposition.get("name"); 1015 pname = pname.substring(1, pname.length() - 1); 1016 1017 String value = ""; 1018 if (item.get("content-type") == null) { 1019 while (mpline != null && !mpline.contains(boundary)) { 1020 mpline = in.readLine(); 1021 if (mpline != null) { 1022 int d = mpline.indexOf(boundary); 1023 if (d == -1) { 1024 value += mpline; 1025 } else { 1026 value += mpline.substring(0, d - 2); 1027 } 1028 } 1029 } 1030 } else { 1031 if (boundarycount > bpositions.length) { 1032 throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request"); 1033 } 1034 int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]); 1035 String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4); 1036 files.put(pname, path); 1037 value = disposition.get("filename"); 1038 value = value.substring(1, value.length() - 1); 1039 do { 1040 mpline = in.readLine(); 1041 } while (mpline != null && !mpline.contains(boundary)); 1042 } 1043 parms.put(pname, value); 1044 } 1045 } 1046 } catch (IOException ioe) { 1047 throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe); 1048 } 1049 } 1050 1051 /** 1052 * Find byte index separating header from body. It must be the last byte of the first two sequential new lines. 1053 */ 1054 private int findHeaderEnd(final byte[] buf, int rlen) { 1055 int splitbyte = 0; 1056 while (splitbyte + 3 < rlen) { 1057 if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') { 1058 return splitbyte + 4; 1059 } 1060 splitbyte++; 1061 } 1062 return 0; 1063 } 1064 1065 /** 1066 * Find the byte positions where multipart boundaries start. 1067 */ 1068 private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) { 1069 int matchcount = 0; 1070 int matchbyte = -1; 1071 List<Integer> matchbytes = new ArrayList<Integer>(); 1072 for (int i = 0; i < b.limit(); i++) { 1073 if (b.get(i) == boundary[matchcount]) { 1074 if (matchcount == 0) 1075 matchbyte = i; 1076 matchcount++; 1077 if (matchcount == boundary.length) { 1078 matchbytes.add(matchbyte); 1079 matchcount = 0; 1080 matchbyte = -1; 1081 } 1082 } else { 1083 i -= matchcount; 1084 matchcount = 0; 1085 matchbyte = -1; 1086 } 1087 } 1088 int[] ret = new int[matchbytes.size()]; 1089 for (int i = 0; i < ret.length; i++) { 1090 ret[i] = matchbytes.get(i); 1091 } 1092 return ret; 1093 } 1094 1095 /** 1096 * Retrieves the content of a sent file and saves it to a temporary file. The full path to the saved file is returned. 1097 */ 1098 private String saveTmpFile(ByteBuffer b, int offset, int len) { 1099 String path = ""; 1100 if (len > 0) { 1101 FileOutputStream fileOutputStream = null; 1102 try { 1103 TempFile tempFile = tempFileManager.createTempFile(); 1104 ByteBuffer src = b.duplicate(); 1105 fileOutputStream = new FileOutputStream(tempFile.getName()); 1106 FileChannel dest = fileOutputStream.getChannel(); 1107 src.position(offset).limit(offset + len); 1108 dest.write(src.slice()); 1109 path = tempFile.getName(); 1110 } catch (Exception e) { // Catch exception if any 1111 System.err.println("Error: " + e.getMessage()); 1112 } finally { 1113 safeClose(fileOutputStream); 1114 } 1115 } 1116 return path; 1117 } 1118 1119 private RandomAccessFile getTmpBucket() { 1120 try { 1121 TempFile tempFile = tempFileManager.createTempFile(); 1122 return new RandomAccessFile(tempFile.getName(), "rw"); 1123 } catch (Exception e) { 1124 System.err.println("Error: " + e.getMessage()); 1125 } 1126 return null; 1127 } 1128 1129 /** 1130 * It returns the offset separating multipart file headers from the file's data. 1131 */ 1132 private int stripMultipartHeaders(ByteBuffer b, int offset) { 1133 int i; 1134 for (i = offset; i < b.limit(); i++) { 1135 if (b.get(i) == '\r' && b.get(++i) == '\n' && b.get(++i) == '\r' && b.get(++i) == '\n') { 1136 break; 1137 } 1138 } 1139 return i + 1; 1140 } 1141 1142 /** 1143 * Decodes parameters in percent-encoded URI-format ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and 1144 * adds them to given Map. NOTE: this doesn't support multiple identical keys due to the simplicity of Map. 1145 */ 1146 private void decodeParms(String parms, Map<String, String> p) { 1147 if (parms == null) { 1148 p.put(QUERY_STRING_PARAMETER, ""); 1149 return; 1150 } 1151 1152 p.put(QUERY_STRING_PARAMETER, parms); 1153 StringTokenizer st = new StringTokenizer(parms, "&"); 1154 while (st.hasMoreTokens()) { 1155 String e = st.nextToken(); 1156 int sep = e.indexOf('='); 1157 if (sep >= 0) { 1158 p.put(decodePercent(e.substring(0, sep)).trim(), 1159 decodePercent(e.substring(sep + 1))); 1160 } else { 1161 p.put(decodePercent(e).trim(), ""); 1162 } 1163 } 1164 } 1165 1166 @Override 1167 public final Map<String, String> getParms() { 1168 return parms; 1169 } 1170 1171 @Override 1172 public final Map<String, String> getHeaders() { 1173 return headers; 1174 } 1175 1176 @Override 1177 public final String getUri() { 1178 return uri; 1179 } 1180 1181 @Override 1182 public final Method getMethod() { 1183 return method; 1184 } 1185 1186 @Override 1187 public final InputStream getInputStream() { 1188 return inputStream; 1189 } 1190 1191 @Override 1192 public CookieHandler getCookies() { 1193 return cookies; 1194 } 1195 } 1196 1197 public static class Cookie { 1198 private String n, v, e; 1199 1200 public Cookie(String name, String value, String expires) { 1201 n = name; 1202 v = value; 1203 e = expires; 1204 } 1205 1206 public Cookie(String name, String value) { 1207 this(name, value, 30); 1208 } 1209 1210 public Cookie(String name, String value, int numDays) { 1211 n = name; 1212 v = value; 1213 e = getHTTPTime(numDays); 1214 } 1215 1216 public String getHTTPHeader() { 1217 String fmt = "%s=%s; expires=%s"; 1218 return String.format(fmt, n, v, e); 1219 } 1220 1221 public static String getHTTPTime(int days) { 1222 Calendar calendar = Calendar.getInstance(); 1223 SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); 1224 dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 1225 calendar.add(Calendar.DAY_OF_MONTH, days); 1226 return dateFormat.format(calendar.getTime()); 1227 } 1228 } 1229 1230 /** 1231 * Provides rudimentary support for cookies. 1232 * Doesn't support 'path', 'secure' nor 'httpOnly'. 1233 * Feel free to improve it and/or add unsupported features. 1234 * 1235 * @author LordFokas 1236 */ 1237 public class CookieHandler implements Iterable<String> { 1238 private HashMap<String, String> cookies = new HashMap<String, String>(); 1239 private ArrayList<Cookie> queue = new ArrayList<Cookie>(); 1240 1241 public CookieHandler(Map<String, String> httpHeaders) { 1242 String raw = httpHeaders.get("cookie"); 1243 if (raw != null) { 1244 String[] tokens = raw.split(";"); 1245 for (String token : tokens) { 1246 String[] data = token.trim().split("="); 1247 if (data.length == 2) { 1248 cookies.put(data[0], data[1]); 1249 } 1250 } 1251 } 1252 } 1253 1254 @Override public Iterator<String> iterator() { 1255 return cookies.keySet().iterator(); 1256 } 1257 1258 /** 1259 * Read a cookie from the HTTP Headers. 1260 * 1261 * @param name The cookie's name. 1262 * @return The cookie's value if it exists, null otherwise. 1263 */ 1264 public String read(String name) { 1265 return cookies.get(name); 1266 } 1267 1268 /** 1269 * Sets a cookie. 1270 * 1271 * @param name The cookie's name. 1272 * @param value The cookie's value. 1273 * @param expires How many days until the cookie expires. 1274 */ 1275 public void set(String name, String value, int expires) { 1276 queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires))); 1277 } 1278 1279 public void set(Cookie cookie) { 1280 queue.add(cookie); 1281 } 1282 1283 /** 1284 * Set a cookie with an expiration date from a month ago, effectively deleting it on the client side. 1285 * 1286 * @param name The cookie name. 1287 */ 1288 public void delete(String name) { 1289 set(name, "-delete-", -30); 1290 } 1291 1292 /** 1293 * Internally used by the webserver to add all queued cookies into the Response's HTTP Headers. 1294 * 1295 * @param response The Response object to which headers the queued cookies will be added. 1296 */ 1297 public void unloadQueue(Response response) { 1298 for (Cookie cookie : queue) { 1299 response.addHeader("Set-Cookie", cookie.getHTTPHeader()); 1300 } 1301 } 1302 } 1303} 1304