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