Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

1961
LINES

< > BotCompany Repo | #1000408 // Original source of NanoHTTPD.java

Java source code

1  
package fi.iki.elonen;
2  
3  
/*
4  
 * #%L
5  
 * NanoHttpd-Core
6  
 * %%
7  
 * Copyright (C) 2012 - 2015 nanohttpd
8  
 * %%
9  
 * Redistribution and use in source and binary forms, with or without modification,
10  
 * are permitted provided that the following conditions are met:
11  
 * 
12  
 * 1. Redistributions of source code must retain the above copyright notice, this
13  
 *    list of conditions and the following disclaimer.
14  
 * 
15  
 * 2. Redistributions in binary form must reproduce the above copyright notice,
16  
 *    this list of conditions and the following disclaimer in the documentation
17  
 *    and/or other materials provided with the distribution.
18  
 * 
19  
 * 3. Neither the name of the nanohttpd nor the names of its contributors
20  
 *    may be used to endorse or promote products derived from this software without
21  
 *    specific prior written permission.
22  
 * 
23  
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24  
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25  
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
27  
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30  
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
31  
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
32  
 * OF THE POSSIBILITY OF SUCH DAMAGE.
33  
 * #L%
34  
 */
35  
36  
import java.io.*;
37  
import java.net.InetAddress;
38  
import java.net.InetSocketAddress;
39  
import java.net.ServerSocket;
40  
import java.net.Socket;
41  
import java.net.SocketException;
42  
import java.net.SocketTimeoutException;
43  
import java.net.URLDecoder;
44  
import java.nio.ByteBuffer;
45  
import java.nio.channels.FileChannel;
46  
import java.nio.charset.Charset;
47  
import java.security.KeyStore;
48  
import java.text.SimpleDateFormat;
49  
import java.util.ArrayList;
50  
import java.util.Calendar;
51  
import java.util.Collections;
52  
import java.util.Date;
53  
import java.util.HashMap;
54  
import java.util.Iterator;
55  
import java.util.List;
56  
import java.util.Locale;
57  
import java.util.Map;
58  
import java.util.StringTokenizer;
59  
import java.util.TimeZone;
60  
import java.util.logging.Level;
61  
import java.util.logging.Logger;
62  
import java.util.regex.Matcher;
63  
import java.util.regex.Pattern;
64  
import java.util.zip.GZIPOutputStream;
65  
66  
import javax.net.ssl.KeyManager;
67  
import javax.net.ssl.KeyManagerFactory;
68  
import javax.net.ssl.SSLContext;
69  
import javax.net.ssl.SSLServerSocket;
70  
import javax.net.ssl.SSLServerSocketFactory;
71  
import javax.net.ssl.TrustManagerFactory;
72  
73  
import fi.iki.elonen.NanoHTTPD.Response.IStatus;
74  
import fi.iki.elonen.NanoHTTPD.Response.Status;
75  
76  
/**
77  
 * A simple, tiny, nicely embeddable HTTP server in Java
78  
 * <p/>
79  
 * <p/>
80  
 * NanoHTTPD
81  
 * <p>
82  
 * Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen,
83  
 * 2010 by Konstantinos Togias
84  
 * </p>
85  
 * <p/>
86  
 * <p/>
87  
 * <b>Features + limitations: </b>
88  
 * <ul>
89  
 * <p/>
90  
 * <li>Only one Java file</li>
91  
 * <li>Java 5 compatible</li>
92  
 * <li>Released as open source, Modified BSD licence</li>
93  
 * <li>No fixed config files, logging, authorization etc. (Implement yourself if
94  
 * you need them.)</li>
95  
 * <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT
96  
 * support in 1.25)</li>
97  
 * <li>Supports both dynamic content and file serving</li>
98  
 * <li>Supports file upload (since version 1.2, 2010)</li>
99  
 * <li>Supports partial content (streaming)</li>
100  
 * <li>Supports ETags</li>
101  
 * <li>Never caches anything</li>
102  
 * <li>Doesn't limit bandwidth, request time or simultaneous connections</li>
103  
 * <li>Default code serves files and shows all HTTP parameters and headers</li>
104  
 * <li>File server supports directory listing, index.html and index.htm</li>
105  
 * <li>File server supports partial content (streaming)</li>
106  
 * <li>File server supports ETags</li>
107  
 * <li>File server does the 301 redirection trick for directories without '/'</li>
108  
 * <li>File server supports simple skipping for files (continue download)</li>
109  
 * <li>File server serves also very long files without memory overhead</li>
110  
 * <li>Contains a built-in list of most common MIME types</li>
111  
 * <li>All header names are converted to lower case so they don't vary between
112  
 * browsers/clients</li>
113  
 * <p/>
114  
 * </ul>
115  
 * <p/>
116  
 * <p/>
117  
 * <b>How to use: </b>
118  
 * <ul>
119  
 * <p/>
120  
 * <li>Subclass and implement serve() and embed to your own program</li>
121  
 * <p/>
122  
 * </ul>
123  
 * <p/>
124  
 * See the separate "LICENSE.md" file for the distribution license (Modified BSD
125  
 * licence)
126  
 */
127  
public abstract class NanoHTTPD {
128  
129  
    /**
130  
     * Pluggable strategy for asynchronously executing requests.
131  
     */
132  
    public interface AsyncRunner {
133  
134  
        void closeAll();
135  
136  
        void closed(ClientHandler clientHandler);
137  
138  
        void exec(ClientHandler code);
139  
    }
140  
141  
    /**
142  
     * The runnable that will be used for every new client connection.
143  
     */
144  
    public class ClientHandler implements Runnable {
145  
146  
        private final InputStream inputStream;
147  
148  
        private final Socket acceptSocket;
149  
150  
        private ClientHandler(InputStream inputStream, Socket acceptSocket) {
151  
            this.inputStream = inputStream;
152  
            this.acceptSocket = acceptSocket;
153  
        }
154  
155  
        public void close() {
156  
            safeClose(this.inputStream);
157  
            safeClose(this.acceptSocket);
158  
        }
159  
160  
        @Override
161  
        public void run() {
162  
            OutputStream outputStream = null;
163  
            try {
164  
                outputStream = this.acceptSocket.getOutputStream();
165  
                TempFileManager tempFileManager = NanoHTTPD.this.tempFileManagerFactory.create();
166  
                HTTPSession session = new HTTPSession(tempFileManager, this.inputStream, outputStream, this.acceptSocket.getInetAddress());
167  
                while (!this.acceptSocket.isClosed()) {
168  
                    session.execute();
169  
                }
170  
            } catch (Exception e) {
171  
                // When the socket is closed by the client,
172  
                // we throw our own SocketException
173  
                // to break the "keep alive" loop above. If
174  
                // the exception was anything other
175  
                // than the expected SocketException OR a
176  
                // SocketTimeoutException, print the
177  
                // stacktrace
178  
                if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())) && !(e instanceof SocketTimeoutException)) {
179  
                    NanoHTTPD.LOG.log(Level.FINE, "Communication with the client broken", e);
180  
                }
181  
            } finally {
182  
                safeClose(outputStream);
183  
                safeClose(this.inputStream);
184  
                safeClose(this.acceptSocket);
185  
                NanoHTTPD.this.asyncRunner.closed(this);
186  
            }
187  
        }
188  
    }
189  
190  
    public static class Cookie {
191  
192  
        public static String getHTTPTime(int days) {
193  
            Calendar calendar = Calendar.getInstance();
194  
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
195  
            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
196  
            calendar.add(Calendar.DAY_OF_MONTH, days);
197  
            return dateFormat.format(calendar.getTime());
198  
        }
199  
200  
        private final String n, v, e;
201  
202  
        public Cookie(String name, String value) {
203  
            this(name, value, 30);
204  
        }
205  
206  
        public Cookie(String name, String value, int numDays) {
207  
            this.n = name;
208  
            this.v = value;
209  
            this.e = getHTTPTime(numDays);
210  
        }
211  
212  
        public Cookie(String name, String value, String expires) {
213  
            this.n = name;
214  
            this.v = value;
215  
            this.e = expires;
216  
        }
217  
218  
        public String getHTTPHeader() {
219  
            String fmt = "%s=%s; expires=%s";
220  
            return String.format(fmt, this.n, this.v, this.e);
221  
        }
222  
    }
223  
224  
    /**
225  
     * Provides rudimentary support for cookies. Doesn't support 'path',
226  
     * 'secure' nor 'httpOnly'. Feel free to improve it and/or add unsupported
227  
     * features.
228  
     * 
229  
     * @author LordFokas
230  
     */
231  
    public class CookieHandler implements Iterable<String> {
232  
233  
        private final HashMap<String, String> cookies = new HashMap<String, String>();
234  
235  
        private final ArrayList<Cookie> queue = new ArrayList<Cookie>();
236  
237  
        public CookieHandler(Map<String, String> httpHeaders) {
238  
            String raw = httpHeaders.get("cookie");
239  
            if (raw != null) {
240  
                String[] tokens = raw.split(";");
241  
                for (String token : tokens) {
242  
                    String[] data = token.trim().split("=");
243  
                    if (data.length == 2) {
244  
                        this.cookies.put(data[0], data[1]);
245  
                    }
246  
                }
247  
            }
248  
        }
249  
250  
        /**
251  
         * Set a cookie with an expiration date from a month ago, effectively
252  
         * deleting it on the client side.
253  
         * 
254  
         * @param name
255  
         *            The cookie name.
256  
         */
257  
        public void delete(String name) {
258  
            set(name, "-delete-", -30);
259  
        }
260  
261  
        @Override
262  
        public Iterator<String> iterator() {
263  
            return this.cookies.keySet().iterator();
264  
        }
265  
266  
        /**
267  
         * Read a cookie from the HTTP Headers.
268  
         * 
269  
         * @param name
270  
         *            The cookie's name.
271  
         * @return The cookie's value if it exists, null otherwise.
272  
         */
273  
        public String read(String name) {
274  
            return this.cookies.get(name);
275  
        }
276  
277  
        public void set(Cookie cookie) {
278  
            this.queue.add(cookie);
279  
        }
280  
281  
        /**
282  
         * Sets a cookie.
283  
         * 
284  
         * @param name
285  
         *            The cookie's name.
286  
         * @param value
287  
         *            The cookie's value.
288  
         * @param expires
289  
         *            How many days until the cookie expires.
290  
         */
291  
        public void set(String name, String value, int expires) {
292  
            this.queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires)));
293  
        }
294  
295  
        /**
296  
         * Internally used by the webserver to add all queued cookies into the
297  
         * Response's HTTP Headers.
298  
         * 
299  
         * @param response
300  
         *            The Response object to which headers the queued cookies
301  
         *            will be added.
302  
         */
303  
        public void unloadQueue(Response response) {
304  
            for (Cookie cookie : this.queue) {
305  
                response.addHeader("Set-Cookie", cookie.getHTTPHeader());
306  
            }
307  
        }
308  
    }
309  
310  
    /**
311  
     * Default threading strategy for NanoHTTPD.
312  
     * <p/>
313  
     * <p>
314  
     * By default, the server spawns a new Thread for every incoming request.
315  
     * These are set to <i>daemon</i> status, and named according to the request
316  
     * number. The name is useful when profiling the application.
317  
     * </p>
318  
     */
319  
    public static class DefaultAsyncRunner implements AsyncRunner {
320  
321  
        private long requestCount;
322  
323  
        private final List<ClientHandler> running = Collections.synchronizedList(new ArrayList<NanoHTTPD.ClientHandler>());
324  
325  
        /**
326  
         * @return a list with currently running clients.
327  
         */
328  
        public List<ClientHandler> getRunning() {
329  
            return running;
330  
        }
331  
332  
        @Override
333  
        public void closeAll() {
334  
            // copy of the list for concurrency
335  
            for (ClientHandler clientHandler : new ArrayList<ClientHandler>(this.running)) {
336  
                clientHandler.close();
337  
            }
338  
        }
339  
340  
        @Override
341  
        public void closed(ClientHandler clientHandler) {
342  
            this.running.remove(clientHandler);
343  
        }
344  
345  
        @Override
346  
        public void exec(ClientHandler clientHandler) {
347  
            ++this.requestCount;
348  
            Thread t = new Thread(clientHandler);
349  
            t.setDaemon(true);
350  
            t.setName("NanoHttpd Request Processor (#" + this.requestCount + ")");
351  
            this.running.add(clientHandler);
352  
            t.start();
353  
        }
354  
    }
355  
356  
    /**
357  
     * Default strategy for creating and cleaning up temporary files.
358  
     * <p/>
359  
     * <p>
360  
     * By default, files are created by <code>File.createTempFile()</code> in
361  
     * the directory specified.
362  
     * </p>
363  
     */
364  
    public static class DefaultTempFile implements TempFile {
365  
366  
        private final File file;
367  
368  
        private final OutputStream fstream;
369  
370  
        public DefaultTempFile(String tempdir) throws IOException {
371  
            this.file = File.createTempFile("NanoHTTPD-", "", new File(tempdir));
372  
            this.fstream = new FileOutputStream(this.file);
373  
        }
374  
375  
        @Override
376  
        public void delete() throws Exception {
377  
            safeClose(this.fstream);
378  
            if (!this.file.delete()) {
379  
                throw new Exception("could not delete temporary file");
380  
            }
381  
        }
382  
383  
        @Override
384  
        public String getName() {
385  
            return this.file.getAbsolutePath();
386  
        }
387  
388  
        @Override
389  
        public OutputStream open() throws Exception {
390  
            return this.fstream;
391  
        }
392  
    }
393  
394  
    /**
395  
     * Default strategy for creating and cleaning up temporary files.
396  
     * <p/>
397  
     * <p>
398  
     * This class stores its files in the standard location (that is, wherever
399  
     * <code>java.io.tmpdir</code> points to). Files are added to an internal
400  
     * list, and deleted when no longer needed (that is, when
401  
     * <code>clear()</code> is invoked at the end of processing a request).
402  
     * </p>
403  
     */
404  
    public static class DefaultTempFileManager implements TempFileManager {
405  
406  
        private final String tmpdir;
407  
408  
        private final List<TempFile> tempFiles;
409  
410  
        public DefaultTempFileManager() {
411  
            this.tmpdir = System.getProperty("java.io.tmpdir");
412  
            this.tempFiles = new ArrayList<TempFile>();
413  
        }
414  
415  
        @Override
416  
        public void clear() {
417  
            for (TempFile file : this.tempFiles) {
418  
                try {
419  
                    file.delete();
420  
                } catch (Exception ignored) {
421  
                    NanoHTTPD.LOG.log(Level.WARNING, "could not delete file ", ignored);
422  
                }
423  
            }
424  
            this.tempFiles.clear();
425  
        }
426  
427  
        @Override
428  
        public TempFile createTempFile() throws Exception {
429  
            DefaultTempFile tempFile = new DefaultTempFile(this.tmpdir);
430  
            this.tempFiles.add(tempFile);
431  
            return tempFile;
432  
        }
433  
    }
434  
435  
    /**
436  
     * Default strategy for creating and cleaning up temporary files.
437  
     */
438  
    private class DefaultTempFileManagerFactory implements TempFileManagerFactory {
439  
440  
        @Override
441  
        public TempFileManager create() {
442  
            return new DefaultTempFileManager();
443  
        }
444  
    }
445  
446  
    private static final String CONTENT_DISPOSITION_REGEX = "([ |\t]*Content-Disposition[ |\t]*:)(.*)";
447  
448  
    private static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern.compile(CONTENT_DISPOSITION_REGEX, Pattern.CASE_INSENSITIVE);
449  
450  
    private static final String CONTENT_TYPE_REGEX = "([ |\t]*content-type[ |\t]*:)(.*)";
451  
452  
    private static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile(CONTENT_TYPE_REGEX, Pattern.CASE_INSENSITIVE);
453  
454  
    private static final String CONTENT_DISPOSITION_ATTRIBUTE_REGEX = "[ |\t]*([a-zA-Z]*)[ |\t]*=[ |\t]*['|\"]([^\"^']*)['|\"]";
455  
456  
    private static final Pattern CONTENT_DISPOSITION_ATTRIBUTE_PATTERN = Pattern.compile(CONTENT_DISPOSITION_ATTRIBUTE_REGEX);
457  
458  
    protected class HTTPSession implements IHTTPSession {
459  
460  
        public static final int BUFSIZE = 8192;
461  
462  
        private final TempFileManager tempFileManager;
463  
464  
        private final OutputStream outputStream;
465  
466  
        private final PushbackInputStream inputStream;
467  
468  
        private int splitbyte;
469  
470  
        private int rlen;
471  
472  
        private String uri;
473  
474  
        private Method method;
475  
476  
        private Map<String, String> parms;
477  
478  
        private Map<String, String> headers;
479  
480  
        private CookieHandler cookies;
481  
482  
        private String queryParameterString;
483  
484  
        private String remoteIp;
485  
486  
        private String protocolVersion;
487  
488  
        public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) {
489  
            this.tempFileManager = tempFileManager;
490  
            this.inputStream = new PushbackInputStream(inputStream, HTTPSession.BUFSIZE);
491  
            this.outputStream = outputStream;
492  
        }
493  
494  
        public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
495  
            this.tempFileManager = tempFileManager;
496  
            this.inputStream = new PushbackInputStream(inputStream, HTTPSession.BUFSIZE);
497  
            this.outputStream = outputStream;
498  
            this.remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
499  
            this.headers = new HashMap<String, String>();
500  
        }
501  
502  
        /**
503  
         * Decodes the sent headers and loads the data into Key/value pairs
504  
         */
505  
        private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers) throws ResponseException {
506  
            try {
507  
                // Read the request line
508  
                String inLine = in.readLine();
509  
                if (inLine == null) {
510  
                    return;
511  
                }
512  
513  
                StringTokenizer st = new StringTokenizer(inLine);
514  
                if (!st.hasMoreTokens()) {
515  
                    throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html");
516  
                }
517  
518  
                pre.put("method", st.nextToken());
519  
520  
                if (!st.hasMoreTokens()) {
521  
                    throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html");
522  
                }
523  
524  
                String uri = st.nextToken();
525  
526  
                // Decode parameters from the URI
527  
                int qmi = uri.indexOf('?');
528  
                if (qmi >= 0) {
529  
                    decodeParms(uri.substring(qmi + 1), parms);
530  
                    uri = decodePercent(uri.substring(0, qmi));
531  
                } else {
532  
                    uri = decodePercent(uri);
533  
                }
534  
535  
                // If there's another token, its protocol version,
536  
                // followed by HTTP headers.
537  
                // NOTE: this now forces header names lower case since they are
538  
                // case insensitive and vary by client.
539  
                if (st.hasMoreTokens()) {
540  
                    protocolVersion = st.nextToken();
541  
                } else {
542  
                    protocolVersion = "HTTP/1.1";
543  
                    NanoHTTPD.LOG.log(Level.FINE, "no protocol version specified, strange. Assuming HTTP/1.1.");
544  
                }
545  
                String line = in.readLine();
546  
                while (line != null && line.trim().length() > 0) {
547  
                    int p = line.indexOf(':');
548  
                    if (p >= 0) {
549  
                        headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim());
550  
                    }
551  
                    line = in.readLine();
552  
                }
553  
554  
                pre.put("uri", uri);
555  
            } catch (IOException ioe) {
556  
                throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
557  
            }
558  
        }
559  
560  
        /**
561  
         * Decodes the Multipart Body data and put it into Key/Value pairs.
562  
         */
563  
        private void decodeMultipartFormData(String boundary, ByteBuffer fbuf, Map<String, String> parms, Map<String, String> files) throws ResponseException {
564  
            try {
565  
                int[] boundary_idxs = getBoundaryPositions(fbuf, boundary.getBytes());
566  
                if (boundary_idxs.length < 2) {
567  
                    throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but contains less than two boundary strings.");
568  
                }
569  
570  
                final int MAX_HEADER_SIZE = 1024;
571  
                byte[] part_header_buff = new byte[MAX_HEADER_SIZE];
572  
                for (int bi = 0; bi < boundary_idxs.length - 1; bi++) {
573  
                    fbuf.position(boundary_idxs[bi]);
574  
                    int len = (fbuf.remaining() < MAX_HEADER_SIZE) ? fbuf.remaining() : MAX_HEADER_SIZE;
575  
                    fbuf.get(part_header_buff, 0, len);
576  
                    ByteArrayInputStream bais = new ByteArrayInputStream(part_header_buff, 0, len);
577  
                    BufferedReader in = new BufferedReader(new InputStreamReader(bais, Charset.forName("US-ASCII")));
578  
579  
                    // First line is boundary string
580  
                    String mpline = in.readLine();
581  
                    if (!mpline.contains(boundary)) {
582  
                        throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but chunk does not start with boundary.");
583  
                    }
584  
585  
                    String part_name = null, file_name = null, content_type = null;
586  
                    // Parse the reset of the header lines
587  
                    mpline = in.readLine();
588  
                    while (mpline != null && mpline.trim().length() > 0) {
589  
                        Matcher matcher = CONTENT_DISPOSITION_PATTERN.matcher(mpline);
590  
                        if (matcher.matches()) {
591  
                            String attributeString = matcher.group(2);
592  
                            matcher = CONTENT_DISPOSITION_ATTRIBUTE_PATTERN.matcher(attributeString);
593  
                            while (matcher.find()) {
594  
                                String key = matcher.group(1);
595  
                                if (key.equalsIgnoreCase("name")) {
596  
                                    part_name = matcher.group(2);
597  
                                } else if (key.equalsIgnoreCase("filename")) {
598  
                                    file_name = matcher.group(2);
599  
                                }
600  
                            }
601  
                        }
602  
                        matcher = CONTENT_TYPE_PATTERN.matcher(mpline);
603  
                        if (matcher.matches()) {
604  
                            content_type = matcher.group(2).trim();
605  
                        }
606  
                        mpline = in.readLine();
607  
                    }
608  
609  
                    // Read the part data
610  
                    int part_header_len = len - (int) in.skip(MAX_HEADER_SIZE);
611  
                    if (part_header_len >= len - 4) {
612  
                        throw new ResponseException(Response.Status.INTERNAL_ERROR, "Multipart header size exceeds MAX_HEADER_SIZE.");
613  
                    }
614  
                    int part_data_start = boundary_idxs[bi] + part_header_len;
615  
                    int part_data_end = boundary_idxs[bi + 1] - 4;
616  
617  
                    fbuf.position(part_data_start);
618  
                    if (content_type == null) {
619  
                        // Read the part into a string
620  
                        byte[] data_bytes = new byte[part_data_end - part_data_start];
621  
                        fbuf.get(data_bytes);
622  
                        parms.put(part_name, new String(data_bytes));
623  
                    } else {
624  
                        // Read it into a file
625  
                        String path = saveTmpFile(fbuf, part_data_start, part_data_end - part_data_start);
626  
                        if (!files.containsKey(part_name)) {
627  
                            files.put(part_name, path);
628  
                        } else {
629  
                            int count = 2;
630  
                            while (files.containsKey(part_name + count)) {
631  
                                count++;
632  
                            }
633  
                            files.put(part_name + count, path);
634  
                        }
635  
                        parms.put(part_name, file_name);
636  
                    }
637  
                }
638  
            } catch (ResponseException re) {
639  
                throw re;
640  
            } catch (Exception e) {
641  
                throw new ResponseException(Response.Status.INTERNAL_ERROR, e.toString());
642  
            }
643  
        }
644  
645  
        /**
646  
         * Decodes parameters in percent-encoded URI-format ( e.g.
647  
         * "name=Jack%20Daniels&pass=Single%20Malt" ) and adds them to given
648  
         * Map. NOTE: this doesn't support multiple identical keys due to the
649  
         * simplicity of Map.
650  
         */
651  
        private void decodeParms(String parms, Map<String, String> p) {
652  
            if (parms == null) {
653  
                this.queryParameterString = "";
654  
                return;
655  
            }
656  
657  
            this.queryParameterString = parms;
658  
            StringTokenizer st = new StringTokenizer(parms, "&");
659  
            while (st.hasMoreTokens()) {
660  
                String e = st.nextToken();
661  
                int sep = e.indexOf('=');
662  
                if (sep >= 0) {
663  
                    p.put(decodePercent(e.substring(0, sep)).trim(), decodePercent(e.substring(sep + 1)));
664  
                } else {
665  
                    p.put(decodePercent(e).trim(), "");
666  
                }
667  
            }
668  
        }
669  
670  
        @Override
671  
        public void execute() throws IOException {
672  
            Response r = null;
673  
            try {
674  
                // Read the first 8192 bytes.
675  
                // The full header should fit in here.
676  
                // Apache's default header limit is 8KB.
677  
                // Do NOT assume that a single read will get the entire header
678  
                // at once!
679  
                byte[] buf = new byte[HTTPSession.BUFSIZE];
680  
                this.splitbyte = 0;
681  
                this.rlen = 0;
682  
683  
                int read = -1;
684  
                try {
685  
                    read = this.inputStream.read(buf, 0, HTTPSession.BUFSIZE);
686  
                } catch (Exception e) {
687  
                    safeClose(this.inputStream);
688  
                    safeClose(this.outputStream);
689  
                    throw new SocketException("NanoHttpd Shutdown");
690  
                }
691  
                if (read == -1) {
692  
                    // socket was been closed
693  
                    safeClose(this.inputStream);
694  
                    safeClose(this.outputStream);
695  
                    throw new SocketException("NanoHttpd Shutdown");
696  
                }
697  
                while (read > 0) {
698  
                    this.rlen += read;
699  
                    this.splitbyte = findHeaderEnd(buf, this.rlen);
700  
                    if (this.splitbyte > 0) {
701  
                        break;
702  
                    }
703  
                    read = this.inputStream.read(buf, this.rlen, HTTPSession.BUFSIZE - this.rlen);
704  
                }
705  
706  
                if (this.splitbyte < this.rlen) {
707  
                    this.inputStream.unread(buf, this.splitbyte, this.rlen - this.splitbyte);
708  
                }
709  
710  
                this.parms = new HashMap<String, String>();
711  
                if (null == this.headers) {
712  
                    this.headers = new HashMap<String, String>();
713  
                } else {
714  
                    this.headers.clear();
715  
                }
716  
717  
                if (null != this.remoteIp) {
718  
                    this.headers.put("remote-addr", this.remoteIp);
719  
                    this.headers.put("http-client-ip", this.remoteIp);
720  
                }
721  
722  
                // Create a BufferedReader for parsing the header.
723  
                BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, this.rlen)));
724  
725  
                // Decode the header into parms and header java properties
726  
                Map<String, String> pre = new HashMap<String, String>();
727  
                decodeHeader(hin, pre, this.parms, this.headers);
728  
729  
                this.method = Method.lookup(pre.get("method"));
730  
                if (this.method == null) {
731  
                    throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error.");
732  
                }
733  
734  
                this.uri = pre.get("uri");
735  
736  
                this.cookies = new CookieHandler(this.headers);
737  
738  
                String connection = this.headers.get("connection");
739  
                boolean keepAlive = protocolVersion.equals("HTTP/1.1") && (connection == null || !connection.matches("(?i).*close.*"));
740  
741  
                // Ok, now do the serve()
742  
                r = serve(this);
743  
                if (r == null) {
744  
                    throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");
745  
                } else {
746  
                    String acceptEncoding = this.headers.get("accept-encoding");
747  
                    this.cookies.unloadQueue(r);
748  
                    r.setRequestMethod(this.method);
749  
                    r.setGzipEncoding(useGzipWhenAccepted(r) && acceptEncoding != null && acceptEncoding.contains("gzip"));
750  
                    r.setKeepAlive(keepAlive);
751  
                    r.send(this.outputStream);
752  
                }
753  
                if (!keepAlive || "close".equalsIgnoreCase(r.getHeader("connection"))) {
754  
                    throw new SocketException("NanoHttpd Shutdown");
755  
                }
756  
            } catch (SocketException e) {
757  
                // throw it out to close socket object (finalAccept)
758  
                throw e;
759  
            } catch (SocketTimeoutException ste) {
760  
                // treat socket timeouts the same way we treat socket exceptions
761  
                // i.e. close the stream & finalAccept object by throwing the
762  
                // exception up the call stack.
763  
                throw ste;
764  
            } catch (IOException ioe) {
765  
                Response resp = newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
766  
                resp.send(this.outputStream);
767  
                safeClose(this.outputStream);
768  
            } catch (ResponseException re) {
769  
                Response resp = newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
770  
                resp.send(this.outputStream);
771  
                safeClose(this.outputStream);
772  
            } finally {
773  
                safeClose(r);
774  
                this.tempFileManager.clear();
775  
            }
776  
        }
777  
778  
        /**
779  
         * Find byte index separating header from body. It must be the last byte
780  
         * of the first two sequential new lines.
781  
         */
782  
        private int findHeaderEnd(final byte[] buf, int rlen) {
783  
            int splitbyte = 0;
784  
            while (splitbyte + 3 < rlen) {
785  
                if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') {
786  
                    return splitbyte + 4;
787  
                }
788  
                splitbyte++;
789  
            }
790  
            return 0;
791  
        }
792  
793  
        /**
794  
         * Find the byte positions where multipart boundaries start. This reads
795  
         * a large block at a time and uses a temporary buffer to optimize
796  
         * (memory mapped) file access.
797  
         */
798  
        private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) {
799  
            int[] res = new int[0];
800  
            if (b.remaining() < boundary.length) {
801  
                return res;
802  
            }
803  
804  
            int search_window_pos = 0;
805  
            byte[] search_window = new byte[4 * 1024 + boundary.length];
806  
807  
            int first_fill = (b.remaining() < search_window.length) ? b.remaining() : search_window.length;
808  
            b.get(search_window, 0, first_fill);
809  
            int new_bytes = first_fill - boundary.length;
810  
811  
            do {
812  
                // Search the search_window
813  
                for (int j = 0; j < new_bytes; j++) {
814  
                    for (int i = 0; i < boundary.length; i++) {
815  
                        if (search_window[j + i] != boundary[i])
816  
                            break;
817  
                        if (i == boundary.length - 1) {
818  
                            // Match found, add it to results
819  
                            int[] new_res = new int[res.length + 1];
820  
                            System.arraycopy(res, 0, new_res, 0, res.length);
821  
                            new_res[res.length] = search_window_pos + j;
822  
                            res = new_res;
823  
                        }
824  
                    }
825  
                }
826  
                search_window_pos += new_bytes;
827  
828  
                // Copy the end of the buffer to the start
829  
                System.arraycopy(search_window, search_window.length - boundary.length, search_window, 0, boundary.length);
830  
831  
                // Refill search_window
832  
                new_bytes = search_window.length - boundary.length;
833  
                new_bytes = (b.remaining() < new_bytes) ? b.remaining() : new_bytes;
834  
                b.get(search_window, boundary.length, new_bytes);
835  
            } while (new_bytes > 0);
836  
            return res;
837  
        }
838  
839  
        @Override
840  
        public CookieHandler getCookies() {
841  
            return this.cookies;
842  
        }
843  
844  
        @Override
845  
        public final Map<String, String> getHeaders() {
846  
            return this.headers;
847  
        }
848  
849  
        @Override
850  
        public final InputStream getInputStream() {
851  
            return this.inputStream;
852  
        }
853  
854  
        @Override
855  
        public final Method getMethod() {
856  
            return this.method;
857  
        }
858  
859  
        @Override
860  
        public final Map<String, String> getParms() {
861  
            return this.parms;
862  
        }
863  
864  
        @Override
865  
        public String getQueryParameterString() {
866  
            return this.queryParameterString;
867  
        }
868  
869  
        private RandomAccessFile getTmpBucket() {
870  
            try {
871  
                TempFile tempFile = this.tempFileManager.createTempFile();
872  
                return new RandomAccessFile(tempFile.getName(), "rw");
873  
            } catch (Exception e) {
874  
                throw new Error(e); // we won't recover, so throw an error
875  
            }
876  
        }
877  
878  
        @Override
879  
        public final String getUri() {
880  
            return this.uri;
881  
        }
882  
883  
        @Override
884  
        public void parseBody(Map<String, String> files) throws IOException, ResponseException {
885  
            final int REQUEST_BUFFER_LEN = 512;
886  
            final int MEMORY_STORE_LIMIT = 1024;
887  
            RandomAccessFile randomAccessFile = null;
888  
            try {
889  
                long size;
890  
                if (this.headers.containsKey("content-length")) {
891  
                    size = Integer.parseInt(this.headers.get("content-length"));
892  
                } else if (this.splitbyte < this.rlen) {
893  
                    size = this.rlen - this.splitbyte;
894  
                } else {
895  
                    size = 0;
896  
                }
897  
898  
                ByteArrayOutputStream baos = null;
899  
                DataOutput request_data_output = null;
900  
901  
                // Store the request in memory or a file, depending on size
902  
                if (size < MEMORY_STORE_LIMIT) {
903  
                    baos = new ByteArrayOutputStream();
904  
                    request_data_output = new DataOutputStream(baos);
905  
                } else {
906  
                    randomAccessFile = getTmpBucket();
907  
                    request_data_output = randomAccessFile;
908  
                }
909  
910  
                // Read all the body and write it to request_data_output
911  
                byte[] buf = new byte[REQUEST_BUFFER_LEN];
912  
                while (this.rlen >= 0 && size > 0) {
913  
                    this.rlen = this.inputStream.read(buf, 0, (int) Math.min(size, REQUEST_BUFFER_LEN));
914  
                    size -= this.rlen;
915  
                    if (this.rlen > 0) {
916  
                        request_data_output.write(buf, 0, this.rlen);
917  
                    }
918  
                }
919  
920  
                ByteBuffer fbuf = null;
921  
                if (baos != null) {
922  
                    fbuf = ByteBuffer.wrap(baos.toByteArray(), 0, baos.size());
923  
                } else {
924  
                    fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
925  
                    randomAccessFile.seek(0);
926  
                }
927  
928  
                // If the method is POST, there may be parameters
929  
                // in data section, too, read it:
930  
                if (Method.POST.equals(this.method)) {
931  
                    String contentType = "";
932  
                    String contentTypeHeader = this.headers.get("content-type");
933  
934  
                    StringTokenizer st = null;
935  
                    if (contentTypeHeader != null) {
936  
                        st = new StringTokenizer(contentTypeHeader, ",; ");
937  
                        if (st.hasMoreTokens()) {
938  
                            contentType = st.nextToken();
939  
                        }
940  
                    }
941  
942  
                    if ("multipart/form-data".equalsIgnoreCase(contentType)) {
943  
                        // Handle multipart/form-data
944  
                        if (!st.hasMoreTokens()) {
945  
                            throw new ResponseException(Response.Status.BAD_REQUEST,
946  
                                    "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html");
947  
                        }
948  
949  
                        String boundaryStartString = "boundary=";
950  
                        int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length();
951  
                        String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length());
952  
                        if (boundary.startsWith("\"") && boundary.endsWith("\"")) {
953  
                            boundary = boundary.substring(1, boundary.length() - 1);
954  
                        }
955  
956  
                        decodeMultipartFormData(boundary, fbuf, this.parms, files);
957  
                    } else {
958  
                        byte[] postBytes = new byte[fbuf.remaining()];
959  
                        fbuf.get(postBytes);
960  
                        String postLine = new String(postBytes).trim();
961  
                        // Handle application/x-www-form-urlencoded
962  
                        if ("application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) {
963  
                            decodeParms(postLine, this.parms);
964  
                        } else if (postLine.length() != 0) {
965  
                            // Special case for raw POST data => create a
966  
                            // special files entry "postData" with raw content
967  
                            // data
968  
                            files.put("postData", postLine);
969  
                        }
970  
                    }
971  
                } else if (Method.PUT.equals(this.method)) {
972  
                    files.put("content", saveTmpFile(fbuf, 0, fbuf.limit()));
973  
                }
974  
            } finally {
975  
                safeClose(randomAccessFile);
976  
            }
977  
        }
978  
979  
        /**
980  
         * Retrieves the content of a sent file and saves it to a temporary
981  
         * file. The full path to the saved file is returned.
982  
         */
983  
        private String saveTmpFile(ByteBuffer b, int offset, int len) {
984  
            String path = "";
985  
            if (len > 0) {
986  
                FileOutputStream fileOutputStream = null;
987  
                try {
988  
                    TempFile tempFile = this.tempFileManager.createTempFile();
989  
                    ByteBuffer src = b.duplicate();
990  
                    fileOutputStream = new FileOutputStream(tempFile.getName());
991  
                    FileChannel dest = fileOutputStream.getChannel();
992  
                    src.position(offset).limit(offset + len);
993  
                    dest.write(src.slice());
994  
                    path = tempFile.getName();
995  
                } catch (Exception e) { // Catch exception if any
996  
                    throw new Error(e); // we won't recover, so throw an error
997  
                } finally {
998  
                    safeClose(fileOutputStream);
999  
                }
1000  
            }
1001  
            return path;
1002  
        }
1003  
    }
1004  
1005  
    /**
1006  
     * Handles one session, i.e. parses the HTTP request and returns the
1007  
     * response.
1008  
     */
1009  
    public interface IHTTPSession {
1010  
1011  
        void execute() throws IOException;
1012  
1013  
        CookieHandler getCookies();
1014  
1015  
        Map<String, String> getHeaders();
1016  
1017  
        InputStream getInputStream();
1018  
1019  
        Method getMethod();
1020  
1021  
        Map<String, String> getParms();
1022  
1023  
        String getQueryParameterString();
1024  
1025  
        /**
1026  
         * @return the path part of the URL.
1027  
         */
1028  
        String getUri();
1029  
1030  
        /**
1031  
         * Adds the files in the request body to the files map.
1032  
         * 
1033  
         * @param files
1034  
         *            map to modify
1035  
         */
1036  
        void parseBody(Map<String, String> files) throws IOException, ResponseException;
1037  
    }
1038  
1039  
    /**
1040  
     * HTTP Request methods, with the ability to decode a <code>String</code>
1041  
     * back to its enum value.
1042  
     */
1043  
    public enum Method {
1044  
        GET,
1045  
        PUT,
1046  
        POST,
1047  
        DELETE,
1048  
        HEAD,
1049  
        OPTIONS,
1050  
        TRACE,
1051  
        CONNECT,
1052  
        PATCH;
1053  
1054  
        static Method lookup(String method) {
1055  
            for (Method m : Method.values()) {
1056  
                if (m.toString().equalsIgnoreCase(method)) {
1057  
                    return m;
1058  
                }
1059  
            }
1060  
            return null;
1061  
        }
1062  
    }
1063  
1064  
    /**
1065  
     * HTTP response. Return one of these from serve().
1066  
     */
1067  
    public static class Response implements Closeable {
1068  
1069  
        public interface IStatus {
1070  
1071  
            String getDescription();
1072  
1073  
            int getRequestStatus();
1074  
        }
1075  
1076  
        /**
1077  
         * Some HTTP response status codes
1078  
         */
1079  
        public enum Status implements IStatus {
1080  
            SWITCH_PROTOCOL(101, "Switching Protocols"),
1081  
            OK(200, "OK"),
1082  
            CREATED(201, "Created"),
1083  
            ACCEPTED(202, "Accepted"),
1084  
            NO_CONTENT(204, "No Content"),
1085  
            PARTIAL_CONTENT(206, "Partial Content"),
1086  
            REDIRECT(301, "Moved Permanently"),
1087  
            NOT_MODIFIED(304, "Not Modified"),
1088  
            BAD_REQUEST(400, "Bad Request"),
1089  
            UNAUTHORIZED(401, "Unauthorized"),
1090  
            FORBIDDEN(403, "Forbidden"),
1091  
            NOT_FOUND(404, "Not Found"),
1092  
            METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
1093  
            REQUEST_TIMEOUT(408, "Request Timeout"),
1094  
            RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"),
1095  
            INTERNAL_ERROR(500, "Internal Server Error"),
1096  
            UNSUPPORTED_HTTP_VERSION(505, "HTTP Version Not Supported");
1097  
1098  
            private final int requestStatus;
1099  
1100  
            private final String description;
1101  
1102  
            Status(int requestStatus, String description) {
1103  
                this.requestStatus = requestStatus;
1104  
                this.description = description;
1105  
            }
1106  
1107  
            @Override
1108  
            public String getDescription() {
1109  
                return "" + this.requestStatus + " " + this.description;
1110  
            }
1111  
1112  
            @Override
1113  
            public int getRequestStatus() {
1114  
                return this.requestStatus;
1115  
            }
1116  
1117  
        }
1118  
1119  
        /**
1120  
         * Output stream that will automatically send every write to the wrapped
1121  
         * OutputStream according to chunked transfer:
1122  
         * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1
1123  
         */
1124  
        private static class ChunkedOutputStream extends FilterOutputStream {
1125  
1126  
            public ChunkedOutputStream(OutputStream out) {
1127  
                super(out);
1128  
            }
1129  
1130  
            @Override
1131  
            public void write(int b) throws IOException {
1132  
                byte[] data = {
1133  
                    (byte) b
1134  
                };
1135  
                write(data, 0, 1);
1136  
            }
1137  
1138  
            @Override
1139  
            public void write(byte[] b) throws IOException {
1140  
                write(b, 0, b.length);
1141  
            }
1142  
1143  
            @Override
1144  
            public void write(byte[] b, int off, int len) throws IOException {
1145  
                if (len == 0)
1146  
                    return;
1147  
                out.write(String.format("%x\r\n", len).getBytes());
1148  
                out.write(b, off, len);
1149  
                out.write("\r\n".getBytes());
1150  
            }
1151  
1152  
            public void finish() throws IOException {
1153  
                out.write("0\r\n\r\n".getBytes());
1154  
            }
1155  
1156  
        }
1157  
1158  
        /**
1159  
         * HTTP status code after processing, e.g. "200 OK", Status.OK
1160  
         */
1161  
        private IStatus status;
1162  
1163  
        /**
1164  
         * MIME type of content, e.g. "text/html"
1165  
         */
1166  
        private String mimeType;
1167  
1168  
        /**
1169  
         * Data of the response, may be null.
1170  
         */
1171  
        private InputStream data;
1172  
1173  
        private long contentLength;
1174  
1175  
        /**
1176  
         * Headers for the HTTP response. Use addHeader() to add lines.
1177  
         */
1178  
        private final Map<String, String> header = new HashMap<String, String>();
1179  
1180  
        /**
1181  
         * The request method that spawned this response.
1182  
         */
1183  
        private Method requestMethod;
1184  
1185  
        /**
1186  
         * Use chunkedTransfer
1187  
         */
1188  
        private boolean chunkedTransfer;
1189  
1190  
        private boolean encodeAsGzip;
1191  
1192  
        private boolean keepAlive;
1193  
1194  
        /**
1195  
         * Creates a fixed length response if totalBytes>=0, otherwise chunked.
1196  
         */
1197  
        protected Response(IStatus status, String mimeType, InputStream data, long totalBytes) {
1198  
            this.status = status;
1199  
            this.mimeType = mimeType;
1200  
            if (data == null) {
1201  
                this.data = new ByteArrayInputStream(new byte[0]);
1202  
                this.contentLength = 0L;
1203  
            } else {
1204  
                this.data = data;
1205  
                this.contentLength = totalBytes;
1206  
            }
1207  
            this.chunkedTransfer = this.contentLength < 0;
1208  
            keepAlive = true;
1209  
        }
1210  
1211  
        @Override
1212  
        public void close() throws IOException {
1213  
            if (this.data != null) {
1214  
                this.data.close();
1215  
            }
1216  
        }
1217  
1218  
        /**
1219  
         * Adds given line to the header.
1220  
         */
1221  
        public void addHeader(String name, String value) {
1222  
            this.header.put(name, value);
1223  
        }
1224  
1225  
        public InputStream getData() {
1226  
            return this.data;
1227  
        }
1228  
1229  
        public String getHeader(String name) {
1230  
            for (String headerName : header.keySet()) {
1231  
                if (headerName.equalsIgnoreCase(name)) {
1232  
                    return header.get(headerName);
1233  
                }
1234  
            }
1235  
            return null;
1236  
        }
1237  
1238  
        public String getMimeType() {
1239  
            return this.mimeType;
1240  
        }
1241  
1242  
        public Method getRequestMethod() {
1243  
            return this.requestMethod;
1244  
        }
1245  
1246  
        public IStatus getStatus() {
1247  
            return this.status;
1248  
        }
1249  
1250  
        public void setGzipEncoding(boolean encodeAsGzip) {
1251  
            this.encodeAsGzip = encodeAsGzip;
1252  
        }
1253  
1254  
        public void setKeepAlive(boolean useKeepAlive) {
1255  
            this.keepAlive = useKeepAlive;
1256  
        }
1257  
1258  
        private boolean headerAlreadySent(Map<String, String> header, String name) {
1259  
            boolean alreadySent = false;
1260  
            for (String headerName : header.keySet()) {
1261  
                alreadySent |= headerName.equalsIgnoreCase(name);
1262  
            }
1263  
            return alreadySent;
1264  
        }
1265  
1266  
        /**
1267  
         * Sends given response to the socket.
1268  
         */
1269  
        protected void send(OutputStream outputStream) {
1270  
            String mime = this.mimeType;
1271  
            SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
1272  
            gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));
1273  
1274  
            try {
1275  
                if (this.status == null) {
1276  
                    throw new Error("sendResponse(): Status can't be null.");
1277  
                }
1278  
                PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")), false);
1279  
                pw.print("HTTP/1.1 " + this.status.getDescription() + " \r\n");
1280  
1281  
                if (mime != null) {
1282  
                    pw.print("Content-Type: " + mime + "\r\n");
1283  
                }
1284  
1285  
                if (this.header == null || this.header.get("Date") == null) {
1286  
                    pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n");
1287  
                }
1288  
1289  
                if (this.header != null) {
1290  
                    for (String key : this.header.keySet()) {
1291  
                        String value = this.header.get(key);
1292  
                        pw.print(key + ": " + value + "\r\n");
1293  
                    }
1294  
                }
1295  
1296  
                if (!headerAlreadySent(header, "connection")) {
1297  
                    pw.print("Connection: " + (this.keepAlive ? "keep-alive" : "close") + "\r\n");
1298  
                }
1299  
1300  
                if (headerAlreadySent(this.header, "content-length")) {
1301  
                    encodeAsGzip = false;
1302  
                }
1303  
1304  
                if (encodeAsGzip) {
1305  
                    pw.print("Content-Encoding: gzip\r\n");
1306  
                    setChunkedTransfer(true);
1307  
                }
1308  
1309  
                long pending = this.data != null ? this.contentLength : 0;
1310  
                if (this.requestMethod != Method.HEAD && this.chunkedTransfer) {
1311  
                    pw.print("Transfer-Encoding: chunked\r\n");
1312  
                } else if (!encodeAsGzip) {
1313  
                    pending = sendContentLengthHeaderIfNotAlreadyPresent(pw, this.header, pending);
1314  
                }
1315  
                pw.print("\r\n");
1316  
                pw.flush();
1317  
                sendBodyWithCorrectTransferAndEncoding(outputStream, pending);
1318  
                outputStream.flush();
1319  
                safeClose(this.data);
1320  
            } catch (IOException ioe) {
1321  
                NanoHTTPD.LOG.log(Level.SEVERE, "Could not send response to the client", ioe);
1322  
            }
1323  
        }
1324  
1325  
        private void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) throws IOException {
1326  
            if (this.requestMethod != Method.HEAD && this.chunkedTransfer) {
1327  
                ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream);
1328  
                sendBodyWithCorrectEncoding(chunkedOutputStream, -1);
1329  
                chunkedOutputStream.finish();
1330  
            } else {
1331  
                sendBodyWithCorrectEncoding(outputStream, pending);
1332  
            }
1333  
        }
1334  
1335  
        private void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException {
1336  
            if (encodeAsGzip) {
1337  
                GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
1338  
                sendBody(gzipOutputStream, -1);
1339  
                gzipOutputStream.finish();
1340  
            } else {
1341  
                sendBody(outputStream, pending);
1342  
            }
1343  
        }
1344  
1345  
        /**
1346  
         * Sends the body to the specified OutputStream. The pending parameter
1347  
         * limits the maximum amounts of bytes sent unless it is -1, in which
1348  
         * case everything is sent.
1349  
         * 
1350  
         * @param outputStream
1351  
         *            the OutputStream to send data to
1352  
         * @param pending
1353  
         *            -1 to send everything, otherwise sets a max limit to the
1354  
         *            number of bytes sent
1355  
         * @throws IOException
1356  
         *             if something goes wrong while sending the data.
1357  
         */
1358  
        private void sendBody(OutputStream outputStream, long pending) throws IOException {
1359  
            long BUFFER_SIZE = 16 * 1024;
1360  
            byte[] buff = new byte[(int) BUFFER_SIZE];
1361  
            boolean sendEverything = pending == -1;
1362  
            while (pending > 0 || sendEverything) {
1363  
                long bytesToRead = sendEverything ? BUFFER_SIZE : Math.min(pending, BUFFER_SIZE);
1364  
                int read = this.data.read(buff, 0, (int) bytesToRead);
1365  
                if (read <= 0) {
1366  
                    break;
1367  
                }
1368  
                outputStream.write(buff, 0, read);
1369  
                if (!sendEverything) {
1370  
                    pending -= read;
1371  
                }
1372  
            }
1373  
        }
1374  
1375  
        protected long sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header, long size) {
1376  
            for (String headerName : header.keySet()) {
1377  
                if (headerName.equalsIgnoreCase("content-length")) {
1378  
                    try {
1379  
                        return Long.parseLong(header.get(headerName));
1380  
                    } catch (NumberFormatException ex) {
1381  
                        return size;
1382  
                    }
1383  
                }
1384  
            }
1385  
1386  
            pw.print("Content-Length: " + size + "\r\n");
1387  
            return size;
1388  
        }
1389  
1390  
        public void setChunkedTransfer(boolean chunkedTransfer) {
1391  
            this.chunkedTransfer = chunkedTransfer;
1392  
        }
1393  
1394  
        public void setData(InputStream data) {
1395  
            this.data = data;
1396  
        }
1397  
1398  
        public void setMimeType(String mimeType) {
1399  
            this.mimeType = mimeType;
1400  
        }
1401  
1402  
        public void setRequestMethod(Method requestMethod) {
1403  
            this.requestMethod = requestMethod;
1404  
        }
1405  
1406  
        public void setStatus(IStatus status) {
1407  
            this.status = status;
1408  
        }
1409  
    }
1410  
1411  
    public static final class ResponseException extends Exception {
1412  
1413  
        private static final long serialVersionUID = 6569838532917408380L;
1414  
1415  
        private final Response.Status status;
1416  
1417  
        public ResponseException(Response.Status status, String message) {
1418  
            super(message);
1419  
            this.status = status;
1420  
        }
1421  
1422  
        public ResponseException(Response.Status status, String message, Exception e) {
1423  
            super(message, e);
1424  
            this.status = status;
1425  
        }
1426  
1427  
        public Response.Status getStatus() {
1428  
            return this.status;
1429  
        }
1430  
    }
1431  
1432  
    /**
1433  
     * The runnable that will be used for the main listening thread.
1434  
     */
1435  
    public class ServerRunnable implements Runnable {
1436  
1437  
        private final int timeout;
1438  
1439  
        private IOException bindException;
1440  
1441  
        private boolean hasBinded = false;
1442  
1443  
        private ServerRunnable(int timeout) {
1444  
            this.timeout = timeout;
1445  
        }
1446  
1447  
        @Override
1448  
        public void run() {
1449  
            try {
1450  
                myServerSocket.bind(hostname != null ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
1451  
                hasBinded = true;
1452  
            } catch (IOException e) {
1453  
                this.bindException = e;
1454  
                return;
1455  
            }
1456  
            do {
1457  
                try {
1458  
                    final Socket finalAccept = NanoHTTPD.this.myServerSocket.accept();
1459  
                    if (this.timeout > 0) {
1460  
                        finalAccept.setSoTimeout(this.timeout);
1461  
                    }
1462  
                    final InputStream inputStream = finalAccept.getInputStream();
1463  
                    NanoHTTPD.this.asyncRunner.exec(createClientHandler(finalAccept, inputStream));
1464  
                } catch (IOException e) {
1465  
                    NanoHTTPD.LOG.log(Level.FINE, "Communication with the client broken", e);
1466  
                }
1467  
            } while (!NanoHTTPD.this.myServerSocket.isClosed());
1468  
        }
1469  
    }
1470  
1471  
    /**
1472  
     * A temp file.
1473  
     * <p/>
1474  
     * <p>
1475  
     * Temp files are responsible for managing the actual temporary storage and
1476  
     * cleaning themselves up when no longer needed.
1477  
     * </p>
1478  
     */
1479  
    public interface TempFile {
1480  
1481  
        void delete() throws Exception;
1482  
1483  
        String getName();
1484  
1485  
        OutputStream open() throws Exception;
1486  
    }
1487  
1488  
    /**
1489  
     * Temp file manager.
1490  
     * <p/>
1491  
     * <p>
1492  
     * Temp file managers are created 1-to-1 with incoming requests, to create
1493  
     * and cleanup temporary files created as a result of handling the request.
1494  
     * </p>
1495  
     */
1496  
    public interface TempFileManager {
1497  
1498  
        void clear();
1499  
1500  
        TempFile createTempFile() throws Exception;
1501  
    }
1502  
1503  
    /**
1504  
     * Factory to create temp file managers.
1505  
     */
1506  
    public interface TempFileManagerFactory {
1507  
1508  
        TempFileManager create();
1509  
    }
1510  
1511  
    /**
1512  
     * Maximum time to wait on Socket.getInputStream().read() (in milliseconds)
1513  
     * This is required as the Keep-Alive HTTP connections would otherwise block
1514  
     * the socket reading thread forever (or as long the browser is open).
1515  
     */
1516  
    public static final int SOCKET_READ_TIMEOUT = 5000;
1517  
1518  
    /**
1519  
     * Common MIME type for dynamic content: plain text
1520  
     */
1521  
    public static final String MIME_PLAINTEXT = "text/plain";
1522  
1523  
    /**
1524  
     * Common MIME type for dynamic content: html
1525  
     */
1526  
    public static final String MIME_HTML = "text/html";
1527  
1528  
    /**
1529  
     * Pseudo-Parameter to use to store the actual query string in the
1530  
     * parameters map for later re-processing.
1531  
     */
1532  
    private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING";
1533  
1534  
    /**
1535  
     * logger to log to.
1536  
     */
1537  
    private static final Logger LOG = Logger.getLogger(NanoHTTPD.class.getName());
1538  
1539  
    /**
1540  
     * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an
1541  
     * array of loaded KeyManagers. These objects must properly
1542  
     * loaded/initialized by the caller.
1543  
     */
1544  
    public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {
1545  
        SSLServerSocketFactory res = null;
1546  
        try {
1547  
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
1548  
            trustManagerFactory.init(loadedKeyStore);
1549  
            SSLContext ctx = SSLContext.getInstance("TLS");
1550  
            ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
1551  
            res = ctx.getServerSocketFactory();
1552  
        } catch (Exception e) {
1553  
            throw new IOException(e.getMessage());
1554  
        }
1555  
        return res;
1556  
    }
1557  
1558  
    /**
1559  
     * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a
1560  
     * loaded KeyManagerFactory. These objects must properly loaded/initialized
1561  
     * by the caller.
1562  
     */
1563  
    public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {
1564  
        SSLServerSocketFactory res = null;
1565  
        try {
1566  
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
1567  
            trustManagerFactory.init(loadedKeyStore);
1568  
            SSLContext ctx = SSLContext.getInstance("TLS");
1569  
            ctx.init(loadedKeyFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
1570  
            res = ctx.getServerSocketFactory();
1571  
        } catch (Exception e) {
1572  
            throw new IOException(e.getMessage());
1573  
        }
1574  
        return res;
1575  
    }
1576  
1577  
    /**
1578  
     * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
1579  
     * certificate and passphrase
1580  
     */
1581  
    public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException {
1582  
        SSLServerSocketFactory res = null;
1583  
        try {
1584  
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
1585  
            InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);
1586  
            keystore.load(keystoreStream, passphrase);
1587  
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
1588  
            trustManagerFactory.init(keystore);
1589  
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
1590  
            keyManagerFactory.init(keystore, passphrase);
1591  
            SSLContext ctx = SSLContext.getInstance("TLS");
1592  
            ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
1593  
            res = ctx.getServerSocketFactory();
1594  
        } catch (Exception e) {
1595  
            throw new IOException(e.getMessage());
1596  
        }
1597  
        return res;
1598  
    }
1599  
1600  
    private static final void safeClose(Object closeable) {
1601  
        try {
1602  
            if (closeable != null) {
1603  
                if (closeable instanceof Closeable) {
1604  
                    ((Closeable) closeable).close();
1605  
                } else if (closeable instanceof Socket) {
1606  
                    ((Socket) closeable).close();
1607  
                } else if (closeable instanceof ServerSocket) {
1608  
                    ((ServerSocket) closeable).close();
1609  
                } else {
1610  
                    throw new IllegalArgumentException("Unknown object to close");
1611  
                }
1612  
            }
1613  
        } catch (IOException e) {
1614  
            NanoHTTPD.LOG.log(Level.SEVERE, "Could not close", e);
1615  
        }
1616  
    }
1617  
1618  
    private final String hostname;
1619  
1620  
    private final int myPort;
1621  
1622  
    private ServerSocket myServerSocket;
1623  
1624  
    private SSLServerSocketFactory sslServerSocketFactory;
1625  
1626  
    private Thread myThread;
1627  
1628  
    /**
1629  
     * Pluggable strategy for asynchronously executing requests.
1630  
     */
1631  
    protected AsyncRunner asyncRunner;
1632  
1633  
    /**
1634  
     * Pluggable strategy for creating and cleaning up temporary files.
1635  
     */
1636  
    private TempFileManagerFactory tempFileManagerFactory;
1637  
1638  
    /**
1639  
     * Constructs an HTTP server on given port.
1640  
     */
1641  
    public NanoHTTPD(int port) {
1642  
        this(null, port);
1643  
    }
1644  
1645  
    // -------------------------------------------------------------------------------
1646  
    // //
1647  
    //
1648  
    // Threading Strategy.
1649  
    //
1650  
    // -------------------------------------------------------------------------------
1651  
    // //
1652  
1653  
    /**
1654  
     * Constructs an HTTP server on given hostname and port.
1655  
     */
1656  
    public NanoHTTPD(String hostname, int port) {
1657  
        this.hostname = hostname;
1658  
        this.myPort = port;
1659  
        setTempFileManagerFactory(new DefaultTempFileManagerFactory());
1660  
        setAsyncRunner(new DefaultAsyncRunner());
1661  
    }
1662  
1663  
    /**
1664  
     * Forcibly closes all connections that are open.
1665  
     */
1666  
    public synchronized void closeAllConnections() {
1667  
        stop();
1668  
    }
1669  
1670  
    /**
1671  
     * create a instance of the client handler, subclasses can return a subclass
1672  
     * of the ClientHandler.
1673  
     * 
1674  
     * @param finalAccept
1675  
     *            the socket the cleint is connected to
1676  
     * @param inputStream
1677  
     *            the input stream
1678  
     * @return the client handler
1679  
     */
1680  
    protected ClientHandler createClientHandler(final Socket finalAccept, final InputStream inputStream) {
1681  
        return new ClientHandler(inputStream, finalAccept);
1682  
    }
1683  
1684  
    /**
1685  
     * Instantiate the server runnable, can be overwritten by subclasses to
1686  
     * provide a subclass of the ServerRunnable.
1687  
     * 
1688  
     * @param timeout
1689  
     *            the socet timeout to use.
1690  
     * @return the server runnable.
1691  
     */
1692  
    protected ServerRunnable createServerRunnable(final int timeout) {
1693  
        return new ServerRunnable(timeout);
1694  
    }
1695  
1696  
    /**
1697  
     * Decode parameters from a URL, handing the case where a single parameter
1698  
     * name might have been supplied several times, by return lists of values.
1699  
     * In general these lists will contain a single element.
1700  
     * 
1701  
     * @param parms
1702  
     *            original <b>NanoHTTPD</b> parameters values, as passed to the
1703  
     *            <code>serve()</code> method.
1704  
     * @return a map of <code>String</code> (parameter name) to
1705  
     *         <code>List&lt;String&gt;</code> (a list of the values supplied).
1706  
     */
1707  
    protected Map<String, List<String>> decodeParameters(Map<String, String> parms) {
1708  
        return this.decodeParameters(parms.get(NanoHTTPD.QUERY_STRING_PARAMETER));
1709  
    }
1710  
1711  
    // -------------------------------------------------------------------------------
1712  
    // //
1713  
1714  
    /**
1715  
     * Decode parameters from a URL, handing the case where a single parameter
1716  
     * name might have been supplied several times, by return lists of values.
1717  
     * In general these lists will contain a single element.
1718  
     * 
1719  
     * @param queryString
1720  
     *            a query string pulled from the URL.
1721  
     * @return a map of <code>String</code> (parameter name) to
1722  
     *         <code>List&lt;String&gt;</code> (a list of the values supplied).
1723  
     */
1724  
    protected Map<String, List<String>> decodeParameters(String queryString) {
1725  
        Map<String, List<String>> parms = new HashMap<String, List<String>>();
1726  
        if (queryString != null) {
1727  
            StringTokenizer st = new StringTokenizer(queryString, "&");
1728  
            while (st.hasMoreTokens()) {
1729  
                String e = st.nextToken();
1730  
                int sep = e.indexOf('=');
1731  
                String propertyName = sep >= 0 ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim();
1732  
                if (!parms.containsKey(propertyName)) {
1733  
                    parms.put(propertyName, new ArrayList<String>());
1734  
                }
1735  
                String propertyValue = sep >= 0 ? decodePercent(e.substring(sep + 1)) : null;
1736  
                if (propertyValue != null) {
1737  
                    parms.get(propertyName).add(propertyValue);
1738  
                }
1739  
            }
1740  
        }
1741  
        return parms;
1742  
    }
1743  
1744  
    /**
1745  
     * Decode percent encoded <code>String</code> values.
1746  
     * 
1747  
     * @param str
1748  
     *            the percent encoded <code>String</code>
1749  
     * @return expanded form of the input, for example "foo%20bar" becomes
1750  
     *         "foo bar"
1751  
     */
1752  
    protected String decodePercent(String str) {
1753  
        String decoded = null;
1754  
        try {
1755  
            decoded = URLDecoder.decode(str, "UTF8");
1756  
        } catch (UnsupportedEncodingException ignored) {
1757  
            NanoHTTPD.LOG.log(Level.WARNING, "Encoding not supported, ignored", ignored);
1758  
        }
1759  
        return decoded;
1760  
    }
1761  
1762  
    /**
1763  
     * @return true if the gzip compression should be used if the client
1764  
     *         accespts it. Default this option is on for text content and off
1765  
     *         for everything else.
1766  
     */
1767  
    protected boolean useGzipWhenAccepted(Response r) {
1768  
        return r.getMimeType() != null && r.getMimeType().toLowerCase().contains("text/");
1769  
    }
1770  
1771  
    public final int getListeningPort() {
1772  
        return this.myServerSocket == null ? -1 : this.myServerSocket.getLocalPort();
1773  
    }
1774  
1775  
    public final boolean isAlive() {
1776  
        return wasStarted() && !this.myServerSocket.isClosed() && this.myThread.isAlive();
1777  
    }
1778  
1779  
    /**
1780  
     * Call before start() to serve over HTTPS instead of HTTP
1781  
     */
1782  
    public void makeSecure(SSLServerSocketFactory sslServerSocketFactory) {
1783  
        this.sslServerSocketFactory = sslServerSocketFactory;
1784  
    }
1785  
1786  
    /**
1787  
     * Create a response with unknown length (using HTTP 1.1 chunking).
1788  
     */
1789  
    public Response newChunkedResponse(IStatus status, String mimeType, InputStream data) {
1790  
        return new Response(status, mimeType, data, -1);
1791  
    }
1792  
1793  
    /**
1794  
     * Create a response with known length.
1795  
     */
1796  
    public Response newFixedLengthResponse(IStatus status, String mimeType, InputStream data, long totalBytes) {
1797  
        return new Response(status, mimeType, data, totalBytes);
1798  
    }
1799  
1800  
    /**
1801  
     * Create a text response with known length.
1802  
     */
1803  
    public Response newFixedLengthResponse(IStatus status, String mimeType, String txt) {
1804  
        if (txt == null) {
1805  
            return newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(new byte[0]), 0);
1806  
        } else {
1807  
            byte[] bytes;
1808  
            try {
1809  
                bytes = txt.getBytes("UTF-8");
1810  
            } catch (UnsupportedEncodingException e) {
1811  
                NanoHTTPD.LOG.log(Level.SEVERE, "encoding problem, responding nothing", e);
1812  
                bytes = new byte[0];
1813  
            }
1814  
            return newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(bytes), bytes.length);
1815  
        }
1816  
    }
1817  
1818  
    /**
1819  
     * Create a text response with known length.
1820  
     */
1821  
    public Response newFixedLengthResponse(String msg) {
1822  
        return newFixedLengthResponse(Status.OK, NanoHTTPD.MIME_HTML, msg);
1823  
    }
1824  
1825  
    /**
1826  
     * Override this to customize the server.
1827  
     * <p/>
1828  
     * <p/>
1829  
     * (By default, this returns a 404 "Not Found" plain text error response.)
1830  
     * 
1831  
     * @param session
1832  
     *            The HTTP session
1833  
     * @return HTTP response, see class Response for details
1834  
     */
1835  
    public Response serve(IHTTPSession session) {
1836  
        Map<String, String> files = new HashMap<String, String>();
1837  
        Method method = session.getMethod();
1838  
        if (Method.PUT.equals(method) || Method.POST.equals(method)) {
1839  
            try {
1840  
                session.parseBody(files);
1841  
            } catch (IOException ioe) {
1842  
                return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
1843  
            } catch (ResponseException re) {
1844  
                return newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
1845  
            }
1846  
        }
1847  
1848  
        Map<String, String> parms = session.getParms();
1849  
        parms.put(NanoHTTPD.QUERY_STRING_PARAMETER, session.getQueryParameterString());
1850  
        return serve(session.getUri(), method, session.getHeaders(), parms, files);
1851  
    }
1852  
1853  
    /**
1854  
     * Override this to customize the server.
1855  
     * <p/>
1856  
     * <p/>
1857  
     * (By default, this returns a 404 "Not Found" plain text error response.)
1858  
     * 
1859  
     * @param uri
1860  
     *            Percent-decoded URI without parameters, for example
1861  
     *            "/index.cgi"
1862  
     * @param method
1863  
     *            "GET", "POST" etc.
1864  
     * @param parms
1865  
     *            Parsed, percent decoded parameters from URI and, in case of
1866  
     *            POST, data.
1867  
     * @param headers
1868  
     *            Header entries, percent decoded
1869  
     * @return HTTP response, see class Response for details
1870  
     */
1871  
    @Deprecated
1872  
    public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) {
1873  
        return newFixedLengthResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Not Found");
1874  
    }
1875  
1876  
    /**
1877  
     * Pluggable strategy for asynchronously executing requests.
1878  
     * 
1879  
     * @param asyncRunner
1880  
     *            new strategy for handling threads.
1881  
     */
1882  
    public void setAsyncRunner(AsyncRunner asyncRunner) {
1883  
        this.asyncRunner = asyncRunner;
1884  
    }
1885  
1886  
    /**
1887  
     * Pluggable strategy for creating and cleaning up temporary files.
1888  
     * 
1889  
     * @param tempFileManagerFactory
1890  
     *            new strategy for handling temp files.
1891  
     */
1892  
    public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) {
1893  
        this.tempFileManagerFactory = tempFileManagerFactory;
1894  
    }
1895  
1896  
    /**
1897  
     * Start the server.
1898  
     * 
1899  
     * @throws IOException
1900  
     *             if the socket is in use.
1901  
     */
1902  
    public void start() throws IOException {
1903  
        start(NanoHTTPD.SOCKET_READ_TIMEOUT);
1904  
    }
1905  
1906  
    /**
1907  
     * Start the server.
1908  
     * 
1909  
     * @param timeout
1910  
     *            timeout to use for socket connections.
1911  
     * @throws IOException
1912  
     *             if the socket is in use.
1913  
     */
1914  
    public void start(final int timeout) throws IOException {
1915  
        if (this.sslServerSocketFactory != null) {
1916  
            SSLServerSocket ss = (SSLServerSocket) this.sslServerSocketFactory.createServerSocket();
1917  
            ss.setNeedClientAuth(false);
1918  
            this.myServerSocket = ss;
1919  
        } else {
1920  
            this.myServerSocket = new ServerSocket();
1921  
        }
1922  
        this.myServerSocket.setReuseAddress(true);
1923  
1924  
        ServerRunnable serverRunnable = createServerRunnable(timeout);
1925  
        this.myThread = new Thread(serverRunnable);
1926  
        this.myThread.setDaemon(true);
1927  
        this.myThread.setName("NanoHttpd Main Listener");
1928  
        this.myThread.start();
1929  
        while (!serverRunnable.hasBinded && serverRunnable.bindException == null) {
1930  
            try {
1931  
                Thread.sleep(10L);
1932  
            } catch (Throwable e) {
1933  
                // on android this may not be allowed, that's why we
1934  
                // catch throwable the wait should be very short because we are
1935  
                // just waiting for the bind of the socket
1936  
            }
1937  
        }
1938  
        if (serverRunnable.bindException != null) {
1939  
            throw serverRunnable.bindException;
1940  
        }
1941  
    }
1942  
1943  
    /**
1944  
     * Stop the server.
1945  
     */
1946  
    public void stop() {
1947  
        try {
1948  
            safeClose(this.myServerSocket);
1949  
            this.asyncRunner.closeAll();
1950  
            if (this.myThread != null) {
1951  
                this.myThread.join();
1952  
            }
1953  
        } catch (Exception e) {
1954  
            NanoHTTPD.LOG.log(Level.SEVERE, "Could not stop all connections", e);
1955  
        }
1956  
    }
1957  
1958  
    public final boolean wasStarted() {
1959  
        return this.myServerSocket != null && this.myThread != null;
1960  
    }
1961  
}

Author comment

Some version from Finland

download  show line numbers   

Travelled to 12 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

Comments [hide]

ID Author/Program Comment Date
493 #1000610 Edit suggestion:
!636
!629

main {
static Object androidContext;
static String programID;

public static void main(String[] args) throws Exception {
package fi.iki.elonen;

/*
* #%L
* NanoHttpd-Core
* %%
* Copyright (C) 2012 - 2015 nanohttpd
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the nanohttpd nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/

import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import fi.iki.elonen.NanoHTTPD.Response.IStatus;
import fi.iki.elonen.NanoHTTPD.Response.Status;

/**
* A simple, tiny, nicely embeddable HTTP server in Java
* <p/>
* <p/>
* NanoHTTPD
* <p>
* Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen,
* 2010 by Konstantinos Togias
* </p>
* <p/>
* <p/>
* <b>Features + limitations: </b>
* <ul>
* <p/>
* <li>Only one Java file</li>
* <li>Java 5 compatible</li>
* <li>Released as open source, Modified BSD licence</li>
* <li>No fixed config files, logging, authorization etc. (Implement yourself if
* you need them.)</li>
* <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT
* support in 1.25)</li>
* <li>Supports both dynamic content and file serving</li>
* <li>Supports file upload (since version 1.2, 2010)</li>
* <li>Supports partial content (streaming)</li>
* <li>Supports ETags</li>
* <li>Never caches anything</li>
* <li>Doesn't limit bandwidth, request time or simultaneous connections</li>
* <li>Default code serves files and shows all HTTP parameters and headers</li>
* <li>File server supports directory listing, index.html and index.htm</li>
* <li>File server supports partial content (streaming)</li>
* <li>File server supports ETags</li>
* <li>File server does the 301 redirection trick for directories without '/'</li>
* <li>File server supports simple skipping for files (continue download)</li>
* <li>File server serves also very long files without memory overhead</li>
* <li>Contains a built-in list of most common MIME types</li>
* <li>All header names are converted to lower case so they don't vary between
* browsers/clients</li>
* <p/>
* </ul>
* <p/>
* <p/>
* <b>How to use: </b>
* <ul>
* <p/>
* <li>Subclass and implement serve() and embed to your own program</li>
* <p/>
* </ul>
* <p/>
* See the separate "LICENSE.md" file for the distribution license (Modified BSD
* licence)
*/
public abstract class NanoHTTPD {

/**
* Pluggable strategy for asynchronously executing requests.
*/
public interface AsyncRunner {

void closeAll();

void closed(ClientHandler clientHandler);

void exec(ClientHandler code);
}

/**
* The runnable that will be used for every new client connection.
*/
public class ClientHandler implements Runnable {

private final InputStream inputStream;

private final Socket acceptSocket;

private ClientHandler(InputStream inputStream, Socket acceptSocket) {
this.inputStream = inputStream;
this.acceptSocket = acceptSocket;
}

public void close() {
safeClose(this.inputStream);
safeClose(this.acceptSocket);
}

@Override
public void run() {
OutputStream outputStream = null;
try {
outputStream = this.acceptSocket.getOutputStream();
TempFileManager tempFileManager = NanoHTTPD.this.tempFileManagerFactory.create();
HTTPSession session = new HTTPSession(tempFileManager, this.inputStream, outputStream, this.acceptSocket.getInetAddress());
while (!this.acceptSocket.isClosed()) {
session.execute();
}
} catch (Exception e) {
// When the socket is closed by the client,
// we throw our own SocketException
// to break the "keep alive" loop above. If
// the exception was anything other
// than the expected SocketException OR a
// SocketTimeoutException, print the
// stacktrace
if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())) && !(e instanceof SocketTimeoutException)) {
NanoHTTPD.LOG.log(Level.FINE, "Communication with the client broken", e);
}
} finally {
safeClose(outputStream);
safeClose(this.inputStream);
safeClose(this.acceptSocket);
NanoHTTPD.this.asyncRunner.closed(this);
}
}
}

public static class Cookie {

public static String getHTTPTime(int days) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.add(Calendar.DAY_OF_MONTH, days);
return dateFormat.format(calendar.getTime());
}

private final String n, v, e;

public Cookie(String name, String value) {
this(name, value, 30);
}

public Cookie(String name, String value, int numDays) {
this.n = name;
this.v = value;
this.e = getHTTPTime(numDays);
}

public Cookie(String name, String value, String expires) {
this.n = name;
this.v = value;
this.e = expires;
}

public String getHTTPHeader() {
String fmt = "%s=%s; expires=%s";
return String.format(fmt, this.n, this.v, this.e);
}
}

/**
* Provides rudimentary support for cookies. Doesn't support 'path',
* 'secure' nor 'httpOnly'. Feel free to improve it and/or add unsupported
* features.
*
* @author LordFokas
*/
public class CookieHandler implements Iterable<String> {

private final HashMap<String, String> cookies = new HashMap<String, String>();

private final ArrayList<Cookie> queue = new ArrayList<Cookie>();

public CookieHandler(Map<String, String> httpHeaders) {
String raw = httpHeaders.get("cookie");
if (raw != null) {
String[] tokens = raw.split(";");
for (String token : tokens) {
String[] data = token.trim().split("=");
if (data.length == 2) {
this.cookies.put(data[0], data[1]);
}
}
}
}

/**
* Set a cookie with an expiration date from a month ago, effectively
* deleting it on the client side.
*
* @param name
* The cookie name.
*/
public void delete(String name) {
set(name, "-delete-", -30);
}

@Override
public Iterator<String> iterator() {
return this.cookies.keySet().iterator();
}

/**
* Read a cookie from the HTTP Headers.
*
* @param name
* The cookie's name.
* @return The cookie's value if it exists, null otherwise.
*/
public String read(String name) {
return this.cookies.get(name);
}

public void set(Cookie cookie) {
this.queue.add(cookie);
}

/**
* Sets a cookie.
*
* @param name
* The cookie's name.
* @param value
* The cookie's value.
* @param expires
* How many days until the cookie expires.
*/
public void set(String name, String value, int expires) {
this.queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires)));
}

/**
* Internally used by the webserver to add all queued cookies into the
* Response's HTTP Headers.
*
* @param response
* The Response object to which headers the queued cookies
* will be added.
*/
public void unloadQueue(Response response) {
for (Cookie cookie : this.queue) {
response.addHeader("Set-Cookie", cookie.getHTTPHeader());
}
}
}

/**
* Default threading strategy for NanoHTTPD.
* <p/>
* <p>
* By default, the server spawns a new Thread for every incoming request.
* These are set to <i>daemon</i> status, and named according to the request
* number. The name is useful when profiling the application.
* </p>
*/
public static class DefaultAsyncRunner implements AsyncRunner {

private long requestCount;

private final List<ClientHandler> running = Collections.synchronizedList(new ArrayList<NanoHTTPD.ClientHandler>());

/**
* @return a list with currently running clients.
*/
public List<ClientHandler> getRunning() {
return running;
}

@Override
public void closeAll() {
// copy of the list for concurrency
for (ClientHandler clientHandler : new ArrayList<ClientHandler>(this.running)) {
clientHandler.close();
}
}

@Override
public void closed(ClientHandler clientHandler) {
this.running.remove(clientHandler);
}

@Override
public void exec(ClientHandler clientHandler) {
++this.requestCount;
Thread t = new Thread(clientHandler);
t.setDaemon(true);
t.setName("NanoHttpd Request Processor (#" + this.requestCount + ")");
this.running.add(clientHandler);
t.start();
}
}

/**
* Default strategy for creating and cleaning up temporary files.
* <p/>
* <p>
* By default, files are created by <code>File.createTempFile()</code> in
* the directory specified.
* </p>
*/
public static class DefaultTempFile implements TempFile {

private final File file;

private final OutputStream fstream;

public DefaultTempFile(String tempdir) throws IOException {
this.file = File.createTempFile("NanoHTTPD-", "", new File(tempdir));
this.fstream = new FileOutputStream(this.file);
}

@Override
public void delete() throws Exception {
safeClose(this.fstream);
if (!this.file.delete()) {
throw new Exception("could not delete temporary file");
}
}

@Override
public String getName() {
return this.file.getAbsolutePath();
}

@Override
public OutputStream open() throws Exception {
return this.fstream;
}
}

/**
* Default strategy for creating and cleaning up temporary files.
* <p/>
* <p>
* This class stores its files in the standard location (that is, wherever
* <code>java.io.tmpdir</code> points to). Files are added to an internal
* list, and deleted when no longer needed (that is, when
* <code>clear()</code> is invoked at the end of processing a request).
* </p>
*/
public static class DefaultTempFileManager implements TempFileManager {

private final String tmpdir;

private final List<TempFile> tempFiles;

public DefaultTempFileManager() {
this.tmpdir = System.getProperty("java.io.tmpdir");
this.tempFiles = new ArrayList<TempFile>();
}

@Override
public void clear() {
for (TempFile file : this.tempFiles) {
try {
file.delete();
} catch (Exception ignored) {
NanoHTTPD.LOG.log(Level.WARNING, "could not delete file ", ignored);
}
}
this.tempFiles.clear();
}

@Override
public TempFile createTempFile() throws Exception {
DefaultTempFile tempFile = new DefaultTempFile(this.tmpdir);
this.tempFiles.add(tempFile);
return tempFile;
}
}

/**
* Default strategy for creating and cleaning up temporary files.
*/
private class DefaultTempFileManagerFactory implements TempFileManagerFactory {

@Override
public TempFileManager create() {
return new DefaultTempFileManager();
}
}

private static final String CONTENT_DISPOSITION_REGEX = "([ |\t]*Content-Disposition[ |\t]*:)(.*)";

private static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern.compile(CONTENT_DISPOSITION_REGEX, Pattern.CASE_INSENSITIVE);

private static final String CONTENT_TYPE_REGEX = "([ |\t]*content-type[ |\t]*:)(.*)";

private static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile(CONTENT_TYPE_REGEX, Pattern.CASE_INSENSITIVE);

private static final String CONTENT_DISPOSITION_ATTRIBUTE_REGEX = "[ |\t]*([a-zA-Z]*)[ |\t]*=[ |\t]*['|\"]([^\"^']*)['|\"]";

private static final Pattern CONTENT_DISPOSITION_ATTRIBUTE_PATTERN = Pattern.compile(CONTENT_DISPOSITION_ATTRIBUTE_REGEX);

protected class HTTPSession implements IHTTPSession {

public static final int BUFSIZE = 8192;

private final TempFileManager tempFileManager;

private final OutputStream outputStream;

private final PushbackInputStream inputStream;

private int splitbyte;

private int rlen;

private String uri;

private Method method;

private Map<String, String> parms;

private Map<String, String> headers;

private CookieHandler cookies;

private String queryParameterString;

private String remoteIp;

private String protocolVersion;

public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) {
this.tempFileManager = tempFileManager;
this.inputStream = new PushbackInputStream(inputStream, HTTPSession.BUFSIZE);
this.outputStream = outputStream;
}

public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {
this.tempFileManager = tempFileManager;
this.inputStream = new PushbackInputStream(inputStream, HTTPSession.BUFSIZE);
this.outputStream = outputStream;
this.remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? "127.0.0.1" : inetAddress.getHostAddress().toString();
this.headers = new HashMap<String, String>();
}

/**
* Decodes the sent headers and loads the data into Key/value pairs
*/
private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers) throws ResponseException {
try {
// Read the request line
String inLine = in.readLine();
if (inLine == null) {
return;
}

StringTokenizer st = new StringTokenizer(inLine);
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html");
}

pre.put("method", st.nextToken());

if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html");
}

String uri = st.nextToken();

// Decode parameters from the URI
int qmi = uri.indexOf('?');
if (qmi >= 0) {
decodeParms(uri.substring(qmi + 1), parms);
uri = decodePercent(uri.substring(0, qmi));
} else {
uri = decodePercent(uri);
}

// If there's another token, its protocol version,
// followed by HTTP headers.
// NOTE: this now forces header names lower case since they are
// case insensitive and vary by client.
if (st.hasMoreTokens()) {
protocolVersion = st.nextToken();
} else {
protocolVersion = "HTTP/1.1";
NanoHTTPD.LOG.log(Level.FINE, "no protocol version specified, strange. Assuming HTTP/1.1.");
}
String line = in.readLine();
while (line != null && line.trim().length() > 0) {
int p = line.indexOf(':');
if (p >= 0) {
headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim());
}
line = in.readLine();
}

pre.put("uri", uri);
} catch (IOException ioe) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe);
}
}

/**
* Decodes the Multipart Body data and put it into Key/Value pairs.
*/
private void decodeMultipartFormData(String boundary, ByteBuffer fbuf, Map<String, String> parms, Map<String, String> files) throws ResponseException {
try {
int[] boundary_idxs = getBoundaryPositions(fbuf, boundary.getBytes());
if (boundary_idxs.length < 2) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but contains less than two boundary strings.");
}

final int MAX_HEADER_SIZE = 1024;
byte[] part_header_buff = new byte[MAX_HEADER_SIZE];
for (int bi = 0; bi < boundary_idxs.length - 1; bi++) {
fbuf.position(boundary_idxs[bi]);
int len = (fbuf.remaining() < MAX_HEADER_SIZE) ? fbuf.remaining() : MAX_HEADER_SIZE;
fbuf.get(part_header_buff, 0, len);
ByteArrayInputStream bais = new ByteArrayInputStream(part_header_buff, 0, len);
BufferedReader in = new BufferedReader(new InputStreamReader(bais, Charset.forName("US-ASCII")));

// First line is boundary string
String mpline = in.readLine();
if (!mpline.contains(boundary)) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but chunk does not start with boundary.");
}

String part_name = null, file_name = null, content_type = null;
// Parse the reset of the header lines
mpline = in.readLine();
while (mpline != null && mpline.trim().length() > 0) {
Matcher matcher = CONTENT_DISPOSITION_PATTERN.matcher(mpline);
if (matcher.matches()) {
String attributeString = matcher.group(2);
matcher = CONTENT_DISPOSITION_ATTRIBUTE_PATTERN.matcher(attributeString);
while (matcher.find()) {
String key = matcher.group(1);
if (key.equalsIgnoreCase("name")) {
part_name = matcher.group(2);
} else if (key.equalsIgnoreCase("filename")) {
file_name = matcher.group(2);
}
}
}
matcher = CONTENT_TYPE_PATTERN.matcher(mpline);
if (matcher.matches()) {
content_type = matcher.group(2).trim();
}
mpline = in.readLine();
}

// Read the part data
int part_header_len = len - (int) in.skip(MAX_HEADER_SIZE);
if (part_header_len >= len - 4) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "Multipart header size exceeds MAX_HEADER_SIZE.");
}
int part_data_start = boundary_idxs[bi] + part_header_len;
int part_data_end = boundary_idxs[bi + 1] - 4;

fbuf.position(part_data_start);
if (content_type == null) {
// Read the part into a string
byte[] data_bytes = new byte[part_data_end - part_data_start];
fbuf.get(data_bytes);
parms.put(part_name, new String(data_bytes));
} else {
// Read it into a file
String path = saveTmpFile(fbuf, part_data_start, part_data_end - part_data_start);
if (!files.containsKey(part_name)) {
files.put(part_name, path);
} else {
int count = 2;
while (files.containsKey(part_name + count)) {
count++;
}
files.put(part_name + count, path);
}
parms.put(part_name, file_name);
}
}
} catch (ResponseException re) {
throw re;
} catch (Exception e) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, e.toString());
}
}

/**
* Decodes parameters in percent-encoded URI-format ( e.g.
* "name=Jack%20Daniels&pass=Single%20Malt" ) and adds them to given
* Map. NOTE: this doesn't support multiple identical keys due to the
* simplicity of Map.
*/
private void decodeParms(String parms, Map<String, String> p) {
if (parms == null) {
this.queryParameterString = "";
return;
}

this.queryParameterString = parms;
StringTokenizer st = new StringTokenizer(parms, "&");
while (st.hasMoreTokens()) {
String e = st.nextToken();
int sep = e.indexOf('=');
if (sep >= 0) {
p.put(decodePercent(e.substring(0, sep)).trim(), decodePercent(e.substring(sep + 1)));
} else {
p.put(decodePercent(e).trim(), "");
}
}
}

@Override
public void execute() throws IOException {
Response r = null;
try {
// Read the first 8192 bytes.
// The full header should fit in here.
// Apache's default header limit is 8KB.
// Do NOT assume that a single read will get the entire header
// at once!
byte[] buf = new byte[HTTPSession.BUFSIZE];
this.splitbyte = 0;
this.rlen = 0;

int read = -1;
try {
read = this.inputStream.read(buf, 0, HTTPSession.BUFSIZE);
} catch (Exception e) {
safeClose(this.inputStream);
safeClose(this.outputStream);
throw new SocketException("NanoHttpd Shutdown");
}
if (read == -1) {
// socket was been closed
safeClose(this.inputStream);
safeClose(this.outputStream);
throw new SocketException("NanoHttpd Shutdown");
}
while (read > 0) {
this.rlen += read;
this.splitbyte = findHeaderEnd(buf, this.rlen);
if (this.splitbyte > 0) {
break;
}
read = this.inputStream.read(buf, this.rlen, HTTPSession.BUFSIZE - this.rlen);
}

if (this.splitbyte < this.rlen) {
this.inputStream.unread(buf, this.splitbyte, this.rlen - this.splitbyte);
}

this.parms = new HashMap<String, String>();
if (null == this.headers) {
this.headers = new HashMap<String, String>();
} else {
this.headers.clear();
}

if (null != this.remoteIp) {
this.headers.put("remote-addr", this.remoteIp);
this.headers.put("http-client-ip", this.remoteIp);
}

// Create a BufferedReader for parsing the header.
BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, this.rlen)));

// Decode the header into parms and header java properties
Map<String, String> pre = new HashMap<String, String>();
decodeHeader(hin, pre, this.parms, this.headers);

this.method = Method.lookup(pre.get("method"));
if (this.method == null) {
throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error.");
}

this.uri = pre.get("uri");

this.cookies = new CookieHandler(this.headers);

String connection = this.headers.get("connection");
boolean keepAlive = protocolVersion.equals("HTTP/1.1") && (connection == null || !connection.matches("(?i).*close.*"));

// Ok, now do the serve()
r = serve(this);
if (r == null) {
throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");
} else {
String acceptEncoding = this.headers.get("accept-encoding");
this.cookies.unloadQueue(r);
r.setRequestMethod(this.method);
r.setGzipEncoding(useGzipWhenAccepted(r) && acceptEncoding != null && acceptEncoding.contains("gzip"));
r.setKeepAlive(keepAlive);
r.send(this.outputStream);
}
if (!keepAlive || "close".equalsIgnoreCase(r.getHeader("connection"))) {
throw new SocketException("NanoHttpd Shutdown");
}
} catch (SocketException e) {
// throw it out to close socket object (finalAccept)
throw e;
} catch (SocketTimeoutException ste) {
// treat socket timeouts the same way we treat socket exceptions
// i.e. close the stream & finalAccept object by throwing the
// exception up the call stack.
throw ste;
} catch (IOException ioe) {
Response resp = newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
resp.send(this.outputStream);
safeClose(this.outputStream);
} catch (ResponseException re) {
Response resp = newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
resp.send(this.outputStream);
safeClose(this.outputStream);
} finally {
safeClose(r);
this.tempFileManager.clear();
}
}

/**
* Find byte index separating header from body. It must be the last byte
* of the first two sequential new lines.
*/
private int findHeaderEnd(final byte[] buf, int rlen) {
int splitbyte = 0;
while (splitbyte + 3 < rlen) {
if (buf[splitbyte] == '\r' && buf[splitbyte + 1] == '\n' && buf[splitbyte + 2] == '\r' && buf[splitbyte + 3] == '\n') {
return splitbyte + 4;
}
splitbyte++;
}
return 0;
}

/**
* Find the byte positions where multipart boundaries start. This reads
* a large block at a time and uses a temporary buffer to optimize
* (memory mapped) file access.
*/
private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) {
int[] res = new int[0];
if (b.remaining() < boundary.length) {
return res;
}

int search_window_pos = 0;
byte[] search_window = new byte[4 * 1024 + boundary.length];

int first_fill = (b.remaining() < search_window.length) ? b.remaining() : search_window.length;
b.get(search_window, 0, first_fill);
int new_bytes = first_fill - boundary.length;

do {
// Search the search_window
for (int j = 0; j < new_bytes; j++) {
for (int i = 0; i < boundary.length; i++) {
if (search_window[j + i] != boundary[i])
break;
if (i == boundary.length - 1) {
// Match found, add it to results
int[] new_res = new int[res.length + 1];
System.arraycopy(res, 0, new_res, 0, res.length);
new_res[res.length] = search_window_pos + j;
res = new_res;
}
}
}
search_window_pos += new_bytes;

// Copy the end of the buffer to the start
System.arraycopy(search_window, search_window.length - boundary.length, search_window, 0, boundary.length);

// Refill search_window
new_bytes = search_window.length - boundary.length;
new_bytes = (b.remaining() < new_bytes) ? b.remaining() : new_bytes;
b.get(search_window, boundary.length, new_bytes);
} while (new_bytes > 0);
return res;
}

@Override
public CookieHandler getCookies() {
return this.cookies;
}

@Override
public final Map<String, String> getHeaders() {
return this.headers;
}

@Override
public final InputStream getInputStream() {
return this.inputStream;
}

@Override
public final Method getMethod() {
return this.method;
}

@Override
public final Map<String, String> getParms() {
return this.parms;
}

@Override
public String getQueryParameterString() {
return this.queryParameterString;
}

private RandomAccessFile getTmpBucket() {
try {
TempFile tempFile = this.tempFileManager.createTempFile();
return new RandomAccessFile(tempFile.getName(), "rw");
} catch (Exception e) {
throw new Error(e); // we won't recover, so throw an error
}
}

@Override
public final String getUri() {
return this.uri;
}

@Override
public void parseBody(Map<String, String> files) throws IOException, ResponseException {
final int REQUEST_BUFFER_LEN = 512;
final int MEMORY_STORE_LIMIT = 1024;
RandomAccessFile randomAccessFile = null;
try {
long size;
if (this.headers.containsKey("content-length")) {
size = Integer.parseInt(this.headers.get("content-length"));
} else if (this.splitbyte < this.rlen) {
size = this.rlen - this.splitbyte;
} else {
size = 0;
}

ByteArrayOutputStream baos = null;
DataOutput request_data_output = null;

// Store the request in memory or a file, depending on size
if (size < MEMORY_STORE_LIMIT) {
baos = new ByteArrayOutputStream();
request_data_output = new DataOutputStream(baos);
} else {
randomAccessFile = getTmpBucket();
request_data_output = randomAccessFile;
}

// Read all the body and write it to request_data_output
byte[] buf = new byte[REQUEST_BUFFER_LEN];
while (this.rlen >= 0 && size > 0) {
this.rlen = this.inputStream.read(buf, 0, (int) Math.min(size, REQUEST_BUFFER_LEN));
size -= this.rlen;
if (this.rlen > 0) {
request_data_output.write(buf, 0, this.rlen);
}
}

ByteBuffer fbuf = null;
if (baos != null) {
fbuf = ByteBuffer.wrap(baos.toByteArray(), 0, baos.size());
} else {
fbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());
randomAccessFile.seek(0);
}

// If the method is POST, there may be parameters
// in data section, too, read it:
if (Method.POST.equals(this.method)) {
String contentType = "";
String contentTypeHeader = this.headers.get("content-type");

StringTokenizer st = null;
if (contentTypeHeader != null) {
st = new StringTokenizer(contentTypeHeader, ",; ");
if (st.hasMoreTokens()) {
contentType = st.nextToken();
}
}

if ("multipart/form-data".equalsIgnoreCase(contentType)) {
// Handle multipart/form-data
if (!st.hasMoreTokens()) {
throw new ResponseException(Response.Status.BAD_REQUEST,
"BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html");
}

String boundaryStartString = "boundary=";
int boundaryContentStart = contentTypeHeader.indexOf(boundaryStartString) + boundaryStartString.length();
String boundary = contentTypeHeader.substring(boundaryContentStart, contentTypeHeader.length());
if (boundary.startsWith("\"") && boundary.endsWith("\"")) {
boundary = boundary.substring(1, boundary.length() - 1);
}

decodeMultipartFormData(boundary, fbuf, this.parms, files);
} else {
byte[] postBytes = new byte[fbuf.remaining()];
fbuf.get(postBytes);
String postLine = new String(postBytes).trim();
// Handle application/x-www-form-urlencoded
if ("application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) {
decodeParms(postLine, this.parms);
} else if (postLine.length() != 0) {
// Special case for raw POST data => create a
// special files entry "postData" with raw content
// data
files.put("postData", postLine);
}
}
} else if (Method.PUT.equals(this.method)) {
files.put("content", saveTmpFile(fbuf, 0, fbuf.limit()));
}
} finally {
safeClose(randomAccessFile);
}
}

/**
* Retrieves the content of a sent file and saves it to a temporary
* file. The full path to the saved file is returned.
*/
private String saveTmpFile(ByteBuffer b, int offset, int len) {
String path = "";
if (len > 0) {
FileOutputStream fileOutputStream = null;
try {
TempFile tempFile = this.tempFileManager.createTempFile();
ByteBuffer src = b.duplicate();
fileOutputStream = new FileOutputStream(tempFile.getName());
FileChannel dest = fileOutputStream.getChannel();
src.position(offset).limit(offset + len);
dest.write(src.slice());
path = tempFile.getName();
} catch (Exception e) { // Catch exception if any
throw new Error(e); // we won't recover, so throw an error
} finally {
safeClose(fileOutputStream);
}
}
return path;
}
}

/**
* Handles one session, i.e. parses the HTTP request and returns the
* response.
*/
public interface IHTTPSession {

void execute() throws IOException;

CookieHandler getCookies();

Map<String, String> getHeaders();

InputStream getInputStream();

Method getMethod();

Map<String, String> getParms();

String getQueryParameterString();

/**
* @return the path part of the URL.
*/
String getUri();

/**
* Adds the files in the request body to the files map.
*
* @param files
* map to modify
*/
void parseBody(Map<String, String> files) throws IOException, ResponseException;
}

/**
* HTTP Request methods, with the ability to decode a <code>String</code>
* back to its enum value.
*/
public enum Method {
GET,
PUT,
POST,
DELETE,
HEAD,
OPTIONS,
TRACE,
CONNECT,
PATCH;

static Method lookup(String method) {
for (Method m : Method.values()) {
if (m.toString().equalsIgnoreCase(method)) {
return m;
}
}
return null;
}
}

/**
* HTTP response. Return one of these from serve().
*/
public static class Response implements Closeable {

public interface IStatus {

String getDescription();

int getRequestStatus();
}

/**
* Some HTTP response status codes
*/
public enum Status implements IStatus {
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, "Moved Permanently"),
NOT_MODIFIED(304, "Not Modified"),
BAD_REQUEST(400, "Bad Request"),
UNAUTHORIZED(401, "Unauthorized"),
FORBIDDEN(403, "Forbidden"),
NOT_FOUND(404, "Not Found"),
METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
REQUEST_TIMEOUT(408, "Request Timeout"),
RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"),
INTERNAL_ERROR(500, "Internal Server Error"),
UNSUPPORTED_HTTP_VERSION(505, "HTTP Version Not Supported");

private final int requestStatus;

private final String description;

Status(int requestStatus, String description) {
this.requestStatus = requestStatus;
this.description = description;
}

@Override
public String getDescription() {
return "" + this.requestStatus + " " + this.description;
}

@Override
public int getRequestStatus() {
return this.requestStatus;
}

}

/**
* Output stream that will automatically send every write to the wrapped
* OutputStream according to chunked transfer:
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1
*/
private static class ChunkedOutputStream extends FilterOutputStream {

public ChunkedOutputStream(OutputStream out) {
super(out);
}

@Override
public void write(int b) throws IOException {
byte[] data = {
(byte) b
};
write(data, 0, 1);
}

@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}

@Override
public void write(byte[] b, int off, int len) throws IOException {
if (len == 0)
return;
out.write(String.format("%x\r\n", len).getBytes());
out.write(b, off, len);
out.write("\r\n".getBytes());
}

public void finish() throws IOException {
out.write("0\r\n\r\n".getBytes());
}

}

/**
* HTTP status code after processing, e.g. "200 OK", Status.OK
*/
private IStatus status;

/**
* MIME type of content, e.g. "text/html"
*/
private String mimeType;

/**
* Data of the response, may be null.
*/
private InputStream data;

private long contentLength;

/**
* Headers for the HTTP response. Use addHeader() to add lines.
*/
private final Map<String, String> header = new HashMap<String, String>();

/**
* The request method that spawned this response.
*/
private Method requestMethod;

/**
* Use chunkedTransfer
*/
private boolean chunkedTransfer;

private boolean encodeAsGzip;

private boolean keepAlive;

/**
* Creates a fixed length response if totalBytes>=0, otherwise chunked.
*/
protected Response(IStatus status, String mimeType, InputStream data, long totalBytes) {
this.status = status;
this.mimeType = mimeType;
if (data == null) {
this.data = new ByteArrayInputStream(new byte[0]);
this.contentLength = 0L;
} else {
this.data = data;
this.contentLength = totalBytes;
}
this.chunkedTransfer = this.contentLength < 0;
keepAlive = true;
}

@Override
public void close() throws IOException {
if (this.data != null) {
this.data.close();
}
}

/**
* Adds given line to the header.
*/
public void addHeader(String name, String value) {
this.header.put(name, value);
}

public InputStream getData() {
return this.data;
}

public String getHeader(String name) {
for (String headerName : header.keySet()) {
if (headerName.equalsIgnoreCase(name)) {
return header.get(headerName);
}
}
return null;
}

public String getMimeType() {
return this.mimeType;
}

public Method getRequestMethod() {
return this.requestMethod;
}

public IStatus getStatus() {
return this.status;
}

public void setGzipEncoding(boolean encodeAsGzip) {
this.encodeAsGzip = encodeAsGzip;
}

public void setKeepAlive(boolean useKeepAlive) {
this.keepAlive = useKeepAlive;
}

private boolean headerAlreadySent(Map<String, String> header, String name) {
boolean alreadySent = false;
for (String headerName : header.keySet()) {
alreadySent |= headerName.equalsIgnoreCase(name);
}
return alreadySent;
}

/**
* Sends given response to the socket.
*/
protected void send(OutputStream outputStream) {
String mime = this.mimeType;
SimpleDateFormat gmtFrmt = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));

try {
if (this.status == null) {
throw new Error("sendResponse(): Status can't be null.");
}
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")), false);
pw.print("HTTP/1.1 " + this.status.getDescription() + " \r\n");

if (mime != null) {
pw.print("Content-Type: " + mime + "\r\n");
}

if (this.header == null || this.header.get("Date") == null) {
pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n");
}

if (this.header != null) {
for (String key : this.header.keySet()) {
String value = this.header.get(key);
pw.print(key + ": " + value + "\r\n");
}
}

if (!headerAlreadySent(header, "connection")) {
pw.print("Connection: " + (this.keepAlive ? "keep-alive" : "close") + "\r\n");
}

if (headerAlreadySent(this.header, "content-length")) {
encodeAsGzip = false;
}

if (encodeAsGzip) {
pw.print("Content-Encoding: gzip\r\n");
setChunkedTransfer(true);
}

long pending = this.data != null ? this.contentLength : 0;
if (this.requestMethod != Method.HEAD && this.chunkedTransfer) {
pw.print("Transfer-Encoding: chunked\r\n");
} else if (!encodeAsGzip) {
pending = sendContentLengthHeaderIfNotAlreadyPresent(pw, this.header, pending);
}
pw.print("\r\n");
pw.flush();
sendBodyWithCorrectTransferAndEncoding(outputStream, pending);
outputStream.flush();
safeClose(this.data);
} catch (IOException ioe) {
NanoHTTPD.LOG.log(Level.SEVERE, "Could not send response to the client", ioe);
}
}

private void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) throws IOException {
if (this.requestMethod != Method.HEAD && this.chunkedTransfer) {
ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream);
sendBodyWithCorrectEncoding(chunkedOutputStream, -1);
chunkedOutputStream.finish();
} else {
sendBodyWithCorrectEncoding(outputStream, pending);
}
}

private void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException {
if (encodeAsGzip) {
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
sendBody(gzipOutputStream, -1);
gzipOutputStream.finish();
} else {
sendBody(outputStream, pending);
}
}

/**
* Sends the body to the specified OutputStream. The pending parameter
* limits the maximum amounts of bytes sent unless it is -1, in which
* case everything is sent.
*
* @param outputStream
* the OutputStream to send data to
* @param pending
* -1 to send everything, otherwise sets a max limit to the
* number of bytes sent
* @throws IOException
* if something goes wrong while sending the data.
*/
private void sendBody(OutputStream outputStream, long pending) throws IOException {
long BUFFER_SIZE = 16 * 1024;
byte[] buff = new byte[(int) BUFFER_SIZE];
boolean sendEverything = pending == -1;
while (pending > 0 || sendEverything) {
long bytesToRead = sendEverything ? BUFFER_SIZE : Math.min(pending, BUFFER_SIZE);
int read = this.data.read(buff, 0, (int) bytesToRead);
if (read <= 0) {
break;
}
outputStream.write(buff, 0, read);
if (!sendEverything) {
pending -= read;
}
}
}

protected long sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header, long size) {
for (String headerName : header.keySet()) {
if (headerName.equalsIgnoreCase("content-length")) {
try {
return Long.parseLong(header.get(headerName));
} catch (NumberFormatException ex) {
return size;
}
}
}

pw.print("Content-Length: " + size + "\r\n");
return size;
}

public void setChunkedTransfer(boolean chunkedTransfer) {
this.chunkedTransfer = chunkedTransfer;
}

public void setData(InputStream data) {
this.data = data;
}

public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}

public void setRequestMethod(Method requestMethod) {
this.requestMethod = requestMethod;
}

public void setStatus(IStatus status) {
this.status = status;
}
}

public static final class ResponseException extends Exception {

private static final long serialVersionUID = 6569838532917408380L;

private final Response.Status status;

public ResponseException(Response.Status status, String message) {
super(message);
this.status = status;
}

public ResponseException(Response.Status status, String message, Exception e) {
super(message, e);
this.status = status;
}

public Response.Status getStatus() {
return this.status;
}
}

/**
* The runnable that will be used for the main listening thread.
*/
public class ServerRunnable implements Runnable {

private final int timeout;

private IOException bindException;

private boolean hasBinded = false;

private ServerRunnable(int timeout) {
this.timeout = timeout;
}

@Override
public void run() {
try {
myServerSocket.bind(hostname != null ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));
hasBinded = true;
} catch (IOException e) {
this.bindException = e;
return;
}
do {
try {
final Socket finalAccept = NanoHTTPD.this.myServerSocket.accept();
if (this.timeout > 0) {
finalAccept.setSoTimeout(this.timeout);
}
final InputStream inputStream = finalAccept.getInputStream();
NanoHTTPD.this.asyncRunner.exec(createClientHandler(finalAccept, inputStream));
} catch (IOException e) {
NanoHTTPD.LOG.log(Level.FINE, "Communication with the client broken", e);
}
} while (!NanoHTTPD.this.myServerSocket.isClosed());
}
}

/**
* A temp file.
* <p/>
* <p>
* Temp files are responsible for managing the actual temporary storage and
* cleaning themselves up when no longer needed.
* </p>
*/
public interface TempFile {

void delete() throws Exception;

String getName();

OutputStream open() throws Exception;
}

/**
* Temp file manager.
* <p/>
* <p>
* Temp file managers are created 1-to-1 with incoming requests, to create
* and cleanup temporary files created as a result of handling the request.
* </p>
*/
public interface TempFileManager {

void clear();

TempFile createTempFile() throws Exception;
}

/**
* Factory to create temp file managers.
*/
public interface TempFileManagerFactory {

TempFileManager create();
}

/**
* Maximum time to wait on Socket.getInputStream().read() (in milliseconds)
* This is required as the Keep-Alive HTTP connections would otherwise block
* the socket reading thread forever (or as long the browser is open).
*/
public static final int SOCKET_READ_TIMEOUT = 5000;

/**
* Common MIME type for dynamic content: plain text
*/
public static final String MIME_PLAINTEXT = "text/plain";

/**
* Common MIME type for dynamic content: html
*/
public static final String MIME_HTML = "text/html";

/**
* Pseudo-Parameter to use to store the actual query string in the
* parameters map for later re-processing.
*/
private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING";

/**
* logger to log to.
*/
private static final Logger LOG = Logger.getLogger(NanoHTTPD.class.getName());

/**
* Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an
* array of loaded KeyManagers. These objects must properly
* loaded/initialized by the caller.
*/
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {
SSLServerSocketFactory res = null;
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(loadedKeyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
res = ctx.getServerSocketFactory();
} catch (Exception e) {
throw new IOException(e.getMessage());
}
return res;
}

/**
* Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a
* loaded KeyManagerFactory. These objects must properly loaded/initialized
* by the caller.
*/
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {
SSLServerSocketFactory res = null;
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(loadedKeyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(loadedKeyFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
res = ctx.getServerSocketFactory();
} catch (Exception e) {
throw new IOException(e.getMessage());
}
return res;
}

/**
* Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
* certificate and passphrase
*/
public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException {
SSLServerSocketFactory res = null;
try {
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);
keystore.load(keystoreStream, passphrase);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, passphrase);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
res = ctx.getServerSocketFactory();
} catch (Exception e) {
throw new IOException(e.getMessage());
}
return res;
}

private static final void safeClose(Object closeable) {
try {
if (closeable != null) {
if (closeable instanceof Closeable) {
((Closeable) closeable).close();
} else if (closeable instanceof Socket) {
((Socket) closeable).close();
} else if (closeable instanceof ServerSocket) {
((ServerSocket) closeable).close();
} else {
throw new IllegalArgumentException("Unknown object to close");
}
}
} catch (IOException e) {
NanoHTTPD.LOG.log(Level.SEVERE, "Could not close", e);
}
}

private final String hostname;

private final int myPort;

private ServerSocket myServerSocket;

private SSLServerSocketFactory sslServerSocketFactory;

private Thread myThread;

/**
* Pluggable strategy for asynchronously executing requests.
*/
protected AsyncRunner asyncRunner;

/**
* Pluggable strategy for creating and cleaning up temporary files.
*/
private TempFileManagerFactory tempFileManagerFactory;

/**
* Constructs an HTTP server on given port.
*/
public NanoHTTPD(int port) {
this(null, port);
}

// -------------------------------------------------------------------------------
// //
//
// Threading Strategy.
//
// -------------------------------------------------------------------------------
// //

/**
* Constructs an HTTP server on given hostname and port.
*/
public NanoHTTPD(String hostname, int port) {
this.hostname = hostname;
this.myPort = port;
setTempFileManagerFactory(new DefaultTempFileManagerFactory());
setAsyncRunner(new DefaultAsyncRunner());
}

/**
* Forcibly closes all connections that are open.
*/
public synchronized void closeAllConnections() {
stop();
}

/**
* create a instance of the client handler, subclasses can return a subclass
* of the ClientHandler.
*
* @param finalAccept
* the socket the cleint is connected to
* @param inputStream
* the input stream
* @return the client handler
*/
protected ClientHandler createClientHandler(final Socket finalAccept, final InputStream inputStream) {
return new ClientHandler(inputStream, finalAccept);
}

/**
* Instantiate the server runnable, can be overwritten by subclasses to
* provide a subclass of the ServerRunnable.
*
* @param timeout
* the socet timeout to use.
* @return the server runnable.
*/
protected ServerRunnable createServerRunnable(final int timeout) {
return new ServerRunnable(timeout);
}

/**
* Decode parameters from a URL, handing the case where a single parameter
* name might have been supplied several times, by return lists of values.
* In general these lists will contain a single element.
*
* @param parms
* original <b>NanoHTTPD</b> parameters values, as passed to the
* <code>serve()</code> method.
* @return a map of <code>String</code> (parameter name) to
* <code>List&lt;String&gt;</code> (a list of the values supplied).
*/
protected Map<String, List<String>> decodeParameters(Map<String, String> parms) {
return this.decodeParameters(parms.get(NanoHTTPD.QUERY_STRING_PARAMETER));
}

// -------------------------------------------------------------------------------
// //

/**
* Decode parameters from a URL, handing the case where a single parameter
* name might have been supplied several times, by return lists of values.
* In g
2015-08-18 18:21:36  delete 
491 #1000604 (pitcher) 2015-08-20 15:28:24

add comment

Snippet ID: #1000408
Snippet name: Original source of NanoHTTPD.java
Eternal ID of this version: #1000408/1
Text MD5: 6705de2af002fd5b5e717b79d3b20e9f
Author: stefan
Category:
Type: Java source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-03 03:37:42
Source code size: 74515 bytes / 1961 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 1389 / 212
Referenced in: [show references]