1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.http.multipart;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.handler.codec.http.HttpConstants;
20 import io.netty.handler.codec.http.HttpContent;
21 import io.netty.handler.codec.http.HttpHeaderNames;
22 import io.netty.handler.codec.http.HttpHeaderValues;
23 import io.netty.handler.codec.http.HttpRequest;
24 import io.netty.handler.codec.http.LastHttpContent;
25 import io.netty.handler.codec.http.QueryStringDecoder;
26 import io.netty.handler.codec.http.multipart.HttpPostBodyUtil.SeekAheadOptimize;
27 import io.netty.handler.codec.http.multipart.HttpPostBodyUtil.TransferEncodingMechanism;
28 import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.EndOfDataDecoderException;
29 import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException;
30 import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.MultiPartStatus;
31 import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.NotEnoughDataDecoderException;
32 import io.netty.util.CharsetUtil;
33 import io.netty.util.internal.EmptyArrays;
34 import io.netty.util.internal.InternalThreadLocalMap;
35 import io.netty.util.internal.PlatformDependent;
36 import io.netty.util.internal.StringUtil;
37
38 import java.io.IOException;
39 import java.nio.charset.Charset;
40 import java.nio.charset.IllegalCharsetNameException;
41 import java.nio.charset.UnsupportedCharsetException;
42 import java.util.ArrayList;
43 import java.util.List;
44 import java.util.Locale;
45 import java.util.Map;
46 import java.util.TreeMap;
47
48 import static io.netty.util.internal.ObjectUtil.checkNotNull;
49 import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
50
51
52
53
54
55
56
57 public class HttpPostMultipartRequestDecoder implements InterfaceHttpPostRequestDecoder {
58
59
60
61
62 private final HttpDataFactory factory;
63
64
65
66
67 private final HttpRequest request;
68
69
70
71
72 private final int maxFields;
73
74
75
76
77 private final int maxBufferedBytes;
78
79
80
81
82 private Charset charset;
83
84
85
86
87 private boolean isLastChunk;
88
89
90
91
92 private final List<InterfaceHttpData> bodyListHttpData = new ArrayList<InterfaceHttpData>();
93
94
95
96
97 private final Map<String, List<InterfaceHttpData>> bodyMapHttpData = new TreeMap<String, List<InterfaceHttpData>>(
98 CaseIgnoringComparator.INSTANCE);
99
100
101
102
103 private ByteBuf undecodedChunk;
104
105
106
107
108 private int bodyListHttpDataRank;
109
110
111
112
113 private final String multipartDataBoundary;
114
115
116
117
118
119 private String multipartMixedBoundary;
120
121
122
123
124 private MultiPartStatus currentStatus = MultiPartStatus.NOTSTARTED;
125
126
127
128
129 private Map<CharSequence, Attribute> currentFieldAttributes;
130
131
132
133
134 private FileUpload currentFileUpload;
135
136
137
138
139 private Attribute currentAttribute;
140
141 private boolean destroyed;
142
143 private int discardThreshold = HttpPostRequestDecoder.DEFAULT_DISCARD_THRESHOLD;
144
145
146
147
148
149
150
151
152
153
154
155 public HttpPostMultipartRequestDecoder(HttpRequest request) {
156 this(new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE), request, HttpConstants.DEFAULT_CHARSET);
157 }
158
159
160
161
162
163
164
165
166
167
168
169
170
171 public HttpPostMultipartRequestDecoder(HttpDataFactory factory, HttpRequest request) {
172 this(factory, request, HttpConstants.DEFAULT_CHARSET);
173 }
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189 public HttpPostMultipartRequestDecoder(HttpDataFactory factory, HttpRequest request, Charset charset) {
190 this(factory, request, charset, HttpPostRequestDecoder.DEFAULT_MAX_FIELDS,
191 HttpPostRequestDecoder.DEFAULT_MAX_BUFFERED_BYTES);
192 }
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212 public HttpPostMultipartRequestDecoder(HttpDataFactory factory, HttpRequest request, Charset charset,
213 int maxFields, int maxBufferedBytes) {
214 this.request = checkNotNull(request, "request");
215 this.charset = checkNotNull(charset, "charset");
216 this.factory = checkNotNull(factory, "factory");
217 this.maxFields = maxFields;
218 this.maxBufferedBytes = maxBufferedBytes;
219
220
221 String contentTypeValue = this.request.headers().get(HttpHeaderNames.CONTENT_TYPE);
222 if (contentTypeValue == null || contentTypeValue.isEmpty()) {
223
224 throw new ErrorDataDecoderException(
225 "No '" + HttpHeaderNames.CONTENT_TYPE + "' header present, or value is empty.");
226 }
227
228 String[] dataBoundary = HttpPostRequestDecoder.getMultipartDataBoundary(contentTypeValue);
229 if (dataBoundary != null) {
230 multipartDataBoundary = dataBoundary[0];
231 if (dataBoundary.length > 1 && dataBoundary[1] != null) {
232 try {
233 this.charset = Charset.forName(dataBoundary[1]);
234 } catch (IllegalCharsetNameException e) {
235 throw new ErrorDataDecoderException(e);
236 }
237 }
238 } else {
239 multipartDataBoundary = null;
240 }
241 currentStatus = MultiPartStatus.HEADERDELIMITER;
242
243 try {
244 if (request instanceof HttpContent) {
245
246
247 offer((HttpContent) request);
248 } else {
249 parseBody();
250 }
251 } catch (Throwable e) {
252 destroy();
253 PlatformDependent.throwException(e);
254 }
255 }
256
257 private void checkDestroyed() {
258 if (destroyed) {
259 throw new IllegalStateException(HttpPostMultipartRequestDecoder.class.getSimpleName()
260 + " was destroyed already");
261 }
262 }
263
264
265
266
267
268
269 @Override
270 public boolean isMultipart() {
271 checkDestroyed();
272 return true;
273 }
274
275
276
277
278
279
280 @Override
281 public void setDiscardThreshold(int discardThreshold) {
282 this.discardThreshold = checkPositiveOrZero(discardThreshold, "discardThreshold");
283 }
284
285
286
287
288 @Override
289 public int getDiscardThreshold() {
290 return discardThreshold;
291 }
292
293
294
295
296
297
298
299
300
301
302
303 @Override
304 public List<InterfaceHttpData> getBodyHttpDatas() {
305 checkDestroyed();
306
307 if (!isLastChunk) {
308 throw new NotEnoughDataDecoderException();
309 }
310 return bodyListHttpData;
311 }
312
313
314
315
316
317
318
319
320
321
322
323
324 @Override
325 public List<InterfaceHttpData> getBodyHttpDatas(String name) {
326 checkDestroyed();
327
328 if (!isLastChunk) {
329 throw new NotEnoughDataDecoderException();
330 }
331 return bodyMapHttpData.get(name);
332 }
333
334
335
336
337
338
339
340
341
342
343
344
345
346 @Override
347 public InterfaceHttpData getBodyHttpData(String name) {
348 checkDestroyed();
349
350 if (!isLastChunk) {
351 throw new NotEnoughDataDecoderException();
352 }
353 List<InterfaceHttpData> list = bodyMapHttpData.get(name);
354 if (list != null) {
355 return list.get(0);
356 }
357 return null;
358 }
359
360
361
362
363
364
365
366
367
368
369 @Override
370 public HttpPostMultipartRequestDecoder offer(HttpContent content) {
371 checkDestroyed();
372
373 if (content instanceof LastHttpContent) {
374 isLastChunk = true;
375 }
376
377 ByteBuf buf = content.content();
378 if (undecodedChunk == null) {
379 undecodedChunk =
380
381
382
383
384 buf.alloc().buffer(buf.readableBytes()).writeBytes(buf);
385 } else {
386 undecodedChunk.writeBytes(buf);
387 }
388 parseBody();
389 if (maxBufferedBytes > 0 && undecodedChunk != null && undecodedChunk.readableBytes() > maxBufferedBytes) {
390 throw new HttpPostRequestDecoder.TooLongFormFieldException();
391 }
392 if (undecodedChunk != null && undecodedChunk.writerIndex() > discardThreshold) {
393 if (undecodedChunk.refCnt() == 1) {
394
395 undecodedChunk.discardReadBytes();
396 } else {
397
398
399 ByteBuf buffer = undecodedChunk.alloc().buffer(undecodedChunk.readableBytes());
400 buffer.writeBytes(undecodedChunk);
401 undecodedChunk.release();
402 undecodedChunk = buffer;
403 }
404 }
405 return this;
406 }
407
408
409
410
411
412
413
414
415
416
417
418 @Override
419 public boolean hasNext() {
420 checkDestroyed();
421
422 if (currentStatus == MultiPartStatus.EPILOGUE) {
423
424 if (bodyListHttpDataRank >= bodyListHttpData.size()) {
425 throw new EndOfDataDecoderException();
426 }
427 }
428 return !bodyListHttpData.isEmpty() && bodyListHttpDataRank < bodyListHttpData.size();
429 }
430
431
432
433
434
435
436
437
438
439
440
441
442
443 @Override
444 public InterfaceHttpData next() {
445 checkDestroyed();
446
447 if (hasNext()) {
448 return bodyListHttpData.get(bodyListHttpDataRank++);
449 }
450 return null;
451 }
452
453 @Override
454 public InterfaceHttpData currentPartialHttpData() {
455 if (currentFileUpload != null) {
456 return currentFileUpload;
457 } else {
458 return currentAttribute;
459 }
460 }
461
462
463
464
465
466
467
468
469 private void parseBody() {
470 if (currentStatus == MultiPartStatus.PREEPILOGUE || currentStatus == MultiPartStatus.EPILOGUE) {
471 if (isLastChunk) {
472 currentStatus = MultiPartStatus.EPILOGUE;
473 }
474 return;
475 }
476 parseBodyMultipart();
477 }
478
479
480
481
482 protected void addHttpData(InterfaceHttpData data) {
483 if (data == null) {
484 return;
485 }
486 if (maxFields > 0 && bodyListHttpData.size() >= maxFields) {
487 throw new HttpPostRequestDecoder.TooManyFormFieldsException();
488 }
489 List<InterfaceHttpData> datas = bodyMapHttpData.get(data.getName());
490 if (datas == null) {
491 datas = new ArrayList<InterfaceHttpData>(1);
492 bodyMapHttpData.put(data.getName(), datas);
493 }
494 datas.add(data);
495 bodyListHttpData.add(data);
496 }
497
498
499
500
501
502
503
504
505 private void parseBodyMultipart() {
506 if (undecodedChunk == null || undecodedChunk.readableBytes() == 0) {
507
508 return;
509 }
510 InterfaceHttpData data = decodeMultipart(currentStatus);
511 while (data != null) {
512 addHttpData(data);
513 if (currentStatus == MultiPartStatus.PREEPILOGUE || currentStatus == MultiPartStatus.EPILOGUE) {
514 break;
515 }
516 data = decodeMultipart(currentStatus);
517 }
518 }
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536 private InterfaceHttpData decodeMultipart(MultiPartStatus state) {
537 switch (state) {
538 case NOTSTARTED:
539 throw new ErrorDataDecoderException("Should not be called with the current getStatus");
540 case PREAMBLE:
541
542 throw new ErrorDataDecoderException("Should not be called with the current getStatus");
543 case HEADERDELIMITER: {
544
545 return findMultipartDelimiter(multipartDataBoundary, MultiPartStatus.DISPOSITION,
546 MultiPartStatus.PREEPILOGUE);
547 }
548 case DISPOSITION: {
549
550
551
552
553
554
555
556
557
558 return findMultipartDisposition();
559 }
560 case FIELD: {
561
562 Charset localCharset = null;
563 Attribute charsetAttribute = currentFieldAttributes.get(HttpHeaderValues.CHARSET);
564 if (charsetAttribute != null) {
565 try {
566 localCharset = Charset.forName(charsetAttribute.getValue());
567 } catch (IOException e) {
568 throw new ErrorDataDecoderException(e);
569 } catch (UnsupportedCharsetException e) {
570 throw new ErrorDataDecoderException(e);
571 }
572 }
573 Attribute nameAttribute = currentFieldAttributes.get(HttpHeaderValues.NAME);
574 if (currentAttribute == null) {
575 Attribute lengthAttribute = currentFieldAttributes
576 .get(HttpHeaderNames.CONTENT_LENGTH);
577 long size;
578 try {
579 size = lengthAttribute != null? Long.parseLong(lengthAttribute
580 .getValue()) : 0L;
581 } catch (IOException e) {
582 throw new ErrorDataDecoderException(e);
583 } catch (NumberFormatException ignored) {
584 size = 0;
585 }
586 try {
587 if (size > 0) {
588 currentAttribute = factory.createAttribute(request,
589 cleanString(nameAttribute.getValue()), size);
590 } else {
591 currentAttribute = factory.createAttribute(request,
592 cleanString(nameAttribute.getValue()));
593 }
594 } catch (NullPointerException e) {
595 throw new ErrorDataDecoderException(e);
596 } catch (IllegalArgumentException e) {
597 throw new ErrorDataDecoderException(e);
598 } catch (IOException e) {
599 throw new ErrorDataDecoderException(e);
600 }
601 if (localCharset != null) {
602 currentAttribute.setCharset(localCharset);
603 }
604 }
605
606 if (!loadDataMultipartOptimized(undecodedChunk, multipartDataBoundary, currentAttribute)) {
607
608 return null;
609 }
610 Attribute finalAttribute = currentAttribute;
611 currentAttribute = null;
612 currentFieldAttributes = null;
613
614 currentStatus = MultiPartStatus.HEADERDELIMITER;
615 return finalAttribute;
616 }
617 case FILEUPLOAD: {
618
619 return getFileUpload(multipartDataBoundary);
620 }
621 case MIXEDDELIMITER: {
622
623
624 return findMultipartDelimiter(multipartMixedBoundary, MultiPartStatus.MIXEDDISPOSITION,
625 MultiPartStatus.HEADERDELIMITER);
626 }
627 case MIXEDDISPOSITION: {
628 return findMultipartDisposition();
629 }
630 case MIXEDFILEUPLOAD: {
631
632 return getFileUpload(multipartMixedBoundary);
633 }
634 case PREEPILOGUE:
635 return null;
636 case EPILOGUE:
637 return null;
638 default:
639 throw new ErrorDataDecoderException("Shouldn't reach here.");
640 }
641 }
642
643
644
645
646
647
648 private static void skipControlCharacters(ByteBuf undecodedChunk) {
649 if (!undecodedChunk.hasArray()) {
650 try {
651 skipControlCharactersStandard(undecodedChunk);
652 } catch (IndexOutOfBoundsException e1) {
653 throw new NotEnoughDataDecoderException(e1);
654 }
655 return;
656 }
657 SeekAheadOptimize sao = new SeekAheadOptimize(undecodedChunk);
658 while (sao.pos < sao.limit) {
659 char c = (char) (sao.bytes[sao.pos++] & 0xFF);
660 if (!Character.isISOControl(c) && !Character.isWhitespace(c)) {
661 sao.setReadPosition(1);
662 return;
663 }
664 }
665 throw new NotEnoughDataDecoderException("Access out of bounds");
666 }
667
668 private static void skipControlCharactersStandard(ByteBuf undecodedChunk) {
669 for (;;) {
670 char c = (char) undecodedChunk.readUnsignedByte();
671 if (!Character.isISOControl(c) && !Character.isWhitespace(c)) {
672 undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 1);
673 break;
674 }
675 }
676 }
677
678
679
680
681
682
683
684
685
686
687
688
689
690 private InterfaceHttpData findMultipartDelimiter(String delimiter, MultiPartStatus dispositionStatus,
691 MultiPartStatus closeDelimiterStatus) {
692
693 int readerIndex = undecodedChunk.readerIndex();
694 try {
695 skipControlCharacters(undecodedChunk);
696 } catch (NotEnoughDataDecoderException ignored) {
697 undecodedChunk.readerIndex(readerIndex);
698 return null;
699 }
700 skipOneLine();
701 String newline;
702 try {
703 newline = readDelimiterOptimized(undecodedChunk, delimiter, charset);
704 } catch (NotEnoughDataDecoderException ignored) {
705 undecodedChunk.readerIndex(readerIndex);
706 return null;
707 }
708 if (newline.equals(delimiter)) {
709 currentStatus = dispositionStatus;
710 return decodeMultipart(dispositionStatus);
711 }
712 if (newline.equals(delimiter + "--")) {
713
714 currentStatus = closeDelimiterStatus;
715 if (currentStatus == MultiPartStatus.HEADERDELIMITER) {
716
717
718 currentFieldAttributes = null;
719 return decodeMultipart(MultiPartStatus.HEADERDELIMITER);
720 }
721 return null;
722 }
723 undecodedChunk.readerIndex(readerIndex);
724 throw new ErrorDataDecoderException("No Multipart delimiter found");
725 }
726
727
728
729
730
731
732
733 private InterfaceHttpData findMultipartDisposition() {
734 int readerIndex = undecodedChunk.readerIndex();
735 if (currentStatus == MultiPartStatus.DISPOSITION) {
736 currentFieldAttributes = new TreeMap<CharSequence, Attribute>(CaseIgnoringComparator.INSTANCE);
737 }
738
739 while (!skipOneLine()) {
740 String newline;
741 try {
742 skipControlCharacters(undecodedChunk);
743 newline = readLineOptimized(undecodedChunk, charset);
744 } catch (NotEnoughDataDecoderException ignored) {
745 undecodedChunk.readerIndex(readerIndex);
746 return null;
747 }
748 String[] contents = splitMultipartHeader(newline);
749 if (HttpHeaderNames.CONTENT_DISPOSITION.contentEqualsIgnoreCase(contents[0])) {
750 boolean checkSecondArg;
751 if (currentStatus == MultiPartStatus.DISPOSITION) {
752 checkSecondArg = HttpHeaderValues.FORM_DATA.contentEqualsIgnoreCase(contents[1]);
753 } else {
754 checkSecondArg = HttpHeaderValues.ATTACHMENT.contentEqualsIgnoreCase(contents[1])
755 || HttpHeaderValues.FILE.contentEqualsIgnoreCase(contents[1]);
756 }
757 if (checkSecondArg) {
758
759 for (int i = 2; i < contents.length; i++) {
760 String[] values = contents[i].split("=", 2);
761 Attribute attribute;
762 try {
763 attribute = getContentDispositionAttribute(values);
764 } catch (NullPointerException e) {
765 throw new ErrorDataDecoderException(e);
766 } catch (IllegalArgumentException e) {
767 throw new ErrorDataDecoderException(e);
768 } catch (ArrayIndexOutOfBoundsException e) {
769 throw new ErrorDataDecoderException(e);
770 }
771 currentFieldAttributes.put(attribute.getName(), attribute);
772 }
773 }
774 } else if (HttpHeaderNames.CONTENT_TRANSFER_ENCODING.contentEqualsIgnoreCase(contents[0])) {
775 Attribute attribute;
776 try {
777 attribute = factory.createAttribute(request, HttpHeaderNames.CONTENT_TRANSFER_ENCODING.toString(),
778 cleanString(contents[1]));
779 } catch (NullPointerException e) {
780 throw new ErrorDataDecoderException(e);
781 } catch (IllegalArgumentException e) {
782 throw new ErrorDataDecoderException(e);
783 }
784
785 currentFieldAttributes.put(HttpHeaderNames.CONTENT_TRANSFER_ENCODING, attribute);
786 } else if (HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(contents[0])) {
787 Attribute attribute;
788 try {
789 attribute = factory.createAttribute(request, HttpHeaderNames.CONTENT_LENGTH.toString(),
790 cleanString(contents[1]));
791 } catch (NullPointerException e) {
792 throw new ErrorDataDecoderException(e);
793 } catch (IllegalArgumentException e) {
794 throw new ErrorDataDecoderException(e);
795 }
796
797 currentFieldAttributes.put(HttpHeaderNames.CONTENT_LENGTH, attribute);
798 } else if (HttpHeaderNames.CONTENT_TYPE.contentEqualsIgnoreCase(contents[0])) {
799
800 if (HttpHeaderValues.MULTIPART_MIXED.contentEqualsIgnoreCase(contents[1])) {
801 if (currentStatus == MultiPartStatus.DISPOSITION) {
802 String values = StringUtil.substringAfter(contents[2], '=');
803 multipartMixedBoundary = "--" + values;
804 currentStatus = MultiPartStatus.MIXEDDELIMITER;
805 return decodeMultipart(MultiPartStatus.MIXEDDELIMITER);
806 } else {
807 throw new ErrorDataDecoderException("Mixed Multipart found in a previous Mixed Multipart");
808 }
809 } else {
810 for (int i = 1; i < contents.length; i++) {
811 final String charsetHeader = HttpHeaderValues.CHARSET.toString();
812 if (contents[i].regionMatches(true, 0, charsetHeader, 0, charsetHeader.length())) {
813 String values = StringUtil.substringAfter(contents[i], '=');
814 Attribute attribute;
815 try {
816 attribute = factory.createAttribute(request, charsetHeader, cleanString(values));
817 } catch (NullPointerException e) {
818 throw new ErrorDataDecoderException(e);
819 } catch (IllegalArgumentException e) {
820 throw new ErrorDataDecoderException(e);
821 }
822 currentFieldAttributes.put(HttpHeaderValues.CHARSET, attribute);
823 } else if (contents[i].contains("=")) {
824 String name = StringUtil.substringBefore(contents[i], '=');
825 String values = StringUtil.substringAfter(contents[i], '=');
826 Attribute attribute;
827 try {
828 attribute = factory.createAttribute(request, cleanString(name), values);
829 } catch (NullPointerException e) {
830 throw new ErrorDataDecoderException(e);
831 } catch (IllegalArgumentException e) {
832 throw new ErrorDataDecoderException(e);
833 }
834 currentFieldAttributes.put(name, attribute);
835 } else {
836 Attribute attribute;
837 try {
838 attribute = factory.createAttribute(request,
839 cleanString(contents[0]), contents[i]);
840 } catch (NullPointerException e) {
841 throw new ErrorDataDecoderException(e);
842 } catch (IllegalArgumentException e) {
843 throw new ErrorDataDecoderException(e);
844 }
845 currentFieldAttributes.put(attribute.getName(), attribute);
846 }
847 }
848 }
849 }
850 }
851
852 Attribute filenameAttribute = currentFieldAttributes.get(HttpHeaderValues.FILENAME);
853 if (currentStatus == MultiPartStatus.DISPOSITION) {
854 if (filenameAttribute != null) {
855
856 currentStatus = MultiPartStatus.FILEUPLOAD;
857
858 return decodeMultipart(MultiPartStatus.FILEUPLOAD);
859 } else {
860
861 currentStatus = MultiPartStatus.FIELD;
862
863 return decodeMultipart(MultiPartStatus.FIELD);
864 }
865 } else {
866 if (filenameAttribute != null) {
867
868 currentStatus = MultiPartStatus.MIXEDFILEUPLOAD;
869
870 return decodeMultipart(MultiPartStatus.MIXEDFILEUPLOAD);
871 } else {
872
873 throw new ErrorDataDecoderException("Filename not found");
874 }
875 }
876 }
877
878 private static final String FILENAME_ENCODED = HttpHeaderValues.FILENAME.toString() + '*';
879
880 private Attribute getContentDispositionAttribute(String... values) {
881 String name = cleanString(values[0]);
882 String value = values[1];
883
884
885 if (HttpHeaderValues.FILENAME.contentEquals(name)) {
886
887 int last = value.length() - 1;
888 if (last > 0 &&
889 value.charAt(0) == HttpConstants.DOUBLE_QUOTE &&
890 value.charAt(last) == HttpConstants.DOUBLE_QUOTE) {
891 value = value.substring(1, last);
892 }
893 } else if (FILENAME_ENCODED.equals(name)) {
894 try {
895 name = HttpHeaderValues.FILENAME.toString();
896 String[] split = cleanString(value).split("'", 3);
897 value = QueryStringDecoder.decodeComponent(split[2], Charset.forName(split[0]));
898 } catch (ArrayIndexOutOfBoundsException e) {
899 throw new ErrorDataDecoderException(e);
900 } catch (UnsupportedCharsetException e) {
901 throw new ErrorDataDecoderException(e);
902 }
903 } else {
904
905 value = cleanString(value);
906 }
907 return factory.createAttribute(request, name, value);
908 }
909
910
911
912
913
914
915
916
917
918 protected InterfaceHttpData getFileUpload(String delimiter) {
919
920
921 Attribute encoding = currentFieldAttributes.get(HttpHeaderNames.CONTENT_TRANSFER_ENCODING);
922 Charset localCharset = charset;
923
924 TransferEncodingMechanism mechanism = TransferEncodingMechanism.BIT7;
925 if (encoding != null) {
926 String code;
927 try {
928
929
930
931
932 code = encoding.getValue().toLowerCase(Locale.US);
933 } catch (IOException e) {
934 throw new ErrorDataDecoderException(e);
935 }
936 if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT7.value())) {
937 localCharset = CharsetUtil.US_ASCII;
938 } else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT8.value())) {
939 localCharset = CharsetUtil.ISO_8859_1;
940 mechanism = TransferEncodingMechanism.BIT8;
941 } else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value())) {
942
943 mechanism = TransferEncodingMechanism.BINARY;
944 } else {
945 throw new ErrorDataDecoderException("TransferEncoding Unknown: " + code);
946 }
947 }
948 Attribute charsetAttribute = currentFieldAttributes.get(HttpHeaderValues.CHARSET);
949 if (charsetAttribute != null) {
950 try {
951 localCharset = Charset.forName(charsetAttribute.getValue());
952 } catch (IOException e) {
953 throw new ErrorDataDecoderException(e);
954 } catch (UnsupportedCharsetException e) {
955 throw new ErrorDataDecoderException(e);
956 }
957 }
958 if (currentFileUpload == null) {
959 Attribute filenameAttribute = currentFieldAttributes.get(HttpHeaderValues.FILENAME);
960 Attribute nameAttribute = currentFieldAttributes.get(HttpHeaderValues.NAME);
961 Attribute contentTypeAttribute = currentFieldAttributes.get(HttpHeaderNames.CONTENT_TYPE);
962 Attribute lengthAttribute = currentFieldAttributes.get(HttpHeaderNames.CONTENT_LENGTH);
963 long size;
964 try {
965 size = lengthAttribute != null ? Long.parseLong(lengthAttribute.getValue()) : 0L;
966 } catch (IOException e) {
967 throw new ErrorDataDecoderException(e);
968 } catch (NumberFormatException ignored) {
969 size = 0;
970 }
971 try {
972 String contentType;
973 if (contentTypeAttribute != null) {
974 contentType = contentTypeAttribute.getValue();
975 } else {
976 contentType = HttpPostBodyUtil.DEFAULT_BINARY_CONTENT_TYPE;
977 }
978 currentFileUpload = factory.createFileUpload(request,
979 cleanString(nameAttribute.getValue()), cleanString(filenameAttribute.getValue()),
980 cleanMimeContentType(contentType), mechanism.value(), localCharset,
981 size);
982 } catch (NullPointerException e) {
983 throw new ErrorDataDecoderException(e);
984 } catch (IllegalArgumentException e) {
985 throw new ErrorDataDecoderException(e);
986 } catch (IOException e) {
987 throw new ErrorDataDecoderException(e);
988 }
989 }
990
991 if (!loadDataMultipartOptimized(undecodedChunk, delimiter, currentFileUpload)) {
992
993 return null;
994 }
995 if (currentFileUpload.isCompleted()) {
996
997 if (currentStatus == MultiPartStatus.FILEUPLOAD) {
998 currentStatus = MultiPartStatus.HEADERDELIMITER;
999 currentFieldAttributes = null;
1000 } else {
1001 currentStatus = MultiPartStatus.MIXEDDELIMITER;
1002 cleanMixedAttributes();
1003 }
1004 FileUpload fileUpload = currentFileUpload;
1005 currentFileUpload = null;
1006 return fileUpload;
1007 }
1008
1009
1010
1011 return null;
1012 }
1013
1014
1015
1016
1017
1018 @Override
1019 public void destroy() {
1020
1021 cleanFiles();
1022
1023 for (InterfaceHttpData httpData : bodyListHttpData) {
1024
1025 if (httpData.refCnt() > 0) {
1026 httpData.release();
1027 }
1028 }
1029
1030 destroyed = true;
1031
1032 if (undecodedChunk != null && undecodedChunk.refCnt() > 0) {
1033 undecodedChunk.release();
1034 undecodedChunk = null;
1035 }
1036 }
1037
1038
1039
1040
1041 @Override
1042 public void cleanFiles() {
1043 checkDestroyed();
1044
1045 factory.cleanRequestHttpData(request);
1046 }
1047
1048
1049
1050
1051 @Override
1052 public void removeHttpDataFromClean(InterfaceHttpData data) {
1053 checkDestroyed();
1054
1055 factory.removeHttpDataFromClean(request, data);
1056 }
1057
1058
1059
1060
1061
1062 private void cleanMixedAttributes() {
1063 currentFieldAttributes.remove(HttpHeaderValues.CHARSET);
1064 currentFieldAttributes.remove(HttpHeaderNames.CONTENT_LENGTH);
1065 currentFieldAttributes.remove(HttpHeaderNames.CONTENT_TRANSFER_ENCODING);
1066 currentFieldAttributes.remove(HttpHeaderNames.CONTENT_TYPE);
1067 currentFieldAttributes.remove(HttpHeaderValues.FILENAME);
1068 }
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078 private static String readLineOptimized(ByteBuf undecodedChunk, Charset charset) {
1079 int readerIndex = undecodedChunk.readerIndex();
1080 ByteBuf line = null;
1081 try {
1082 if (undecodedChunk.isReadable()) {
1083 int posLfOrCrLf = HttpPostBodyUtil.findLineBreak(undecodedChunk, undecodedChunk.readerIndex());
1084 if (posLfOrCrLf <= 0) {
1085 throw new NotEnoughDataDecoderException();
1086 }
1087 try {
1088 line = undecodedChunk.alloc().heapBuffer(posLfOrCrLf);
1089 line.writeBytes(undecodedChunk, posLfOrCrLf);
1090
1091 byte nextByte = undecodedChunk.readByte();
1092 if (nextByte == HttpConstants.CR) {
1093
1094 undecodedChunk.readByte();
1095 }
1096 return line.toString(charset);
1097 } finally {
1098 line.release();
1099 }
1100 }
1101 } catch (IndexOutOfBoundsException e) {
1102 undecodedChunk.readerIndex(readerIndex);
1103 throw new NotEnoughDataDecoderException(e);
1104 }
1105 undecodedChunk.readerIndex(readerIndex);
1106 throw new NotEnoughDataDecoderException();
1107 }
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124 private static String readDelimiterOptimized(ByteBuf undecodedChunk, String delimiter, Charset charset) {
1125 final int readerIndex = undecodedChunk.readerIndex();
1126 final byte[] bdelimiter = delimiter.getBytes(charset);
1127 final int delimiterLength = bdelimiter.length;
1128 try {
1129 int delimiterPos = HttpPostBodyUtil.findDelimiter(undecodedChunk, readerIndex, bdelimiter, false);
1130 if (delimiterPos < 0) {
1131
1132 undecodedChunk.readerIndex(readerIndex);
1133 throw new NotEnoughDataDecoderException();
1134 }
1135 StringBuilder sb = new StringBuilder(delimiter);
1136 undecodedChunk.readerIndex(readerIndex + delimiterPos + delimiterLength);
1137
1138 if (undecodedChunk.isReadable()) {
1139 byte nextByte = undecodedChunk.readByte();
1140
1141 if (nextByte == HttpConstants.CR) {
1142 nextByte = undecodedChunk.readByte();
1143 if (nextByte == HttpConstants.LF) {
1144 return sb.toString();
1145 } else {
1146
1147
1148 undecodedChunk.readerIndex(readerIndex);
1149 throw new NotEnoughDataDecoderException();
1150 }
1151 } else if (nextByte == HttpConstants.LF) {
1152 return sb.toString();
1153 } else if (nextByte == '-') {
1154 sb.append('-');
1155
1156 nextByte = undecodedChunk.readByte();
1157 if (nextByte == '-') {
1158 sb.append('-');
1159
1160 if (undecodedChunk.isReadable()) {
1161 nextByte = undecodedChunk.readByte();
1162 if (nextByte == HttpConstants.CR) {
1163 nextByte = undecodedChunk.readByte();
1164 if (nextByte == HttpConstants.LF) {
1165 return sb.toString();
1166 } else {
1167
1168
1169 undecodedChunk.readerIndex(readerIndex);
1170 throw new NotEnoughDataDecoderException();
1171 }
1172 } else if (nextByte == HttpConstants.LF) {
1173 return sb.toString();
1174 } else {
1175
1176
1177
1178 undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 1);
1179 return sb.toString();
1180 }
1181 }
1182
1183
1184
1185
1186 return sb.toString();
1187 }
1188
1189
1190 }
1191 }
1192 } catch (IndexOutOfBoundsException e) {
1193 undecodedChunk.readerIndex(readerIndex);
1194 throw new NotEnoughDataDecoderException(e);
1195 }
1196 undecodedChunk.readerIndex(readerIndex);
1197 throw new NotEnoughDataDecoderException();
1198 }
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209 private static void rewriteCurrentBuffer(ByteBuf buffer, int lengthToSkip) {
1210 if (lengthToSkip == 0) {
1211 return;
1212 }
1213 final int readerIndex = buffer.readerIndex();
1214 final int readableBytes = buffer.readableBytes();
1215 if (readableBytes == lengthToSkip) {
1216 buffer.readerIndex(readerIndex);
1217 buffer.writerIndex(readerIndex);
1218 return;
1219 }
1220 buffer.setBytes(readerIndex, buffer, readerIndex + lengthToSkip, readableBytes - lengthToSkip);
1221 buffer.readerIndex(readerIndex);
1222 buffer.writerIndex(readerIndex + readableBytes - lengthToSkip);
1223 }
1224
1225
1226
1227
1228
1229
1230
1231 private static boolean loadDataMultipartOptimized(ByteBuf undecodedChunk, String delimiter, HttpData httpData) {
1232 if (!undecodedChunk.isReadable()) {
1233 return false;
1234 }
1235 final int startReaderIndex = undecodedChunk.readerIndex();
1236 final byte[] bdelimiter = delimiter.getBytes(httpData.getCharset());
1237 int posDelimiter = HttpPostBodyUtil.findDelimiter(undecodedChunk, startReaderIndex, bdelimiter, true);
1238 if (posDelimiter < 0) {
1239
1240
1241
1242
1243 int readableBytes = undecodedChunk.readableBytes();
1244 int lastPosition = readableBytes - bdelimiter.length - 1;
1245 if (lastPosition < 0) {
1246
1247 lastPosition = 0;
1248 }
1249 posDelimiter = HttpPostBodyUtil.findLastLineBreak(undecodedChunk, startReaderIndex + lastPosition);
1250
1251
1252 if (posDelimiter < 0 &&
1253 httpData.definedLength() == httpData.length() + readableBytes - 1 &&
1254 undecodedChunk.getByte(readableBytes + startReaderIndex - 1) == HttpConstants.CR) {
1255
1256 lastPosition = 0;
1257 posDelimiter = readableBytes - 1;
1258 }
1259 if (posDelimiter < 0) {
1260
1261 ByteBuf content = undecodedChunk.copy();
1262 try {
1263 httpData.addContent(content, false);
1264 } catch (IOException e) {
1265 throw new ErrorDataDecoderException(e);
1266 }
1267 undecodedChunk.readerIndex(startReaderIndex);
1268 undecodedChunk.writerIndex(startReaderIndex);
1269 return false;
1270 }
1271
1272 posDelimiter += lastPosition;
1273 if (posDelimiter == 0) {
1274
1275 return false;
1276 }
1277
1278 ByteBuf content = undecodedChunk.copy(startReaderIndex, posDelimiter);
1279 try {
1280 httpData.addContent(content, false);
1281 } catch (IOException e) {
1282 throw new ErrorDataDecoderException(e);
1283 }
1284 rewriteCurrentBuffer(undecodedChunk, posDelimiter);
1285 return false;
1286 }
1287
1288 ByteBuf content = undecodedChunk.copy(startReaderIndex, posDelimiter);
1289 try {
1290 httpData.addContent(content, true);
1291 } catch (IOException e) {
1292 throw new ErrorDataDecoderException(e);
1293 }
1294 rewriteCurrentBuffer(undecodedChunk, posDelimiter);
1295 return true;
1296 }
1297
1298
1299
1300
1301
1302
1303 private static String cleanString(String field) {
1304 int size = field.length();
1305 StringBuilder sb = new StringBuilder(size);
1306 for (int i = 0; i < size; i++) {
1307 char nextChar = field.charAt(i);
1308 switch (nextChar) {
1309 case HttpConstants.COLON:
1310 case HttpConstants.COMMA:
1311 case HttpConstants.EQUALS:
1312 case HttpConstants.SEMICOLON:
1313 case HttpConstants.HT:
1314 sb.append(HttpConstants.SP_CHAR);
1315 break;
1316 case HttpConstants.DOUBLE_QUOTE:
1317 case HttpConstants.BACKSLASH:
1318
1319 break;
1320 default:
1321 if (nextChar < HttpConstants.SP || nextChar == HttpConstants.DEL) {
1322 sb.append(HttpConstants.SP_CHAR);
1323 } else {
1324 sb.append(nextChar);
1325 }
1326 break;
1327 }
1328 }
1329 return sb.toString().trim();
1330 }
1331
1332
1333
1334
1335
1336
1337
1338 private static String cleanMimeContentType(String contentType) {
1339 if (!FileUploadUtil.isContentTypeForMultiPartValid(contentType)) {
1340
1341
1342 return HttpPostBodyUtil.DEFAULT_BINARY_CONTENT_TYPE;
1343 }
1344 return contentType;
1345 }
1346
1347
1348
1349
1350
1351
1352 private boolean skipOneLine() {
1353 if (!undecodedChunk.isReadable()) {
1354 return false;
1355 }
1356 byte nextByte = undecodedChunk.readByte();
1357 if (nextByte == HttpConstants.CR) {
1358 if (!undecodedChunk.isReadable()) {
1359 undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 1);
1360 return false;
1361 }
1362 nextByte = undecodedChunk.readByte();
1363 if (nextByte == HttpConstants.LF) {
1364 return true;
1365 }
1366 undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 2);
1367 return false;
1368 }
1369 if (nextByte == HttpConstants.LF) {
1370 return true;
1371 }
1372 undecodedChunk.readerIndex(undecodedChunk.readerIndex() - 1);
1373 return false;
1374 }
1375
1376
1377
1378
1379
1380
1381
1382 private static String[] splitMultipartHeader(String sb) {
1383 ArrayList<String> headers = new ArrayList<String>(1);
1384 int nameStart;
1385 int nameEnd;
1386 int colonEnd;
1387 int valueStart;
1388 int valueEnd;
1389 nameStart = HttpPostBodyUtil.findNonWhitespace(sb, 0);
1390 for (nameEnd = nameStart; nameEnd < sb.length(); nameEnd++) {
1391 char ch = sb.charAt(nameEnd);
1392 if (ch == ':' || Character.isWhitespace(ch)) {
1393 break;
1394 }
1395 }
1396 for (colonEnd = nameEnd; colonEnd < sb.length(); colonEnd++) {
1397 if (sb.charAt(colonEnd) == ':') {
1398 colonEnd++;
1399 break;
1400 }
1401 }
1402 valueStart = HttpPostBodyUtil.findNonWhitespace(sb, colonEnd);
1403 valueEnd = HttpPostBodyUtil.findEndOfString(sb);
1404 headers.add(sb.substring(nameStart, nameEnd));
1405 String svalue = (valueStart >= valueEnd) ? StringUtil.EMPTY_STRING : sb.substring(valueStart, valueEnd);
1406 String[] values;
1407 if (svalue.indexOf(';') >= 0) {
1408 values = splitMultipartHeaderValues(svalue);
1409 } else {
1410 values = svalue.split(",");
1411 }
1412 for (String value : values) {
1413 headers.add(value.trim());
1414 }
1415 String[] array = new String[headers.size()];
1416 for (int i = 0; i < headers.size(); i++) {
1417 array[i] = headers.get(i);
1418 }
1419 return array;
1420 }
1421
1422
1423
1424
1425
1426 private static String[] splitMultipartHeaderValues(String svalue) {
1427 List<String> values = InternalThreadLocalMap.get().arrayList(1);
1428 boolean inQuote = false;
1429 boolean escapeNext = false;
1430 int start = 0;
1431 for (int i = 0; i < svalue.length(); i++) {
1432 char c = svalue.charAt(i);
1433 if (inQuote) {
1434 if (escapeNext) {
1435 escapeNext = false;
1436 } else {
1437 if (c == '\\') {
1438 escapeNext = true;
1439 } else if (c == '"') {
1440 inQuote = false;
1441 }
1442 }
1443 } else {
1444 if (c == '"') {
1445 inQuote = true;
1446 } else if (c == ';') {
1447 values.add(svalue.substring(start, i));
1448 start = i + 1;
1449 }
1450 }
1451 }
1452 values.add(svalue.substring(start));
1453 return values.toArray(EmptyArrays.EMPTY_STRINGS);
1454 }
1455
1456
1457
1458
1459
1460
1461
1462
1463 int getCurrentAllocatedCapacity() {
1464 return undecodedChunk.capacity();
1465 }
1466 }