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