-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathHTTPServer.java
More file actions
3086 lines (2890 loc) · 132 KB
/
Copy pathHTTPServer.java
File metadata and controls
3086 lines (2890 loc) · 132 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright © 2005-2019 Amichai Rothman
*
* This file is part of JLHTTP - the Java Lightweight HTTP Server.
*
* JLHTTP is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* JLHTTP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JLHTTP. If not, see <http://www.gnu.org/licenses/>.
*
* For additional info see http://www.freeutils.net/source/jlhttp/
*/
package net.freeutils.httpserver;
import java.io.*;
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.net.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
/**
* The {@code HTTPServer} class implements a light-weight HTTP server.
* <p>
* This server implements all functionality required by RFC 2616 ("Hypertext
* Transfer Protocol -- HTTP/1.1"), as well as some of the optional
* functionality (this is termed "conditionally compliant" in the RFC).
* In fact, a couple of bugs in the RFC itself were discovered
* (and fixed) during the development of this server.
* <p>
* <b>Feature Overview</b>
* <ul>
* <li>RFC compliant - correctness is not sacrificed for the sake of size</li>
* <li>Virtual hosts - multiple domains and subdomains per server</li>
* <li>File serving - built-in handler to serve files and folders from disk</li>
* <li>Mime type mappings - configurable via API or a standard mime.types file</li>
* <li>Directory index generation - enables browsing folder contents</li>
* <li>Welcome files - configurable default filename (e.g. index.html)</li>
* <li>All HTTP methods supported - GET/HEAD/OPTIONS/TRACE/POST/PUT/DELETE/custom</li>
* <li>Conditional statuses - ETags and If-* header support</li>
* <li>Chunked transfer encoding - for serving dynamically-generated data streams</li>
* <li>Gzip/deflate compression - reduces bandwidth and download time</li>
* <li>HTTPS - secures all server communications</li>
* <li>Partial content - download continuation (a.k.a. byte range serving)</li>
* <li>File upload - multipart/form-data handling as stream or iterator</li>
* <li>Multiple context handlers - a different handler method per URL path</li>
* <li>@Context annotations - auto-detection of context handler methods</li>
* <li>Parameter parsing - from query string or x-www-form-urlencoded body</li>
* <li>A single source file - super-easy to integrate into any application</li>
* <li>Standalone - no dependencies other than the Java runtime</li>
* <li>Small footprint - standard jar is ~50K, stripped jar is ~35K</li>
* <li>Extensible design - easy to override, add or remove functionality</li>
* <li>Reusable utility methods to simplify your custom code</li>
* <li>Extensive documentation of API and implementation (>40% of source lines)</li>
* </ul>
* <p>
* <b>Use Cases</b>
* <p>
* Being a lightweight, standalone, easily embeddable and tiny-footprint
* server, it is well-suited for
* <ul>
* <li>Resource-constrained environments such as embedded devices.
* For really extreme constraints, you can easily remove unneeded
* functionality to make it even smaller (and use the -Dstripped
* maven build option to strip away debug info, license, etc.)</li>
* <li>Unit and integration tests - fast setup/teardown times, small overhead
* and simple context handler setup make it a great web server for testing
* client components under various server response conditions.</li>
* <li>Embedding a web console into any headless application for
* administration, monitoring, or a full portable GUI.</li>
* <li>A full-fledged standalone web server serving static files,
* dynamically-generated content, REST APIs, pseudo-streaming, etc.</li>
* <li>A good reference for learning how HTTP works under the hood.</li>
* </ul>
* <p>
* <b>Implementation Notes</b>
* <p>
* The design and implementation of this server attempt to balance correctness,
* compliance, readability, size, features, extensibility and performance,
* and often prioritize them in this order, but some trade-offs must be made.
* <p>
* This server is multithreaded in its support for multiple concurrent HTTP
* connections, however most of its constituent classes are not thread-safe and
* require external synchronization if accessed by multiple threads concurrently.
* <p>
* <b>Source Structure and Documentation</b>
* <p>
* This server is intentionally written as a single source file, in order to make
* it as easy as possible to integrate into any existing project - by simply adding
* this single file to the project sources. It does, however, aim to maintain a
* structured and flexible design. There are no external package dependencies.
* <p>
* This file contains extensive documentation of its classes and methods, as
* well as implementation details and references to specific RFC sections
* which clarify the logic behind the code. It is recommended that anyone
* attempting to modify the protocol-level functionality become acquainted with
* the RFC, in order to make sure that protocol compliance is not broken.
* <p>
* <b>Getting Started</b>
* <p>
* For an example and a good starting point for learning how to use the API,
* see the {@link #main main} method at the bottom of the file, and follow
* the code into the API from there. Alternatively, you can just browse through
* the classes and utility methods and read their documentation and code.
*
* @author Amichai Rothman
* @since 2008-07-24
*/
public class HTTPServer {
/**
* The SimpleDateFormat-compatible formats of dates which must be supported.
* Note that all generated date fields must be in the RFC 1123 format only,
* while the others are supported by recipients for backwards-compatibility.
*/
public static final String[] DATE_PATTERNS = {
"EEE, dd MMM yyyy HH:mm:ss z", // RFC 822, updated by RFC 1123
"EEEE, dd-MMM-yy HH:mm:ss z", // RFC 850, obsoleted by RFC 1036
"EEE MMM d HH:mm:ss yyyy" // ANSI C's asctime() format
};
/** A GMT (UTC) timezone instance. */
protected static final TimeZone GMT = TimeZone.getTimeZone("GMT");
/** Date format strings. */
protected static final char[]
DAYS = "Sun Mon Tue Wed Thu Fri Sat".toCharArray(),
MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".toCharArray();
/** A convenience array containing the carriage-return and line feed chars. */
public static final byte[] CRLF = { 0x0d, 0x0a };
/** The HTTP status description strings. */
protected static final String[] statuses = new String[600];
static {
// initialize status descriptions lookup table
Arrays.fill(statuses, "Unknown Status");
statuses[100] = "Continue";
statuses[200] = "OK";
statuses[204] = "No Content";
statuses[206] = "Partial Content";
statuses[301] = "Moved Permanently";
statuses[302] = "Found";
statuses[304] = "Not Modified";
statuses[307] = "Temporary Redirect";
statuses[400] = "Bad Request";
statuses[401] = "Unauthorized";
statuses[403] = "Forbidden";
statuses[404] = "Not Found";
statuses[405] = "Method Not Allowed";
statuses[408] = "Request Timeout";
statuses[412] = "Precondition Failed";
statuses[413] = "Request Entity Too Large";
statuses[414] = "Request-URI Too Large";
statuses[416] = "Requested Range Not Satisfiable";
statuses[417] = "Expectation Failed";
statuses[500] = "Internal Server Error";
statuses[501] = "Not Implemented";
statuses[502] = "Bad Gateway";
statuses[503] = "Service Unavailable";
statuses[504] = "Gateway Time-out";
}
/**
* A mapping of path suffixes (e.g. file extensions) to their
* corresponding MIME types.
*/
protected static final Map<String, String> contentTypes =
new ConcurrentHashMap<String, String>();
static {
// add some default common content types
// see http://www.iana.org/assignments/media-types/ for full list
addContentType("application/font-woff", "woff");
addContentType("application/font-woff2", "woff2");
addContentType("application/java-archive", "jar");
addContentType("application/javascript", "js");
addContentType("application/json", "json");
addContentType("application/octet-stream", "exe");
addContentType("application/pdf", "pdf");
addContentType("application/x-7z-compressed", "7z");
addContentType("application/x-compressed", "tgz");
addContentType("application/x-gzip", "gz");
addContentType("application/x-tar", "tar");
addContentType("application/xhtml+xml", "xhtml");
addContentType("application/zip", "zip");
addContentType("audio/mpeg", "mp3");
addContentType("image/gif", "gif");
addContentType("image/jpeg", "jpg", "jpeg");
addContentType("image/png", "png");
addContentType("image/svg+xml", "svg");
addContentType("image/x-icon", "ico");
addContentType("text/css", "css");
addContentType("text/csv", "csv");
addContentType("text/html; charset=utf-8", "htm", "html");
addContentType("text/plain", "txt", "text", "log");
addContentType("text/xml", "xml");
}
/** The MIME types that can be compressed (prefix/suffix wildcards allowed). */
protected static String[] compressibleContentTypes =
{ "text/*", "*/javascript", "*icon", "*+xml", "*/json" };
/**
* The {@code LimitedInputStream} provides access to a limited number
* of consecutive bytes from the underlying InputStream, starting at its
* current position. If this limit is reached, it behaves as though the end
* of stream has been reached (although the underlying stream remains open
* and may contain additional data).
*/
public static class LimitedInputStream extends FilterInputStream {
protected long limit; // decremented when read, until it reaches zero
protected boolean prematureEndException;
/**
* Constructs a LimitedInputStream with the given underlying
* input stream and limit.
*
* @param in the underlying input stream
* @param limit the maximum number of bytes that may be consumed from
* the underlying stream before this stream ends. If zero or
* negative, this stream will be at its end from initialization.
* @param prematureEndException specifies the stream's behavior when
* the underlying stream end is reached before the limit is
* reached: if true, an exception is thrown, otherwise this
* stream reaches its end as well (i.e. read() returns -1)
* @throws NullPointerException if the given stream is null
*/
public LimitedInputStream(InputStream in, long limit, boolean prematureEndException) {
super(in);
if (in == null)
throw new NullPointerException("input stream is null");
this.limit = limit < 0 ? 0 : limit;
this.prematureEndException = prematureEndException;
}
@Override
public int read() throws IOException {
int res = limit == 0 ? -1 : in.read();
if (res < 0 && limit > 0 && prematureEndException)
throw new IOException("unexpected end of stream");
limit = res < 0 ? 0 : limit - 1;
return res;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int res = limit == 0 ? -1 : in.read(b, off, len > limit ? (int)limit : len);
if (res < 0 && limit > 0 && prematureEndException)
throw new IOException("unexpected end of stream");
limit = res < 0 ? 0 : limit - res;
return res;
}
@Override
public long skip(long len) throws IOException {
long res = in.skip(len > limit ? limit : len);
limit -= res;
return res;
}
@Override
public int available() throws IOException {
int res = in.available();
return res > limit ? (int)limit : res;
}
@Override
public boolean markSupported() {
return false;
}
@Override
public void close() {
limit = 0; // end this stream, but don't close the underlying stream
}
}
/**
* The {@code ChunkedInputStream} decodes an InputStream whose data has the
* "chunked" transfer encoding applied to it, providing the underlying data.
*/
public static class ChunkedInputStream extends LimitedInputStream {
protected Headers headers;
protected boolean initialized;
/**
* Constructs a ChunkedInputStream with the given underlying stream, and
* a headers container to which the stream's trailing headers will be
* added.
*
* @param in the underlying "chunked"-encoded input stream
* @param headers the headers container to which the stream's trailing
* headers will be added, or null if they are to be discarded
* @throws NullPointerException if the given stream is null
*/
public ChunkedInputStream(InputStream in, Headers headers) {
super(in, 0, true);
this.headers = headers;
}
@Override
public int read() throws IOException {
return limit <= 0 && initChunk() < 0 ? -1 : super.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return limit <= 0 && initChunk() < 0 ? -1 : super.read(b, off, len);
}
/**
* Initializes the next chunk. If the previous chunk has not yet
* ended, or the end of stream has been reached, does nothing.
*
* @return the length of the chunk, or -1 if the end of stream
* has been reached
* @throws IOException if an IO error occurs or the stream is corrupt
*/
protected long initChunk() throws IOException {
if (limit == 0) { // finished previous chunk
// read chunk-terminating CRLF if it's not the first chunk
if (initialized && readLine(in).length() > 0)
throw new IOException("chunk data must end with CRLF");
initialized = true;
limit = parseChunkSize(readLine(in)); // read next chunk size
if (limit == 0) { // last chunk has size 0
limit = -1; // mark end of stream
// read trailing headers, if any
Headers trailingHeaders = readHeaders(in);
if (headers != null)
headers.addAll(trailingHeaders);
}
}
return limit;
}
/**
* Parses a chunk-size line.
*
* @param line the chunk-size line to parse
* @return the chunk size
* @throws IllegalArgumentException if the chunk-size line is invalid
*/
protected static long parseChunkSize(String line) throws IllegalArgumentException {
int pos = line.indexOf(';');
line = pos < 0 ? line : line.substring(0, pos); // ignore params, if any
try {
return parseULong(line, 16); // throws NFE
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException(
"invalid chunk size line: \"" + line + "\"");
}
}
}
/**
* The {@code ChunkedOutputStream} encodes an OutputStream with the
* "chunked" transfer encoding. It should be used only when the content
* length is not known in advance, and with the response Transfer-Encoding
* header set to "chunked".
* <p>
* Data is written to the stream by calling the {@link #write(byte[], int, int)}
* method, which writes a new chunk per invocation. To end the stream,
* the {@link #writeTrailingChunk} method must be called or the stream closed.
*/
public static class ChunkedOutputStream extends FilterOutputStream {
protected int state; // the current stream state
/**
* Constructs a ChunkedOutputStream with the given underlying stream.
*
* @param out the underlying output stream to which the chunked stream
* is written
* @throws NullPointerException if the given stream is null
*/
public ChunkedOutputStream(OutputStream out) {
super(out);
if (out == null)
throw new NullPointerException("output stream is null");
}
/**
* Initializes a new chunk with the given size.
*
* @param size the chunk size (must be positive)
* @throws IllegalArgumentException if size is negative
* @throws IOException if an IO error occurs, or the stream has
* already been ended
*/
protected void initChunk(long size) throws IOException {
if (size < 0)
throw new IllegalArgumentException("invalid size: " + size);
if (state > 0)
out.write(CRLF); // end previous chunk
else if (state == 0)
state = 1; // start first chunk
else
throw new IOException("chunked stream has already ended");
out.write(getBytes(Long.toHexString(size)));
out.write(CRLF);
}
/**
* Writes the trailing chunk which marks the end of the stream.
*
* @param headers the (optional) trailing headers to write, or null
* @throws IOException if an error occurs
*/
public void writeTrailingChunk(Headers headers) throws IOException {
initChunk(0); // zero-sized chunk marks the end of the stream
if (headers == null)
out.write(CRLF); // empty header block
else
headers.writeTo(out);
state = -1;
}
/**
* Writes a chunk containing the given byte. This method initializes
* a new chunk of size 1, and then writes the byte as the chunk data.
*
* @param b the byte to write as a chunk
* @throws IOException if an error occurs
*/
@Override
public void write(int b) throws IOException {
write(new byte[] { (byte)b }, 0, 1);
}
/**
* Writes a chunk containing the given bytes. This method initializes
* a new chunk of the given size, and then writes the chunk data.
*
* @param b an array containing the bytes to write
* @param off the offset within the array where the data starts
* @param len the length of the data in bytes
* @throws IOException if an error occurs
* @throws IndexOutOfBoundsException if the given offset or length
* are outside the bounds of the given array
*/
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (len > 0) // zero-sized chunk is the trailing chunk
initChunk(len);
out.write(b, off, len);
}
/**
* Writes the trailing chunk if necessary, and closes the underlying stream.
*
* @throws IOException if an error occurs
*/
@Override
public void close() throws IOException {
if (state > -1)
writeTrailingChunk(null);
super.close();
}
}
/**
* The {@code MultipartInputStream} decodes an InputStream whose data has
* a "multipart/*" content type (see RFC 2046), providing the underlying
* data of its various parts.
* <p>
* The {@code InputStream} methods (e.g. {@link #read}) relate only to
* the current part, and the {@link #nextPart} method advances to the
* beginning of the next part.
*/
public static class MultipartInputStream extends FilterInputStream {
protected final byte[] boundary; // including leading CRLF--
protected final byte[] buf = new byte[4096];
protected int head, tail; // indices of current part's data in buf
protected int end; // last index of input data read into buf
protected int len; // length of found boundary
protected int state; // initial, started data, start boundary, EOS, last boundary, epilogue
/**
* Constructs a MultipartInputStream with the given underlying stream.
*
* @param in the underlying multipart stream
* @param boundary the multipart boundary
* @throws NullPointerException if the given stream or boundary is null
* @throws IllegalArgumentException if the given boundary's size is not
* between 1 and 70
*/
protected MultipartInputStream(InputStream in, byte[] boundary) {
super(in);
int len = boundary.length;
if (len == 0 || len > 70)
throw new IllegalArgumentException("invalid boundary length");
this.boundary = new byte[len + 4]; // CRLF--boundary
System.arraycopy(CRLF, 0, this.boundary, 0, 2);
this.boundary[2] = this.boundary[3] = '-';
System.arraycopy(boundary, 0, this.boundary, 4, len);
}
@Override
public int read() throws IOException {
if (!fill())
return -1;
return buf[head++] & 0xFF;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (!fill())
return -1;
len = Math.min(tail - head, len);
System.arraycopy(buf, head, b, off, len); // throws IOOBE as necessary
head += len;
return len;
}
@Override
public long skip(long len) throws IOException {
if (len <= 0 || !fill())
return 0;
len = Math.min(tail - head, len);
head += len;
return len;
}
@Override
public int available() throws IOException {
return tail - head;
}
@Override
public boolean markSupported() {
return false;
}
/**
* Advances the stream position to the beginning of the next part.
* Data read before calling this method for the first time is the preamble,
* and data read after this method returns false is the epilogue.
*
* @return true if successful, or false if there are no more parts
* @throws IOException if an error occurs
*/
public boolean nextPart() throws IOException {
while (skip(buf.length) != 0); // skip current part (until boundary)
head = tail += len; // the next part starts right after boundary
state |= 1; // started data (after first boundary)
if (state >= 8) { // found last boundary
state |= 0x10; // now beyond last boundary (epilogue)
return false;
}
findBoundary(); // update indices
return true;
}
/**
* Fills the buffer with more data from the underlying stream.
*
* @return true if there is available data for the current part,
* or false if the current part's end has been reached
* @throws IOException if an error occurs or the input format is invalid
*/
protected boolean fill() throws IOException {
// check if we already have more available data
if (head != tail) // remember that if we continue, head == tail below
return true;
// if there's no more room, shift extra unread data to beginning of buffer
if (tail > buf.length - 256) { // max boundary + whitespace supported size
System.arraycopy(buf, tail, buf, 0, end -= tail);
head = tail = 0;
}
// read more data and look for boundary (or potential partial boundary)
int read;
do {
read = super.read(buf, end, buf.length - end);
if (read < 0)
state |= 4; // end of stream (EOS)
else
end += read;
findBoundary(); // updates tail and length to next potential boundary
// if we found a partial boundary with no data before it, we must
// continue reading to determine if there is more data or not
} while (read > 0 && tail == head && len == 0);
// update and validate state
if (tail != 0) // anything but a boundary right at the beginning
state |= 1; // started data (preamble or after boundary)
if (state < 8 && len > 0)
state |= 2; // found start boundary
if ((state & 6) == 4 // EOS but no start boundary found
|| len == 0 && ((state & 0xFC) == 4 // EOS but no last and no more boundaries
|| read == 0 && tail == head)) // boundary longer than buffer
throw new IOException("missing boundary");
if (state >= 0x10) // in epilogue
tail = end; // ignore boundaries, return everything
return tail > head; // available data in current part
}
/**
* Finds the first (potential) boundary within the buffer's remaining data.
* Updates tail, length and state fields accordingly.
*
* @throws IOException if an error occurs or the input format is invalid
*/
protected void findBoundary() throws IOException {
// see RFC2046#5.1.1 for boundary syntax
len = 0;
int off = tail - ((state & 1) != 0 || buf[0] != '-' ? 0 : 2); // skip initial CRLF?
for (int end = this.end; tail < end; tail++, off = tail) {
int j = tail; // end of potential boundary
// try to match boundary value (leading CRLF is optional at first boundary)
while (j < end && j - off < boundary.length && buf[j] == boundary[j - off])
j++;
// return potential partial boundary which is cut off at end of current data
if (j + 1 >= end) // at least two more chars needed for full boundary (CRLF or --)
return;
// if we found the boundary value, expand selection to include full line
if (j - off == boundary.length) {
// check if last boundary of entire multipart
if (buf[j] == '-' && buf[j + 1] == '-') {
j += 2;
state |= 8; // found last boundary that ends multipart
}
// allow linear whitespace after boundary
while (j < end && (buf[j] == ' ' || buf[j] == '\t'))
j++;
// check for CRLF (required, except in last boundary with no epilogue)
if (j + 1 < end && buf[j] == '\r' && buf[j + 1] == '\n') // found CRLF
len = j - tail + 2; // including optional whitespace and CRLF
else if (j + 1 < end || (state & 4) != 0 && j + 1 == end) // should have found or never will
throw new IOException("boundary must end with CRLF");
else if ((state & 4) != 0) // last boundary with no CRLF at end of data is valid
len = j - tail;
return;
}
}
}
}
/**
* The {@code MultipartIterator} iterates over the parts of a multipart/form-data request.
* <p>
* For example, to support file upload from a web browser:
* <ol>
* <li>Create an HTML form which includes an input field of type "file", attributes
* method="post" and enctype="multipart/form-data", and an action URL of your choice,
* for example action="/upload". This form can be served normally like any other
* resource, e.g. from an HTML file on disk.
* <li>Add a context handler for the action path ("/upload" in this example), using either
* the explicit {@link VirtualHost#addContext} method or the {@link Context} annotation.
* <li>In the context handler implementation, construct a {@code MultipartIterator} from
* the client {@code Request}.
* <li>Iterate over the form {@link Part}s, processing each named field as appropriate -
* for the file input field, read the uploaded file using the body input stream.
* </ol>
*/
public static class MultipartIterator implements Iterator<MultipartIterator.Part> {
/**
* The {@code Part} class encapsulates a single part of the multipart.
*/
public static class Part {
public String name;
public String filename;
public Headers headers;
public InputStream body;
/**
* Returns the part's name (form field name).
*
* @return the part's name
*/
public String getName() { return name; }
/**
* Returns the part's filename (original filename entered in file form field).
*
* @return the part's filename, or null if there is none
*/
public String getFilename() { return filename; }
/**
* Returns the part's headers.
*
* @return the part's headers
*/
public Headers getHeaders() { return headers; }
/**
* Returns the part's body (form field value).
*
* @return the part's body
*/
public InputStream getBody() { return body; }
/***
* Returns the part's body as a string. If the part
* headers do not specify a charset, UTF-8 is used.
*
* @return the part's body as a string
* @throws IOException if an IO error occurs
*/
public String getString() throws IOException {
String charset = headers.getParams("Content-Type").get("charset");
return readToken(body, -1, charset == null ? "UTF-8" : charset, 8192);
}
}
protected final MultipartInputStream in;
protected boolean next;
/**
* Creates a new MultipartIterator from the given request.
*
* @param req the multipart/form-data request
* @throws IOException if an IO error occurs
* @throws IllegalArgumentException if the given request's content type
* is not multipart/form-data, or is missing the boundary
*/
public MultipartIterator(Request req) throws IOException {
Map<String, String> ct = req.getHeaders().getParams("Content-Type");
if (!ct.containsKey("multipart/form-data"))
throw new IllegalArgumentException("Content-Type is not multipart/form-data");
String boundary = ct.get("boundary"); // should be US-ASCII
if (boundary == null)
throw new IllegalArgumentException("Content-Type is missing boundary");
in = new MultipartInputStream(req.getBody(), getBytes(boundary));
}
public boolean hasNext() {
try {
return next || (next = in.nextPart());
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
public Part next() {
if (!hasNext())
throw new NoSuchElementException();
next = false;
Part p = new Part();
try {
p.headers = readHeaders(in);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
Map<String, String> cd = p.headers.getParams("Content-Disposition");
p.name = cd.get("name");
p.filename = cd.get("filename");
p.body = in;
return p;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* The {@code VirtualHost} class represents a virtual host in the server.
*/
public static class VirtualHost {
/**
* The {@code ContextInfo} class holds a single context's information.
*/
public class ContextInfo {
protected final String path;
protected final Map<String, ContextHandler> handlers =
new ConcurrentHashMap<String, ContextHandler>(2);
/**
* Constructs a ContextInfo with the given context path.
*
* @param path the context path (without trailing slash)
*/
public ContextInfo(String path) {
this.path = path;
}
/**
* Returns the context path.
*
* @return the context path, or null if there is none
*/
public String getPath() {
return path;
}
/**
* Returns the map of supported HTTP methods and their corresponding handlers.
*
* @return the map of supported HTTP methods and their corresponding handlers
*/
public Map<String, ContextHandler> getHandlers() {
return handlers;
}
/**
* Adds (or replaces) a context handler for the given HTTP methods.
*
* @param handler the context handler
* @param methods the HTTP methods supported by the handler (default is "GET")
*/
public void addHandler(ContextHandler handler, String... methods) {
if (methods.length == 0)
methods = new String[] { "GET" };
for (String method : methods) {
handlers.put(method, handler);
VirtualHost.this.methods.add(method); // it's now supported by server
}
}
}
protected final String name;
protected final Set<String> aliases = new CopyOnWriteArraySet<String>();
protected volatile String directoryIndex = "index.html";
protected volatile boolean allowGeneratedIndex;
protected final Set<String> methods = new CopyOnWriteArraySet<String>();
protected final ContextInfo emptyContext = new ContextInfo(null);
protected final ConcurrentMap<String, ContextInfo> contexts =
new ConcurrentHashMap<String, ContextInfo>();
/**
* Constructs a VirtualHost with the given name.
*
* @param name the host's name, or null if it is the default host
*/
public VirtualHost(String name) {
this.name = name;
contexts.put("*", new ContextInfo(null)); // for "OPTIONS *"
}
/**
* Returns this host's name.
*
* @return this host's name, or null if it is the default host
*/
public String getName() {
return name;
}
/**
* Adds an alias for this host.
*
* @param alias the alias
*/
public void addAlias(String alias) {
aliases.add(alias);
}
/**
* Returns this host's aliases.
*
* @return the (unmodifiable) set of aliases (which may be empty)
*/
public Set<String> getAliases() {
return Collections.unmodifiableSet(aliases);
}
/**
* Sets the directory index file. For every request whose URI ends with
* a '/' (i.e. a directory), the index file is appended to the path,
* and the resulting resource is served if it exists. If it does not
* exist, an auto-generated index for the requested directory may be
* served, depending on whether {@link #setAllowGeneratedIndex
* a generated index is allowed}, otherwise an error is returned.
* The default directory index file is "index.html".
*
* @param directoryIndex the directory index file, or null if no
* index file should be used
*/
public void setDirectoryIndex(String directoryIndex) {
this.directoryIndex = directoryIndex;
}
/**
* Gets this host's directory index file.
*
* @return the directory index file, or null
*/
public String getDirectoryIndex() {
return directoryIndex;
}
/**
* Sets whether auto-generated indices are allowed. If false, and a
* directory resource is requested, an error will be returned instead.
*
* @param allowed specifies whether generated indices are allowed
*/
public void setAllowGeneratedIndex(boolean allowed) {
this.allowGeneratedIndex = allowed;
}
/**
* Returns whether auto-generated indices are allowed.
*
* @return whether auto-generated indices are allowed
*/
public boolean isAllowGeneratedIndex() {
return allowGeneratedIndex;
}
/**
* Returns all HTTP methods explicitly supported by at least one context
* (this may or may not include the methods with required or built-in support).
*
* @return all HTTP methods explicitly supported by at least one context
*/
public Set<String> getMethods() {
return methods;
}
/**
* Returns the context handler for the given path.
* <p>
* If a context is not found for the given path, the search is repeated for
* its parent path, and so on until a base context is found. If neither the
* given path nor any of its parents has a context, an empty context is returned.
*
* @param path the context's path
* @return the context info for the given path, or an empty context if none exists
*/
public ContextInfo getContext(String path) {
// all context paths are without trailing slash
for (path = trimRight(path, '/'); path != null; path = getParentPath(path)) {
ContextInfo info = contexts.get(path);
if (info != null)
return info;
}
return emptyContext;
}
/**
* Adds a context and its corresponding context handler to this server.
* Paths are normalized by removing trailing slashes (except the root).
*
* @param path the context's path (must start with '/')
* @param handler the context handler for the given path
* @param methods the HTTP methods supported by the context handler (default is "GET")
* @throws IllegalArgumentException if path is malformed
*/
public void addContext(String path, ContextHandler handler, String... methods) {
if (path == null || !path.startsWith("/") && !path.equals("*"))
throw new IllegalArgumentException("invalid path: " + path);
path = trimRight(path, '/'); // remove trailing slash
ContextInfo info = new ContextInfo(path);
ContextInfo existing = contexts.putIfAbsent(path, info);
info = existing != null ? existing : info;
info.addHandler(handler, methods);
}
/**
* Adds contexts for all methods of the given object that
* are annotated with the {@link Context} annotation.
*
* @param o the object whose annotated methods are added
* @throws IllegalArgumentException if a Context-annotated
* method has an {@link Context invalid signature}
*/
public void addContexts(Object o) throws IllegalArgumentException {
for (Class<?> c = o.getClass(); c != null; c = c.getSuperclass()) {
// add to contexts those with @Context annotation
for (Method m : c.getDeclaredMethods()) {
Context context = m.getAnnotation(Context.class);
if (context != null) {
m.setAccessible(true); // allow access to private method
ContextHandler handler = new MethodContextHandler(m, o);
addContext(context.value(), handler, context.methods());
}
}
}
}
}
/**
* The {@code Context} annotation decorates methods which are mapped