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