1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.http;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.Unpooled;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.channel.ChannelPipeline;
22 import io.netty.handler.codec.ByteToMessageDecoder;
23 import io.netty.handler.codec.DecoderResult;
24 import io.netty.handler.codec.PrematureChannelClosureException;
25 import io.netty.handler.codec.TooLongFrameException;
26 import io.netty.util.AsciiString;
27 import io.netty.util.ByteProcessor;
28 import io.netty.util.internal.StringUtil;
29 import io.netty.util.internal.SystemPropertyUtil;
30
31 import java.util.List;
32 import java.util.concurrent.atomic.AtomicBoolean;
33
34 import static io.netty.util.internal.ObjectUtil.checkNotNull;
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 public abstract class HttpObjectDecoder extends ByteToMessageDecoder {
147 public static final int DEFAULT_MAX_INITIAL_LINE_LENGTH = 4096;
148 public static final int DEFAULT_MAX_HEADER_SIZE = 8192;
149 public static final boolean DEFAULT_CHUNKED_SUPPORTED = true;
150 public static final boolean DEFAULT_ALLOW_PARTIAL_CHUNKS = true;
151 public static final int DEFAULT_MAX_CHUNK_SIZE = 8192;
152 public static final boolean DEFAULT_VALIDATE_HEADERS = true;
153 public static final int DEFAULT_INITIAL_BUFFER_SIZE = 128;
154 public static final boolean DEFAULT_ALLOW_DUPLICATE_CONTENT_LENGTHS = false;
155 public static final boolean DEFAULT_STRICT_LINE_PARSING =
156 SystemPropertyUtil.getBoolean("io.netty.handler.codec.http.defaultStrictLineParsing", true);
157 public static final String PROP_RFC9112_TRANSFER_ENCODING = "io.netty.handler.codec.http.rfc9112TransferEncoding";
158 public static final boolean RFC9112_TRANSFER_ENCODING =
159 SystemPropertyUtil.getBoolean(PROP_RFC9112_TRANSFER_ENCODING, true);
160
161 private static final Runnable THROW_INVALID_CHUNK_EXTENSION = new Runnable() {
162 @Override
163 public void run() {
164 throw new InvalidChunkExtensionException();
165 }
166 };
167
168 private static final Runnable THROW_INVALID_LINE_SEPARATOR = new Runnable() {
169 @Override
170 public void run() {
171 throw new InvalidLineSeparatorException();
172 }
173 };
174 private static final TransferEncodingNotAllowedException TRANSFER_ENCODING_NOT_ALLOWED =
175 TransferEncodingNotAllowedException.newStatic(
176 "The Transfer-Encoding header is only allowed in HTTP/1.1 or newer");
177
178 private final int maxChunkSize;
179 private final boolean chunkedSupported;
180 private final boolean allowPartialChunks;
181
182
183
184 @Deprecated
185 protected final boolean validateHeaders;
186 protected final HttpHeadersFactory headersFactory;
187 protected final HttpHeadersFactory trailersFactory;
188 private final boolean allowDuplicateContentLengths;
189 private final boolean useRfc9112TransferEncoding;
190 private final ByteBuf parserScratchBuffer;
191 private final Runnable defaultStrictCRLFCheck;
192 private final HeaderParser headerParser;
193 private final LineParser lineParser;
194
195 private HttpMessage message;
196 private long chunkSize;
197 private long contentLength = Long.MIN_VALUE;
198 private boolean chunked;
199 private boolean isSwitchingToNonHttp1Protocol;
200
201 private final AtomicBoolean resetRequested = new AtomicBoolean();
202
203
204 private AsciiString name;
205 private String value;
206 private LastHttpContent trailer;
207
208 @Override
209 protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
210 try {
211 parserScratchBuffer.release();
212 } finally {
213 super.handlerRemoved0(ctx);
214 }
215 }
216
217
218
219
220
221 private enum State {
222 SKIP_INITIAL_LINE_CHARS,
223 SKIP_CONTROL_CHARS,
224 READ_INITIAL,
225 READ_HEADER,
226 READ_VARIABLE_LENGTH_CONTENT,
227 READ_FIXED_LENGTH_CONTENT,
228 READ_CHUNK_SIZE,
229 READ_CHUNKED_CONTENT,
230 READ_CHUNK_DELIMITER,
231 READ_CHUNK_FOOTER,
232 BAD_MESSAGE,
233 UPGRADED
234 }
235
236 private State currentState = State.SKIP_INITIAL_LINE_CHARS;
237
238
239
240
241
242
243 protected HttpObjectDecoder() {
244 this(new HttpDecoderConfig());
245 }
246
247
248
249
250
251
252 @Deprecated
253 protected HttpObjectDecoder(
254 int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean chunkedSupported) {
255 this(new HttpDecoderConfig()
256 .setMaxInitialLineLength(maxInitialLineLength)
257 .setMaxHeaderSize(maxHeaderSize)
258 .setMaxChunkSize(maxChunkSize)
259 .setChunkedSupported(chunkedSupported));
260 }
261
262
263
264
265
266
267 @Deprecated
268 protected HttpObjectDecoder(
269 int maxInitialLineLength, int maxHeaderSize, int maxChunkSize,
270 boolean chunkedSupported, boolean validateHeaders) {
271 this(new HttpDecoderConfig()
272 .setMaxInitialLineLength(maxInitialLineLength)
273 .setMaxHeaderSize(maxHeaderSize)
274 .setMaxChunkSize(maxChunkSize)
275 .setChunkedSupported(chunkedSupported)
276 .setValidateHeaders(validateHeaders));
277 }
278
279
280
281
282
283
284 @Deprecated
285 protected HttpObjectDecoder(
286 int maxInitialLineLength, int maxHeaderSize, int maxChunkSize,
287 boolean chunkedSupported, boolean validateHeaders, int initialBufferSize) {
288 this(new HttpDecoderConfig()
289 .setMaxInitialLineLength(maxInitialLineLength)
290 .setMaxHeaderSize(maxHeaderSize)
291 .setMaxChunkSize(maxChunkSize)
292 .setChunkedSupported(chunkedSupported)
293 .setValidateHeaders(validateHeaders)
294 .setInitialBufferSize(initialBufferSize));
295 }
296
297
298
299
300
301
302 @Deprecated
303 protected HttpObjectDecoder(
304 int maxInitialLineLength, int maxHeaderSize, int maxChunkSize,
305 boolean chunkedSupported, boolean validateHeaders, int initialBufferSize,
306 boolean allowDuplicateContentLengths) {
307 this(new HttpDecoderConfig()
308 .setMaxInitialLineLength(maxInitialLineLength)
309 .setMaxHeaderSize(maxHeaderSize)
310 .setMaxChunkSize(maxChunkSize)
311 .setChunkedSupported(chunkedSupported)
312 .setValidateHeaders(validateHeaders)
313 .setInitialBufferSize(initialBufferSize)
314 .setAllowDuplicateContentLengths(allowDuplicateContentLengths));
315 }
316
317
318
319
320
321
322 @Deprecated
323 protected HttpObjectDecoder(
324 int maxInitialLineLength, int maxHeaderSize, int maxChunkSize,
325 boolean chunkedSupported, boolean validateHeaders, int initialBufferSize,
326 boolean allowDuplicateContentLengths, boolean allowPartialChunks) {
327 this(new HttpDecoderConfig()
328 .setMaxInitialLineLength(maxInitialLineLength)
329 .setMaxHeaderSize(maxHeaderSize)
330 .setMaxChunkSize(maxChunkSize)
331 .setChunkedSupported(chunkedSupported)
332 .setValidateHeaders(validateHeaders)
333 .setInitialBufferSize(initialBufferSize)
334 .setAllowDuplicateContentLengths(allowDuplicateContentLengths)
335 .setAllowPartialChunks(allowPartialChunks));
336 }
337
338
339
340
341 protected HttpObjectDecoder(HttpDecoderConfig config) {
342 checkNotNull(config, "config");
343
344 parserScratchBuffer = Unpooled.buffer(config.getInitialBufferSize());
345 defaultStrictCRLFCheck = config.isStrictLineParsing() ? THROW_INVALID_LINE_SEPARATOR : null;
346 lineParser = new LineParser(parserScratchBuffer, config.getMaxInitialLineLength());
347 headerParser = new HeaderParser(parserScratchBuffer, config.getMaxHeaderSize());
348 maxChunkSize = config.getMaxChunkSize();
349 chunkedSupported = config.isChunkedSupported();
350 headersFactory = config.getHeadersFactory();
351 trailersFactory = config.getTrailersFactory();
352 validateHeaders = isValidating(headersFactory);
353 allowDuplicateContentLengths = config.isAllowDuplicateContentLengths();
354 allowPartialChunks = config.isAllowPartialChunks();
355 useRfc9112TransferEncoding = config.isUseRfc9112TransferEncoding();
356 }
357
358 protected boolean isValidating(HttpHeadersFactory headersFactory) {
359 if (headersFactory instanceof DefaultHttpHeadersFactory) {
360 DefaultHttpHeadersFactory builder = (DefaultHttpHeadersFactory) headersFactory;
361 return builder.isValidatingHeaderNames() || builder.isValidatingHeaderValues();
362 }
363 return true;
364 }
365
366 @Override
367 protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
368 if (resetRequested.get()) {
369 resetNow();
370 }
371
372 switch (currentState) {
373 case SKIP_INITIAL_LINE_CHARS:
374
375 case READ_INITIAL: try {
376 ByteBuf line = lineParser.parse(buffer, defaultStrictCRLFCheck);
377 if (line == null) {
378 return;
379 }
380 final String[] initialLine = splitInitialLine(line);
381 assert initialLine.length == 3 : "initialLine::length must be 3";
382
383 message = createMessage(initialLine);
384 currentState = State.READ_HEADER;
385
386 } catch (Exception e) {
387 out.add(invalidMessage(message, buffer, e));
388 return;
389 }
390 case READ_HEADER: try {
391 State nextState = readHeaders(buffer);
392 if (nextState == null) {
393 return;
394 }
395 currentState = nextState;
396 switch (nextState) {
397 case SKIP_CONTROL_CHARS:
398
399
400 addCurrentMessage(out);
401 out.add(LastHttpContent.EMPTY_LAST_CONTENT);
402 resetNow();
403 return;
404 case READ_CHUNK_SIZE:
405 if (!chunkedSupported) {
406 throw new IllegalArgumentException("Chunked messages not supported");
407 }
408
409 addCurrentMessage(out);
410 return;
411 default:
412
413
414
415
416
417
418 if (contentLength == 0 || contentLength == -1 && isDecodingRequest()) {
419 addCurrentMessage(out);
420 out.add(LastHttpContent.EMPTY_LAST_CONTENT);
421 resetNow();
422 return;
423 }
424
425 assert nextState == State.READ_FIXED_LENGTH_CONTENT ||
426 nextState == State.READ_VARIABLE_LENGTH_CONTENT;
427
428 addCurrentMessage(out);
429
430 if (nextState == State.READ_FIXED_LENGTH_CONTENT) {
431
432 chunkSize = contentLength;
433 }
434
435
436 return;
437 }
438 } catch (Exception e) {
439 out.add(invalidMessage(message, buffer, e));
440 return;
441 }
442 case READ_VARIABLE_LENGTH_CONTENT: {
443
444 int toRead = Math.min(buffer.readableBytes(), maxChunkSize);
445 if (toRead > 0) {
446 ByteBuf content = buffer.readRetainedSlice(toRead);
447 out.add(new DefaultHttpContent(content));
448 }
449 return;
450 }
451 case READ_FIXED_LENGTH_CONTENT: {
452 int readLimit = buffer.readableBytes();
453
454
455
456
457
458
459
460 if (readLimit == 0) {
461 return;
462 }
463
464 int toRead = Math.min(readLimit, maxChunkSize);
465 if (toRead > chunkSize) {
466 toRead = (int) chunkSize;
467 }
468 ByteBuf content = buffer.readRetainedSlice(toRead);
469 chunkSize -= toRead;
470
471 if (chunkSize == 0) {
472
473 out.add(new DefaultLastHttpContent(content, trailersFactory));
474 resetNow();
475 } else {
476 out.add(new DefaultHttpContent(content));
477 }
478 return;
479 }
480
481
482
483
484 case READ_CHUNK_SIZE: try {
485 ByteBuf line = lineParser.parse(buffer, THROW_INVALID_CHUNK_EXTENSION);
486 if (line == null) {
487 return;
488 }
489 checkChunkExtensions(line);
490 int chunkSize = getChunkSize(line.array(), line.arrayOffset() + line.readerIndex(), line.readableBytes());
491 this.chunkSize = chunkSize;
492 if (chunkSize == 0) {
493 currentState = State.READ_CHUNK_FOOTER;
494 return;
495 }
496 currentState = State.READ_CHUNKED_CONTENT;
497
498 } catch (Exception e) {
499 out.add(invalidChunk(buffer, e));
500 return;
501 }
502 case READ_CHUNKED_CONTENT: {
503 assert chunkSize <= Integer.MAX_VALUE;
504 int toRead = Math.min((int) chunkSize, maxChunkSize);
505 if (!allowPartialChunks && buffer.readableBytes() < toRead) {
506 return;
507 }
508 toRead = Math.min(toRead, buffer.readableBytes());
509 if (toRead == 0) {
510 return;
511 }
512 HttpContent chunk = new DefaultHttpContent(buffer.readRetainedSlice(toRead));
513 chunkSize -= toRead;
514
515 out.add(chunk);
516
517 if (chunkSize != 0) {
518 return;
519 }
520 currentState = State.READ_CHUNK_DELIMITER;
521
522 }
523 case READ_CHUNK_DELIMITER: {
524 if (buffer.readableBytes() >= 2) {
525 int rIdx = buffer.readerIndex();
526 if (buffer.getByte(rIdx) == HttpConstants.CR &&
527 buffer.getByte(rIdx + 1) == HttpConstants.LF) {
528 buffer.skipBytes(2);
529 currentState = State.READ_CHUNK_SIZE;
530 } else {
531 out.add(invalidChunk(buffer, new InvalidChunkTerminationException()));
532 }
533 }
534 return;
535 }
536 case READ_CHUNK_FOOTER: try {
537 LastHttpContent trailer = readTrailingHeaders(buffer);
538 if (trailer == null) {
539 return;
540 }
541 out.add(trailer);
542 resetNow();
543 return;
544 } catch (Exception e) {
545 out.add(invalidChunk(buffer, e));
546 return;
547 }
548 case BAD_MESSAGE: {
549
550 buffer.skipBytes(buffer.readableBytes());
551 break;
552 }
553 case UPGRADED: {
554 int readableBytes = buffer.readableBytes();
555 if (readableBytes > 0) {
556
557
558
559
560 out.add(buffer.readBytes(readableBytes));
561 }
562 break;
563 }
564 default:
565 break;
566 }
567 }
568
569 @Override
570 protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
571 super.decodeLast(ctx, in, out);
572
573 if (resetRequested.get()) {
574
575
576 resetNow();
577 }
578
579
580 switch (currentState) {
581 case READ_VARIABLE_LENGTH_CONTENT:
582 if (!chunked && !in.isReadable()) {
583
584 out.add(LastHttpContent.EMPTY_LAST_CONTENT);
585 resetNow();
586 }
587 return;
588 case READ_HEADER:
589
590
591 out.add(invalidMessage(message, Unpooled.EMPTY_BUFFER,
592 new PrematureChannelClosureException("Connection closed before received headers")));
593 resetNow();
594 return;
595 case READ_CHUNK_DELIMITER:
596 case READ_CHUNK_FOOTER:
597 case READ_CHUNKED_CONTENT:
598 case READ_CHUNK_SIZE:
599 case READ_FIXED_LENGTH_CONTENT:
600
601 boolean prematureClosure;
602 if (isDecodingRequest() || chunked) {
603
604 prematureClosure = true;
605 } else {
606
607
608
609 prematureClosure = contentLength > 0;
610 }
611 if (!prematureClosure) {
612 out.add(LastHttpContent.EMPTY_LAST_CONTENT);
613 }
614 resetNow();
615 return;
616 case SKIP_CONTROL_CHARS:
617 case SKIP_INITIAL_LINE_CHARS:
618 case READ_INITIAL:
619 case BAD_MESSAGE:
620 case UPGRADED:
621
622 break;
623 default:
624 throw new IllegalStateException("Unhandled state " + currentState);
625 }
626 }
627
628 @Override
629 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
630 if (evt instanceof HttpExpectationFailedEvent) {
631 switch (currentState) {
632 case READ_FIXED_LENGTH_CONTENT:
633 case READ_VARIABLE_LENGTH_CONTENT:
634 case READ_CHUNK_SIZE:
635 reset();
636 break;
637 default:
638 break;
639 }
640 }
641 super.userEventTriggered(ctx, evt);
642 }
643
644 private void addCurrentMessage(List<Object> out) {
645 HttpMessage message = this.message;
646 assert message != null;
647 this.message = null;
648 out.add(message);
649 }
650
651 protected boolean isContentAlwaysEmpty(HttpMessage msg) {
652 if (msg instanceof HttpResponse) {
653 HttpResponse res = (HttpResponse) msg;
654 final HttpResponseStatus status = res.status();
655 final int code = status.code();
656 final HttpStatusClass statusClass = status.codeClass();
657
658
659
660
661
662
663 if (statusClass == HttpStatusClass.INFORMATIONAL) {
664
665 return !(code == 101 && !res.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT)
666 && res.headers().contains(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET, true));
667 }
668
669 switch (code) {
670 case 204: case 304:
671 return true;
672 default:
673 return false;
674 }
675 }
676 return false;
677 }
678
679
680
681
682
683 protected boolean isSwitchingToNonHttp1Protocol(HttpResponse msg) {
684 if (msg.status().code() != HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
685 return false;
686 }
687 String newProtocol = msg.headers().get(HttpHeaderNames.UPGRADE);
688 return newProtocol == null ||
689 !newProtocol.contains(HttpVersion.HTTP_1_0.text()) &&
690 !newProtocol.contains(HttpVersion.HTTP_1_1.text());
691 }
692
693
694
695
696
697 public void reset() {
698 resetRequested.lazySet(true);
699 }
700
701 private void resetNow() {
702 message = null;
703 name = null;
704 value = null;
705 clearContentLength();
706 chunked = false;
707 lineParser.reset();
708 headerParser.reset();
709 trailer = null;
710 if (isSwitchingToNonHttp1Protocol) {
711 isSwitchingToNonHttp1Protocol = false;
712 currentState = State.UPGRADED;
713 return;
714 }
715
716 resetRequested.lazySet(false);
717 currentState = State.SKIP_INITIAL_LINE_CHARS;
718 }
719
720 private HttpMessage invalidMessage(HttpMessage current, ByteBuf in, Exception cause) {
721 currentState = State.BAD_MESSAGE;
722 message = null;
723 trailer = null;
724
725
726
727 in.skipBytes(in.readableBytes());
728
729 if (current == null) {
730 current = createInvalidMessage();
731 }
732 current.setDecoderResult(DecoderResult.failure(cause));
733
734 return current;
735 }
736
737 private static void checkChunkExtensions(ByteBuf line) {
738 int extensionsStart = line.bytesBefore((byte) ';');
739 if (extensionsStart == -1) {
740 return;
741 }
742 HttpChunkLineValidatingByteProcessor processor = new HttpChunkLineValidatingByteProcessor();
743 line.forEachByte(processor);
744 processor.finish();
745 }
746
747 private HttpContent invalidChunk(ByteBuf in, Exception cause) {
748 currentState = State.BAD_MESSAGE;
749 message = null;
750 trailer = null;
751
752
753
754 in.skipBytes(in.readableBytes());
755
756 HttpContent chunk = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER);
757 chunk.setDecoderResult(DecoderResult.failure(cause));
758 return chunk;
759 }
760
761 private State readHeaders(ByteBuf buffer) {
762 final HttpMessage message = this.message;
763 final HttpHeaders headers = message.headers();
764
765 final HeaderParser headerParser = this.headerParser;
766
767 ByteBuf line = headerParser.parse(buffer, defaultStrictCRLFCheck);
768 if (line == null) {
769 return null;
770 }
771 int lineLength = line.readableBytes();
772 while (lineLength > 0) {
773 final byte[] lineContent = line.array();
774 final int startLine = line.arrayOffset() + line.readerIndex();
775 final byte firstChar = lineContent[startLine];
776 if (name != null && (firstChar == ' ' || firstChar == '\t')) {
777
778
779 String trimmedLine = langAsciiString(lineContent, startLine, lineLength).trim();
780 String valueStr = value;
781 value = valueStr + ' ' + trimmedLine;
782 } else {
783 if (name != null) {
784 headers.add(name, value);
785 }
786 splitHeader(lineContent, startLine, lineLength);
787 }
788
789 line = headerParser.parse(buffer, defaultStrictCRLFCheck);
790 if (line == null) {
791 return null;
792 }
793 lineLength = line.readableBytes();
794 }
795
796
797 if (name != null) {
798 headers.add(name, value);
799 }
800
801
802 name = null;
803 value = null;
804
805
806 HttpMessageDecoderResult decoderResult = new HttpMessageDecoderResult(lineParser.size, headerParser.size);
807 message.setDecoderResult(decoderResult);
808
809 List<String> contentLengthFields = headers.getAll(HttpHeaderNames.CONTENT_LENGTH);
810 if (!contentLengthFields.isEmpty()) {
811 HttpVersion version = message.protocolVersion();
812 boolean isHttp10OrEarlier = version.majorVersion() < 1 || (version.majorVersion() == 1
813 && version.minorVersion() == 0);
814
815
816 contentLength = HttpUtil.normalizeAndGetContentLength(contentLengthFields,
817 isHttp10OrEarlier, allowDuplicateContentLengths);
818 if (contentLength != -1) {
819 String lengthValue = contentLengthFields.get(0).trim();
820 if (contentLengthFields.size() > 1 ||
821 !isLengthEqual(lengthValue, contentLength)) {
822 headers.set(HttpHeaderNames.CONTENT_LENGTH, contentLength);
823 }
824 }
825 } else {
826
827
828 contentLength = HttpUtil.getWebSocketContentLength(message);
829 }
830 if (!isDecodingRequest() && message instanceof HttpResponse) {
831 HttpResponse res = (HttpResponse) message;
832 this.isSwitchingToNonHttp1Protocol = isSwitchingToNonHttp1Protocol(res);
833 }
834 if (isContentAlwaysEmpty(message)) {
835 HttpUtil.setTransferEncodingChunked(message, false);
836 return State.SKIP_CONTROL_CHARS;
837 }
838 boolean hasTransferEncoding = message.headers().contains(HttpHeaderNames.TRANSFER_ENCODING);
839 if (hasTransferEncoding &&
840 message.protocolVersion() != HttpVersion.HTTP_1_1 &&
841 useRfc9112TransferEncoding) {
842
843
844 throw TRANSFER_ENCODING_NOT_ALLOWED;
845 }
846 boolean isTransferEncodingChunked = HttpUtil.isTransferEncodingChunked(message);
847
848
849 if (hasTransferEncoding && !isTransferEncodingChunked && isDecodingRequest()) {
850 throw new IllegalArgumentException("The final transfer coding must be chunked for HTTP requests");
851 }
852 if (isTransferEncodingChunked) {
853 this.chunked = true;
854
855
856
857
858
859
860
861 if (!isLastTransferEncodingChunked(headers.getAll(HttpHeaderNames.TRANSFER_ENCODING))) {
862 throw new IllegalArgumentException(
863 "chunked must be the last encoding present in the Transfer-Encoding header");
864 }
865 if (message.protocolVersion() == HttpVersion.HTTP_1_1) {
866 if (!contentLengthFields.isEmpty()) {
867 handleTransferEncodingChunkedWithContentLength(message);
868 }
869 }
870 return State.READ_CHUNK_SIZE;
871 }
872 if (contentLength >= 0) {
873 return State.READ_FIXED_LENGTH_CONTENT;
874 }
875 return State.READ_VARIABLE_LENGTH_CONTENT;
876 }
877
878 private static boolean isLastTransferEncodingChunked(List<String> transferEncodingFields) {
879 boolean chunkedSeen = false;
880 boolean lastChunked = false;
881 int chunkedLength = HttpHeaderValues.CHUNKED.length();
882 for (int i = 0; i < transferEncodingFields.size(); ++i) {
883 String value = transferEncodingFields.get(i);
884 int start = 0;
885 while (start <= value.length()) {
886 int comma = value.indexOf(',', start);
887 int end = comma == -1 ? value.length() : comma;
888 while (start < end && (value.charAt(start) == ' ' || value.charAt(start) == '\t')) {
889 ++start;
890 }
891 while (end > start && (value.charAt(end - 1) == ' ' || value.charAt(end - 1) == '\t')) {
892 --end;
893 }
894 if (start < end) {
895 lastChunked = end - start == chunkedLength &&
896 HttpHeaderValues.CHUNKED.regionMatches(true, 0, value, start, chunkedLength);
897 if (lastChunked) {
898 if (chunkedSeen) {
899 throw new IllegalArgumentException(
900 "chunked transfer coding must not be applied more than once");
901 }
902 chunkedSeen = true;
903 }
904 }
905 if (comma == -1) {
906 break;
907 }
908 start = comma + 1;
909 }
910 }
911 return lastChunked;
912 }
913
914 private static boolean isLengthEqual(String lengthValue, long contentLength) {
915 try {
916 return Long.parseLong(lengthValue) == contentLength;
917 } catch (NumberFormatException e) {
918 return false;
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 @SuppressWarnings("unused")
970 protected void handleTransferEncodingChunkedWithContentLength(HttpMessage message) {
971 clearContentLength();
972 if (useRfc9112TransferEncoding) {
973 throw new ContentLengthNotAllowedException(
974 "Content-Length are not allowed in HTTP/1.1 messages that contains a Transfer-Encoding header.");
975 } else {
976 message.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
977 if (isDecodingRequest()) {
978 HttpUtil.setKeepAlive(message, false);
979 }
980 }
981 }
982
983 protected final void clearContentLength() {
984 contentLength = Long.MIN_VALUE;
985 }
986
987 private LastHttpContent readTrailingHeaders(ByteBuf buffer) {
988 final HeaderParser headerParser = this.headerParser;
989 ByteBuf line = headerParser.parse(buffer, defaultStrictCRLFCheck);
990 if (line == null) {
991 return null;
992 }
993 LastHttpContent trailer = this.trailer;
994 int lineLength = line.readableBytes();
995 if (lineLength == 0 && trailer == null) {
996
997
998 return LastHttpContent.EMPTY_LAST_CONTENT;
999 }
1000
1001 if (trailer == null) {
1002 trailer = this.trailer = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER, trailersFactory);
1003 }
1004 while (lineLength > 0) {
1005 final byte[] lineContent = line.array();
1006 final int startLine = line.arrayOffset() + line.readerIndex();
1007 final byte firstChar = lineContent[startLine];
1008 if (name != null && (firstChar == ' ' || firstChar == '\t')) {
1009
1010
1011 String trimmedLine = langAsciiString(lineContent, startLine, lineLength).trim();
1012 String valueStr = value;
1013 value = valueStr + ' ' + trimmedLine;
1014 } else {
1015 if (name != null && isPermittedTrailingHeader(name)) {
1016 trailer.trailingHeaders().add(name, value);
1017 }
1018 splitHeader(lineContent, startLine, lineLength);
1019 }
1020
1021 line = headerParser.parse(buffer, defaultStrictCRLFCheck);
1022 if (line == null) {
1023 return null;
1024 }
1025 lineLength = line.readableBytes();
1026 }
1027
1028
1029 if (name != null && isPermittedTrailingHeader(name)) {
1030 trailer.trailingHeaders().add(name, value);
1031 }
1032
1033
1034 name = null;
1035 value = null;
1036
1037 this.trailer = null;
1038 return trailer;
1039 }
1040
1041
1042
1043
1044 private static boolean isPermittedTrailingHeader(final AsciiString name) {
1045 return !HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(name) &&
1046 !HttpHeaderNames.TRANSFER_ENCODING.contentEqualsIgnoreCase(name) &&
1047 !HttpHeaderNames.TRAILER.contentEqualsIgnoreCase(name);
1048 }
1049
1050 protected abstract boolean isDecodingRequest();
1051 protected abstract HttpMessage createMessage(String[] initialLine) throws Exception;
1052 protected abstract HttpMessage createInvalidMessage();
1053
1054 private static int getChunkSize(byte[] hex, int start, int length) {
1055 if (length == 0) {
1056 throw new NumberFormatException("Empty chunk size");
1057 }
1058 long result = 0;
1059 for (int i = 0; i < length; i++) {
1060 final int digit = StringUtil.decodeHexNibble(hex[start + i]);
1061 if (digit == -1) {
1062
1063
1064
1065 byte b = hex[start + i];
1066 int j = 0;
1067 while (b == HttpConstants.SP || b == HttpConstants.HT) {
1068 int index = i + (++j);
1069 if (index >= length) {
1070 throw new NumberFormatException("Invalid chunk size; expected extensions");
1071 }
1072 b = hex[start + index];
1073 }
1074 if (b == ';') {
1075 if (i == 0) {
1076 throw new NumberFormatException("Empty chunk size");
1077 }
1078 return (int) result;
1079 }
1080
1081 throw new NumberFormatException("Invalid character in chunk size");
1082 }
1083 result *= 16;
1084 result += digit;
1085 if (result > Integer.MAX_VALUE) {
1086 throw new NumberFormatException("Chunk size overflow: " + result);
1087 }
1088 }
1089 return (int) result;
1090 }
1091
1092 private String[] splitInitialLine(ByteBuf asciiBuffer) {
1093 final byte[] asciiBytes = asciiBuffer.array();
1094
1095 final int arrayOffset = asciiBuffer.arrayOffset();
1096
1097 final int startContent = arrayOffset + asciiBuffer.readerIndex();
1098
1099 final int end = startContent + asciiBuffer.readableBytes();
1100
1101 byte lastByte = asciiBytes[end - 1];
1102 if (isControlOrWhitespaceAsciiChar(lastByte)) {
1103 if (isDecodingRequest() || !isOWS(lastByte)) {
1104
1105
1106
1107
1108
1109 throw new IllegalArgumentException(
1110 "Illegal character in request line: 0x" + Integer.toHexString(lastByte));
1111 }
1112 }
1113
1114 final int aStart = findNonSPLenient(asciiBytes, startContent, end);
1115 final int aEnd = findSPLenient(asciiBytes, aStart, end);
1116
1117 final int bStart = findNonSPLenient(asciiBytes, aEnd, end);
1118 final int bEnd = findSPLenient(asciiBytes, bStart, end);
1119
1120 final int cStart = findNonSPLenient(asciiBytes, bEnd, end);
1121 final int cEnd = findEndOfString(asciiBytes, Math.max(cStart - 1, startContent), end);
1122
1123 return new String[]{
1124 splitFirstWordInitialLine(asciiBytes, aStart, aEnd - aStart),
1125 splitSecondWordInitialLine(asciiBytes, bStart, bEnd - bStart),
1126 cStart < cEnd ? splitThirdWordInitialLine(asciiBytes, cStart, cEnd - cStart) : StringUtil.EMPTY_STRING};
1127 }
1128
1129 protected String splitFirstWordInitialLine(final byte[] asciiContent, int start, int length) {
1130 return langAsciiString(asciiContent, start, length);
1131 }
1132
1133 protected String splitSecondWordInitialLine(final byte[] asciiContent, int start, int length) {
1134 return langAsciiString(asciiContent, start, length);
1135 }
1136
1137 protected String splitThirdWordInitialLine(final byte[] asciiContent, int start, int length) {
1138 return langAsciiString(asciiContent, start, length);
1139 }
1140
1141
1142
1143
1144 private static String langAsciiString(final byte[] asciiContent, int start, int length) {
1145 if (length == 0) {
1146 return StringUtil.EMPTY_STRING;
1147 }
1148
1149 if (start == 0) {
1150 if (length == asciiContent.length) {
1151 return new String(asciiContent, 0, 0, asciiContent.length);
1152 }
1153 return new String(asciiContent, 0, 0, length);
1154 }
1155 return new String(asciiContent, 0, start, length);
1156 }
1157
1158 private void splitHeader(byte[] line, int start, int length) {
1159 final int end = start + length;
1160 int nameEnd;
1161 final int nameStart = start;
1162
1163 final boolean isDecodingRequest = isDecodingRequest();
1164 for (nameEnd = nameStart; nameEnd < end; nameEnd ++) {
1165 byte ch = line[nameEnd];
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175 if (ch == ':' ||
1176
1177
1178
1179
1180 (!isDecodingRequest && isOWS(ch))) {
1181 break;
1182 }
1183 }
1184
1185 if (nameEnd == end) {
1186
1187 throw new IllegalArgumentException("No colon found");
1188 }
1189 int colonEnd;
1190 for (colonEnd = nameEnd; colonEnd < end; colonEnd ++) {
1191 if (line[colonEnd] == ':') {
1192 colonEnd ++;
1193 break;
1194 }
1195 }
1196 name = splitHeaderName(line, nameStart, nameEnd - nameStart);
1197 final int valueStart = findNonWhitespace(line, colonEnd, end);
1198 if (valueStart == end) {
1199 value = StringUtil.EMPTY_STRING;
1200 } else {
1201 final int valueEnd = findEndOfString(line, start, end);
1202
1203 value = langAsciiString(line, valueStart, valueEnd - valueStart);
1204 }
1205 }
1206
1207 protected AsciiString splitHeaderName(byte[] sb, int start, int length) {
1208 return new AsciiString(sb, start, length, true);
1209 }
1210
1211 private static int findNonSPLenient(byte[] sb, int offset, int end) {
1212 for (int result = offset; result < end; ++result) {
1213 byte c = sb[result];
1214
1215 if (isSPLenient(c)) {
1216 continue;
1217 }
1218 if (isWhitespace(c)) {
1219
1220 throw new IllegalArgumentException("Invalid separator");
1221 }
1222 return result;
1223 }
1224 return end;
1225 }
1226
1227 private static int findSPLenient(byte[] sb, int offset, int end) {
1228 for (int result = offset; result < end; ++result) {
1229 if (isSPLenient(sb[result])) {
1230 return result;
1231 }
1232 }
1233 return end;
1234 }
1235
1236 private static final boolean[] SP_LENIENT_BYTES;
1237 private static final boolean[] LATIN_WHITESPACE;
1238
1239 static {
1240
1241 SP_LENIENT_BYTES = new boolean[256];
1242 SP_LENIENT_BYTES[128 + ' '] = true;
1243 SP_LENIENT_BYTES[128 + 0x09] = true;
1244 SP_LENIENT_BYTES[128 + 0x0B] = true;
1245 SP_LENIENT_BYTES[128 + 0x0C] = true;
1246 SP_LENIENT_BYTES[128 + 0x0D] = true;
1247
1248 LATIN_WHITESPACE = new boolean[256];
1249 for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) {
1250 LATIN_WHITESPACE[128 + b] = Character.isWhitespace(b);
1251 }
1252 }
1253
1254 private static boolean isSPLenient(byte c) {
1255
1256 return SP_LENIENT_BYTES[c + 128];
1257 }
1258
1259 private static boolean isWhitespace(byte b) {
1260 return LATIN_WHITESPACE[b + 128];
1261 }
1262
1263 private static int findNonWhitespace(byte[] sb, int offset, int end) {
1264 for (int result = offset; result < end; ++result) {
1265 byte c = sb[result];
1266 if (!isWhitespace(c)) {
1267 return result;
1268 } else if (!isOWS(c)) {
1269
1270 throw new IllegalArgumentException("Invalid separator, only a single space or horizontal tab allowed," +
1271 " but received a '" + c + "' (0x" + Integer.toHexString(c) + ")");
1272 }
1273 }
1274 return end;
1275 }
1276
1277 private static int findEndOfString(byte[] sb, int start, int end) {
1278 for (int result = end - 1; result > start; --result) {
1279 if (!isOWS(sb[result])) {
1280 return result + 1;
1281 }
1282 }
1283 return 0;
1284 }
1285
1286 private static boolean isOWS(byte ch) {
1287 return ch == ' ' || ch == 0x09;
1288 }
1289
1290 private static class HeaderParser {
1291 protected final ByteBuf seq;
1292 protected final int maxLength;
1293 int size;
1294
1295 HeaderParser(ByteBuf seq, int maxLength) {
1296 this.seq = seq;
1297 this.maxLength = maxLength;
1298 }
1299
1300 public ByteBuf parse(ByteBuf buffer, Runnable strictCRLFCheck) {
1301 final int readableBytes = buffer.readableBytes();
1302 final int readerIndex = buffer.readerIndex();
1303 final int maxBodySize = maxLength - size;
1304 assert maxBodySize >= 0;
1305
1306
1307 final long maxBodySizeWithCRLF = maxBodySize + 2L;
1308 final int toProcess = (int) Math.min(maxBodySizeWithCRLF, readableBytes);
1309 final int toIndexExclusive = readerIndex + toProcess;
1310 assert toIndexExclusive >= readerIndex;
1311 final int indexOfLf = buffer.indexOf(readerIndex, toIndexExclusive, HttpConstants.LF);
1312 if (indexOfLf == -1) {
1313 if (readableBytes > maxBodySize) {
1314
1315
1316
1317
1318 throw newException(maxLength);
1319 }
1320 return null;
1321 }
1322 final int endOfSeqIncluded;
1323 if (indexOfLf > readerIndex && buffer.getByte(indexOfLf - 1) == HttpConstants.CR) {
1324
1325 endOfSeqIncluded = indexOfLf - 1;
1326 } else {
1327 if (strictCRLFCheck != null) {
1328 strictCRLFCheck.run();
1329 }
1330 endOfSeqIncluded = indexOfLf;
1331 }
1332 final int newSize = endOfSeqIncluded - readerIndex;
1333 if (newSize == 0) {
1334 seq.clear();
1335 buffer.readerIndex(indexOfLf + 1);
1336 return seq;
1337 }
1338 int size = this.size + newSize;
1339 if (size > maxLength) {
1340 throw newException(maxLength);
1341 }
1342 this.size = size;
1343 seq.clear();
1344 seq.writeBytes(buffer, readerIndex, newSize);
1345 buffer.readerIndex(indexOfLf + 1);
1346 return seq;
1347 }
1348
1349 public void reset() {
1350 size = 0;
1351 }
1352
1353 protected TooLongFrameException newException(int maxLength) {
1354 return new TooLongHttpHeaderException("HTTP header is larger than " + maxLength + " bytes.");
1355 }
1356 }
1357
1358 private final class LineParser extends HeaderParser {
1359
1360 LineParser(ByteBuf seq, int maxLength) {
1361 super(seq, maxLength);
1362 }
1363
1364 @Override
1365 public ByteBuf parse(ByteBuf buffer, Runnable strictCRLFCheck) {
1366
1367 reset();
1368 final int readableBytes = buffer.readableBytes();
1369 if (readableBytes == 0) {
1370 return null;
1371 }
1372 if (currentState == State.SKIP_INITIAL_LINE_CHARS &&
1373 skipLineChars(buffer, readableBytes, buffer.readerIndex(), strictCRLFCheck)) {
1374 return null;
1375 }
1376 return super.parse(buffer, strictCRLFCheck);
1377 }
1378
1379 private boolean skipLineChars(ByteBuf buffer, int readableBytes, int readerIndex, Runnable strictCRLFCheck) {
1380 assert currentState == State.SKIP_INITIAL_LINE_CHARS;
1381 final int maxToSkip = Math.min(maxLength, readableBytes);
1382 final int firstNonLineIndex = buffer.forEachByte(readerIndex, maxToSkip,
1383 strictCRLFCheck == null ? SKIP_CONTROL_CHARS_BYTES : ByteProcessor.FIND_NON_CRLF);
1384 if (firstNonLineIndex == -1) {
1385 buffer.skipBytes(maxToSkip);
1386 if (readableBytes > maxLength) {
1387 throw newException(maxLength);
1388 }
1389 return true;
1390 }
1391 if (strictCRLFCheck != null) {
1392 final int b = buffer.getByte(firstNonLineIndex) & 0xFF;
1393 if (Character.isISOControl(b)) {
1394 strictCRLFCheck.run();
1395 }
1396 }
1397
1398 buffer.readerIndex(firstNonLineIndex);
1399 currentState = State.READ_INITIAL;
1400 return false;
1401 }
1402
1403 @Override
1404 protected TooLongFrameException newException(int maxLength) {
1405 return new TooLongHttpLineException("An HTTP line is larger than " + maxLength + " bytes.");
1406 }
1407 }
1408
1409 private static final boolean[] ISO_CONTROL_OR_WHITESPACE;
1410
1411 static {
1412 ISO_CONTROL_OR_WHITESPACE = new boolean[256];
1413 for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) {
1414 ISO_CONTROL_OR_WHITESPACE[128 + b] = Character.isISOControl(b) || isWhitespace(b);
1415 }
1416 }
1417
1418 private static final ByteProcessor SKIP_CONTROL_CHARS_BYTES = new ByteProcessor() {
1419 @Override
1420 public boolean process(byte value) {
1421 return ISO_CONTROL_OR_WHITESPACE[128 + value];
1422 }
1423 };
1424
1425 private static boolean isControlOrWhitespaceAsciiChar(byte b) {
1426 return ISO_CONTROL_OR_WHITESPACE[128 + b];
1427 }
1428 }