NanoHTTPD.java revision 67e24e482b132ff0a8618f96b43097c9ce5f2776
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&lt;String&gt;</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&lt;String&gt;</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        /**
611         * Sends given response to the socket.
612         */
613        private void send(OutputStream outputStream) {
614            String mime = mimeType;
615            SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
616            gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));
617
618            try {
619                if (status == null) {
620                    throw new Error("sendResponse(): Status can't be null.");
621                }
622                PrintWriter pw = new PrintWriter(outputStream);
623                pw.print("HTTP/1.1 " + status.getDescription() + " \r\n");
624
625                if (mime != null) {
626                    pw.print("Content-Type: " + mime + "\r\n");
627                }
628
629                if (header == null || header.get("Date") == null) {
630                    pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n");
631                }
632
633                if (header != null) {
634                    for (String key : header.keySet()) {
635                        String value = header.get(key);
636                        pw.print(key + ": " + value + "\r\n");
637                    }
638                }
639
640                pw.print("Connection: keep-alive\r\n");
641
642                if (requestMethod != Method.HEAD && chunkedTransfer) {
643                    sendAsChunked(outputStream, pw);
644                } else {
645                    sendAsFixedLength(outputStream, pw);
646                }
647                outputStream.flush();
648                safeClose(data);
649            } catch (IOException ioe) {
650                // Couldn't write? No can do.
651            }
652        }
653
654        private void sendAsChunked(OutputStream outputStream, PrintWriter pw) throws IOException {
655            pw.print("Transfer-Encoding: chunked\r\n");
656            pw.print("\r\n");
657            pw.flush();
658            int BUFFER_SIZE = 16 * 1024;
659            byte[] CRLF = "\r\n".getBytes();
660            byte[] buff = new byte[BUFFER_SIZE];
661            int read;
662            while ((read = data.read(buff)) > 0) {
663                outputStream.write(String.format("%x\r\n", read).getBytes());
664                outputStream.write(buff, 0, read);
665                outputStream.write(CRLF);
666            }
667            outputStream.write(String.format("0\r\n\r\n").getBytes());
668        }
669
670        private void sendAsFixedLength(OutputStream outputStream, PrintWriter pw) throws IOException {
671            int pending = data != null ? data.available() : 0; // This is to support partial sends, see serveFile()
672            pw.print("Content-Length: "+pending+"\r\n");
673
674            pw.print("\r\n");
675            pw.flush();
676
677            if (requestMethod != Method.HEAD && data != null) {
678                int BUFFER_SIZE = 16 * 1024;
679                byte[] buff = new byte[BUFFER_SIZE];
680                while (pending > 0) {
681                    int read = data.read(buff, 0, ((pending > BUFFER_SIZE) ? BUFFER_SIZE : pending));
682                    if (read <= 0) {
683                        break;
684                    }
685                    outputStream.write(buff, 0, read);
686
687                    pending -= read;
688                }
689            }
690        }
691
692        public IStatus getStatus() {
693            return status;
694        }
695
696        public void setStatus(Status status) {
697            this.status = status;
698        }
699
700        public String getMimeType() {
701            return mimeType;
702        }
703
704        public void setMimeType(String mimeType) {
705            this.mimeType = mimeType;
706        }
707
708        public InputStream getData() {
709            return data;
710        }
711
712        public void setData(InputStream data) {
713            this.data = data;
714        }
715
716        public Method getRequestMethod() {
717            return requestMethod;
718        }
719
720        public void setRequestMethod(Method requestMethod) {
721            this.requestMethod = requestMethod;
722        }
723
724        public void setChunkedTransfer(boolean chunkedTransfer) {
725            this.chunkedTransfer = chunkedTransfer;
726        }
727
728        public interface IStatus {
729            int getRequestStatus();
730            String getDescription();
731        }
732
733        /**
734         * Some HTTP response status codes
735         */
736        public enum Status implements IStatus {
737            OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), PARTIAL_CONTENT(206, "Partial Content"), REDIRECT(301,
738                "Moved Permanently"), NOT_MODIFIED(304, "Not Modified"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401,
739                "Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), METHOD_NOT_ALLOWED(405, "Method Not Allowed"), RANGE_NOT_SATISFIABLE(416,
740                "Requested Range Not Satisfiable"), INTERNAL_ERROR(500, "Internal Server Error");
741            private final int requestStatus;
742            private final String description;
743
744            Status(int requestStatus, String description) {
745                this.requestStatus = requestStatus;
746                this.description = description;
747            }
748
749            @Override
750            public int getRequestStatus() {
751                return this.requestStatus;
752            }
753
754            @Override
755            public String getDescription() {
756                return "" + this.requestStatus + " " + description;
757            }
758        }
759    }
760
761    public static final class ResponseException extends Exception {
762
763        private final Response.Status status;
764
765        public ResponseException(Response.Status status, String message) {
766            super(message);
767            this.status = status;
768        }
769
770        public ResponseException(Response.Status status, String message, Exception e) {
771            super(message, e);
772            this.status = status;
773        }
774
775        public Response.Status getStatus() {
776            return status;
777        }
778    }
779
780    /**
781     * Default strategy for creating and cleaning up temporary files.
782     */
783    private class DefaultTempFileManagerFactory implements TempFileManagerFactory {
784        @Override
785        public TempFileManager create() {
786            return new DefaultTempFileManager();
787        }
788    }
789
790    /**
791     * Handles one session, i.e. parses the HTTP request and returns the response.
792     */
793    public interface IHTTPSession {
794        void execute() throws IOException;
795
796        Map<String, String> getParms();
797
798        Map<String, String> getHeaders();
799
800        /**
801         * @return the path part of the URL.
802         */
803        String getUri();
804
805        String getQueryParameterString();
806
807        Method getMethod();
808
809        InputStream getInputStream();
810
811        CookieHandler getCookies();
812
813        /**
814         * Adds the files in the request body to the files map.
815         * @arg files - map to modify
816         */
817        void parseBody(Map<String, String> files) throws IOException, ResponseException;
818    }
819
820    protected class HTTPSession implements IHTTPSession {
821        public static final int BUFSIZE = 8192;
822        private final TempFileManager tempFileManager;
823        private final OutputStream outputStream;
824        private PushbackInputStream inputStream;
825        private int splitbyte;
826        private int rlen;
827        private String uri;
828        private Method method;
829        private Map<String, String> parms;
830        private Map<String, String> headers;
831        private CookieHandler cookies;
832        private String queryParameterString;
833
834        public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) {
835            this.tempFileManager = tempFileManager;
836            this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
837            this.outputStream = outputStream;
838        }
839
840        public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
841            this.tempFileManager = tempFileManager;
842            this.inputStream = new PushbackInputStream(inputStream, BUFSIZE);
843            this.outputStream = outputStream;
844            String remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
845            headers = new HashMap<String, String>();
846
847            headers.put("remote-addr", remoteIp);
848            headers.put("http-client-ip", remoteIp);
849        }
850
851        @Override
852        public void execute() throws IOException {
853            try {
854                // Read the first 8192 bytes.
855                // The full header should fit in here.
856                // Apache's default header limit is 8KB.
857                // Do NOT assume that a single read will get the entire header at once!
858                byte[] buf = new byte[BUFSIZE];
859                splitbyte = 0;
860                rlen = 0;
861                {
862                    int read = -1;
863                    try {
864                        read = inputStream.read(buf, 0, BUFSIZE);
865                    } catch (Exception e) {
866                        safeClose(inputStream);
867                        safeClose(outputStream);
868                        throw new SocketException("NanoHttpd Shutdown");
869                    }
870                    if (read == -1) {
871                        // socket was been closed
872                        safeClose(inputStream);
873                        safeClose(outputStream);
874                        throw new SocketException("NanoHttpd Shutdown");
875                    }
876                    while (read > 0) {
877                        rlen += read;
878                        splitbyte = findHeaderEnd(buf, rlen);
879                        if (splitbyte > 0)
880                            break;
881                        read = inputStream.read(buf, rlen, BUFSIZE - rlen);
882                    }
883                }
884
885                if (splitbyte < rlen) {
886                    inputStream.unread(buf, splitbyte, rlen - splitbyte);
887                }
888
889                parms = new HashMap<String, String>();
890                if(null == headers) {
891                    headers = new HashMap<String, String>();
892                }
893
894                // Create a BufferedReader for parsing the header.
895                BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen)));
896
897                // Decode the header into parms and header java properties
898                Map<String, String> pre = new HashMap<String, String>();
899                decodeHeader(hin, pre, parms, headers);
900
901                method = Method.lookup(pre.get("method"));
902                if (method == null) {
903                    throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error.");
904                }
905
906                uri = pre.get("uri");
907
908                cookies = new CookieHandler(headers);
909
910                // Ok, now do the serve()
911                Response r = serve(this);
912                if (r == null) {
913                    throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");
914                } else {
915                    cookies.unloadQueue(r);
916                    r.setRequestMethod(method);
917                    r.send(outputStream);
918                }
919            } catch (SocketException e) {
920                // throw it out to close socket object (finalAccept)
921                throw e;
922            } catch (SocketTimeoutException ste) {
923            	throw ste;
924            } catch (IOException ioe) {
925                Response r = new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
926                r.send(outputStream);
927                safeClose(outputStream);
928            } catch (ResponseException re) {
929                Response r = new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
930                r.send(outputStream);
931                safeClose(outputStream);
932            } finally {
933                tempFileManager.clear();
934            }
935        }
936
937        @Override
938        public void parseBody(Map<String, String> files) throws IOException, ResponseException {
939            RandomAccessFile randomAccessFile = null;
940            BufferedReader in = null;
941            try {
942
943                randomAccessFile = getTmpBucket();
944
945                long size;
946                if (headers.containsKey("content-length")) {
947                    size = Integer.parseInt(headers.get("content-length"));
948                } else if (splitbyte < rlen) {
949                    size = rlen - splitbyte;
950                } else {
951                    size = 0;
952                }
953
954                // Now read all the body and write it to f
955                byte[] buf = new byte[512];
956                while (rlen >= 0 && size > 0) {
957                    rlen = inputStream.read(buf, 0, (int)Math.min(size, 512));
958                    size -= rlen;
959                    if (rlen > 0) {
960                        randomAccessFile.write(buf, 0, rlen);
961                    }
962                }
963
964                // Get the raw body as a byte []
965                ByteBuffer fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
966                randomAccessFile.seek(0);
967
968                // Create a BufferedReader for easily reading it as string.
969                InputStream bin = new FileInputStream(randomAccessFile.getFD());
970                in = new BufferedReader(new InputStreamReader(bin));
971
972                // If the method is POST, there may be parameters
973                // in data section, too, read it:
974                if (Method.POST.equals(method)) {
975                    String contentType = "";
976                    String contentTypeHeader = headers.get("content-type");
977
978                    StringTokenizer st = null;
979                    if (contentTypeHeader != null) {
980                        st = new StringTokenizer(contentTypeHeader, ",; ");
981                        if (st.hasMoreTokens()) {
982                            contentType = st.nextToken();
983                        }
984                    }
985
986                    if ("multipart/form-data".equalsIgnoreCase(contentType)) {
987                        // Handle multipart/form-data
988                        if (!st.hasMoreTokens()) {
989                            throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html");
990                        }
991
992                        String boundaryStartString = "boundary=";
993                        int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length();
994                        String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length());
995                        if (boundary.startsWith("\"") && boundary.endsWith("\"")) {
996                            boundary = boundary.substring(1, boundary.length() - 1);
997                        }
998
999                        decodeMultipartData(boundary, fbuf, in, parms, files);
1000                    } else {
1001                        // Handle application/x-www-form-urlencoded
1002                        String postLine = "";
1003                        StringBuilder postLineBuffer = new StringBuilder();
1004                        char pbuf[] = new char[512];
1005                        int read = in.read(pbuf);
1006                        while (read >= 0 && !postLine.endsWith("\r\n")) {
1007                            postLine = String.valueOf(pbuf, 0, read);
1008                            postLineBuffer.append(postLine);
1009                            read = in.read(pbuf);
1010                        }
1011                        postLine = postLineBuffer.toString().trim();
1012                        decodeParms(postLine, parms);
1013                    }
1014                } else if (Method.PUT.equals(method)) {
1015                    files.put("content", saveTmpFile(fbuf, 0, fbuf.limit()));
1016                }
1017            } finally {
1018                safeClose(randomAccessFile);
1019                safeClose(in);
1020            }
1021        }
1022
1023        /**
1024         * Decodes the sent headers and loads the data into Key/value pairs
1025         */
1026        private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers)
1027            throws ResponseException {
1028            try {
1029                // Read the request line
1030                String inLine = in.readLine();
1031                if (inLine == null) {
1032                    return;
1033                }
1034
1035                StringTokenizer st = new StringTokenizer(inLine);
1036                if (!st.hasMoreTokens()) {
1037                    throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html");
1038                }
1039
1040                pre.put("method", st.nextToken());
1041
1042                if (!st.hasMoreTokens()) {
1043                    throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html");
1044                }
1045
1046                String uri = st.nextToken();
1047
1048                // Decode parameters from the URI
1049                int qmi = uri.indexOf('?');
1050                if (qmi >= 0) {
1051                    decodeParms(uri.substring(qmi + 1), parms);
1052                    uri = decodePercent(uri.substring(0, qmi));
1053                } else {
1054                    uri = decodePercent(uri);
1055                }
1056
1057                // If there's another token, it's protocol version,
1058                // followed by HTTP headers. Ignore version but parse headers.
1059                // NOTE: this now forces header names lowercase since they are
1060                // case insensitive and vary by client.
1061                if (st.hasMoreTokens()) {
1062                    String line = in.readLine();
1063                    while (line != null && line.trim().length() > 0) {
1064                        int p = line.indexOf(':');
1065                        if (p >= 0)
1066                            headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim());
1067                        line = in.readLine();
1068                    }
1069                }
1070
1071                pre.put("uri", uri);
1072            } catch (IOException ioe) {
1073                throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
1074            }
1075        }
1076
1077        /**
1078         * Decodes the Multipart Body data and put it into Key/Value pairs.
1079         */
1080        private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms,
1081                                         Map<String, String> files) throws ResponseException {
1082            try {
1083                int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes());
1084                int boundarycount = 1;
1085                String mpline = in.readLine();
1086                while (mpline != null) {
1087                    if (!mpline.contains(boundary)) {
1088                        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");
1089                    }
1090                    boundarycount++;
1091                    Map<String, String> item = new HashMap<String, String>();
1092                    mpline = in.readLine();
1093                    while (mpline != null && mpline.trim().length() > 0) {
1094                        int p = mpline.indexOf(':');
1095                        if (p != -1) {
1096                            item.put(mpline.substring(0, p).trim().toLowerCase(Locale.US), mpline.substring(p + 1).trim());
1097                        }
1098                        mpline = in.readLine();
1099                    }
1100                    if (mpline != null) {
1101                        String contentDisposition = item.get("content-disposition");
1102                        if (contentDisposition == null) {
1103                            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");
1104                        }
1105                        StringTokenizer st = new StringTokenizer(contentDisposition, "; ");
1106                        Map<String, String> disposition = new HashMap<String, String>();
1107                        while (st.hasMoreTokens()) {
1108                            String token = st.nextToken();
1109                            int p = token.indexOf('=');
1110                            if (p != -1) {
1111                                disposition.put(token.substring(0, p).trim().toLowerCase(Locale.US), token.substring(p + 1).trim());
1112                            }
1113                        }
1114                        String pname = disposition.get("name");
1115                        pname = pname.substring(1, pname.length() - 1);
1116
1117                        String value = "";
1118                        if (item.get("content-type") == null) {
1119                            while (mpline != null && !mpline.contains(boundary)) {
1120                                mpline = in.readLine();
1121                                if (mpline != null) {
1122                                    int d = mpline.indexOf(boundary);
1123                                    if (d == -1) {
1124                                        value += mpline;
1125                                    } else {
1126                                        value += mpline.substring(0, d - 2);
1127                                    }
1128                                }
1129                            }
1130                        } else {
1131                            if (boundarycount > bpositions.length) {
1132                                throw new ResponseException(Response.Status.INTERNAL_ERROR, "Error processing request");
1133                            }
1134                            int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]);
1135                            String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4);
1136                            files.put(pname, path);
1137                            value = disposition.get("filename");
1138                            value = value.substring(1, value.length() - 1);
1139                            do {
1140                                mpline = in.readLine();
1141                            } while (mpline != null && !mpline.contains(boundary));
1142                        }
1143                        parms.put(pname, value);
1144                    }
1145                }
1146            } catch (IOException ioe) {
1147                throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
1148            }
1149        }
1150
1151        /**
1152         * Find byte index separating header from body. It must be the last byte of the first two sequential new lines.
1153         */
1154        private int findHeaderEnd(final byte[] buf, int rlen) {
1155            int splitbyte = 0;
1156            while (splitbyte + 3 < rlen) {
1157                if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') {
1158                    return splitbyte + 4;
1159                }
1160                splitbyte++;
1161            }
1162            return 0;
1163        }
1164
1165        /**
1166         * Find the byte positions where multipart boundaries start.
1167         */
1168        private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) {
1169            int matchcount = 0;
1170            int matchbyte = -1;
1171            List<Integer> matchbytes = new ArrayList<Integer>();
1172            for (int i = 0; i < b.limit(); i++) {
1173                if (b.get(i) == boundary[matchcount]) {
1174                    if (matchcount == 0)
1175                        matchbyte = i;
1176                    matchcount++;
1177                    if (matchcount == boundary.length) {
1178                        matchbytes.add(matchbyte);
1179                        matchcount = 0;
1180                        matchbyte = -1;
1181                    }
1182                } else {
1183                    i -= matchcount;
1184                    matchcount = 0;
1185                    matchbyte = -1;
1186                }
1187            }
1188            int[] ret = new int[matchbytes.size()];
1189            for (int i = 0; i < ret.length; i++) {
1190                ret[i] = matchbytes.get(i);
1191            }
1192            return ret;
1193        }
1194
1195        /**
1196         * Retrieves the content of a sent file and saves it to a temporary file. The full path to the saved file is returned.
1197         */
1198        private String saveTmpFile(ByteBuffer b, int offset, int len) {
1199            String path = "";
1200            if (len > 0) {
1201                FileOutputStream fileOutputStream = null;
1202                try {
1203                    TempFile tempFile = tempFileManager.createTempFile();
1204                    ByteBuffer src = b.duplicate();
1205                    fileOutputStream = new FileOutputStream(tempFile.getName());
1206                    FileChannel dest = fileOutputStream.getChannel();
1207                    src.position(offset).limit(offset + len);
1208                    dest.write(src.slice());
1209                    path = tempFile.getName();
1210                } catch (Exception e) { // Catch exception if any
1211                    System.err.println("Error: " + e.getMessage());
1212                } finally {
1213                    safeClose(fileOutputStream);
1214                }
1215            }
1216            return path;
1217        }
1218
1219        private RandomAccessFile getTmpBucket() {
1220            try {
1221                TempFile tempFile = tempFileManager.createTempFile();
1222                return new RandomAccessFile(tempFile.getName(), "rw");
1223            } catch (Exception e) {
1224                System.err.println("Error: " + e.getMessage());
1225            }
1226            return null;
1227        }
1228
1229        /**
1230         * It returns the offset separating multipart file headers from the file's data.
1231         */
1232        private int stripMultipartHeaders(ByteBuffer b, int offset) {
1233            int i;
1234            for (i = offset; i < b.limit(); i++) {
1235                if (b.get(i) == '\r' && b.get(++i) == '\n' && b.get(++i) == '\r' && b.get(++i) == '\n') {
1236                    break;
1237                }
1238            }
1239            return i + 1;
1240        }
1241
1242        /**
1243         * Decodes parameters in percent-encoded URI-format ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and
1244         * adds them to given Map. NOTE: this doesn't support multiple identical keys due to the simplicity of Map.
1245         */
1246        private void decodeParms(String parms, Map<String, String> p) {
1247            if (parms == null) {
1248                queryParameterString = "";
1249                return;
1250            }
1251
1252            queryParameterString = parms;
1253            StringTokenizer st = new StringTokenizer(parms, "&");
1254            while (st.hasMoreTokens()) {
1255                String e = st.nextToken();
1256                int sep = e.indexOf('=');
1257                if (sep >= 0) {
1258                    p.put(decodePercent(e.substring(0, sep)).trim(),
1259                        decodePercent(e.substring(sep + 1)));
1260                } else {
1261                    p.put(decodePercent(e).trim(), "");
1262                }
1263            }
1264        }
1265
1266        @Override
1267        public final Map<String, String> getParms() {
1268            return parms;
1269        }
1270
1271        public String getQueryParameterString() {
1272            return queryParameterString;
1273        }
1274
1275        @Override
1276        public final Map<String, String> getHeaders() {
1277            return headers;
1278        }
1279
1280        @Override
1281        public final String getUri() {
1282            return uri;
1283        }
1284
1285        @Override
1286        public final Method getMethod() {
1287            return method;
1288        }
1289
1290        @Override
1291        public final InputStream getInputStream() {
1292            return inputStream;
1293        }
1294
1295        @Override
1296        public CookieHandler getCookies() {
1297            return cookies;
1298        }
1299    }
1300
1301    public static class Cookie {
1302        private String n, v, e;
1303
1304        public Cookie(String name, String value, String expires) {
1305            n = name;
1306            v = value;
1307            e = expires;
1308        }
1309
1310        public Cookie(String name, String value) {
1311            this(name, value, 30);
1312        }
1313
1314        public Cookie(String name, String value, int numDays) {
1315            n = name;
1316            v = value;
1317            e = getHTTPTime(numDays);
1318        }
1319
1320        public String getHTTPHeader() {
1321            String fmt = "%s=%s; expires=%s";
1322            return String.format(fmt, n, v, e);
1323        }
1324
1325        public static String getHTTPTime(int days) {
1326            Calendar calendar = Calendar.getInstance();
1327            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
1328            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
1329            calendar.add(Calendar.DAY_OF_MONTH, days);
1330            return dateFormat.format(calendar.getTime());
1331        }
1332    }
1333
1334    /**
1335     * Provides rudimentary support for cookies.
1336     * Doesn't support 'path', 'secure' nor 'httpOnly'.
1337     * Feel free to improve it and/or add unsupported features.
1338     *
1339     * @author LordFokas
1340     */
1341    public class CookieHandler implements Iterable<String> {
1342        private HashMap<String, String> cookies = new HashMap<String, String>();
1343        private ArrayList<Cookie> queue = new ArrayList<Cookie>();
1344
1345        public CookieHandler(Map<String, String> httpHeaders) {
1346            String raw = httpHeaders.get("cookie");
1347            if (raw != null) {
1348                String[] tokens = raw.split(";");
1349                for (String token : tokens) {
1350                    String[] data = token.trim().split("=");
1351                    if (data.length == 2) {
1352                        cookies.put(data[0], data[1]);
1353                    }
1354                }
1355            }
1356        }
1357
1358        @Override public Iterator<String> iterator() {
1359            return cookies.keySet().iterator();
1360        }
1361
1362        /**
1363         * Read a cookie from the HTTP Headers.
1364         *
1365         * @param name The cookie's name.
1366         * @return The cookie's value if it exists, null otherwise.
1367         */
1368        public String read(String name) {
1369            return cookies.get(name);
1370        }
1371
1372        /**
1373         * Sets a cookie.
1374         *
1375         * @param name    The cookie's name.
1376         * @param value   The cookie's value.
1377         * @param expires How many days until the cookie expires.
1378         */
1379        public void set(String name, String value, int expires) {
1380            queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires)));
1381        }
1382
1383        public void set(Cookie cookie) {
1384            queue.add(cookie);
1385        }
1386
1387        /**
1388         * Set a cookie with an expiration date from a month ago, effectively deleting it on the client side.
1389         *
1390         * @param name The cookie name.
1391         */
1392        public void delete(String name) {
1393            set(name, "-delete-", -30);
1394        }
1395
1396        /**
1397         * Internally used by the webserver to add all queued cookies into the Response's HTTP Headers.
1398         *
1399         * @param response The Response object to which headers the queued cookies will be added.
1400         */
1401        public void unloadQueue(Response response) {
1402            for (Cookie cookie : queue) {
1403                response.addHeader("Set-Cookie", cookie.getHTTPHeader());
1404            }
1405        }
1406    }
1407}
1408