View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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   * Decodes {@link ByteBuf}s into {@link HttpMessage}s and
38   * {@link HttpContent}s.
39   *
40   * <h3>Parameters that prevents excessive memory consumption</h3>
41   * <table border="1">
42   * <tr>
43   * <th>Name</th><th>Default value</th><th>Meaning</th>
44   * </tr>
45   * <tr>
46   * <td>{@code maxInitialLineLength}</td>
47   * <td>{@value #DEFAULT_MAX_INITIAL_LINE_LENGTH}</td>
48   * <td>The maximum length of the initial line
49   *     (e.g. {@code "GET / HTTP/1.0"} or {@code "HTTP/1.0 200 OK"})
50   *     If the length of the initial line exceeds this value, a
51   *     {@link TooLongHttpLineException} will be raised.</td>
52   * </tr>
53   * <tr>
54   * <td>{@code maxHeaderSize}</td>
55   * <td>{@value #DEFAULT_MAX_HEADER_SIZE}</td>
56   * <td>The maximum length of all headers.  If the sum of the length of each
57   *     header exceeds this value, a {@link TooLongHttpHeaderException} will be raised.</td>
58   * </tr>
59   * <tr>
60   * <td>{@code maxChunkSize}</td>
61   * <td>{@value #DEFAULT_MAX_CHUNK_SIZE}</td>
62   * <td>The maximum length of the content or each chunk.  If the content length
63   *     (or the length of each chunk) exceeds this value, the content or chunk
64   *     will be split into multiple {@link HttpContent}s whose length is
65   *     {@code maxChunkSize} at maximum.</td>
66   * </tr>
67   * </table>
68   *
69   * <h3>Parameters that control parsing behavior</h3>
70   * <table border="1">
71   * <tr>
72   * <th>Name</th><th>Default value</th><th>Meaning</th>
73   * </tr>
74   * <tr>
75   * <td>{@code allowDuplicateContentLengths}</td>
76   * <td>{@value #DEFAULT_ALLOW_DUPLICATE_CONTENT_LENGTHS}</td>
77   * <td>When set to {@code false}, will reject any messages that contain multiple Content-Length header fields.
78   *     When set to {@code true}, will allow multiple Content-Length headers only if they are all the same decimal value.
79   *     The duplicated field-values will be replaced with a single valid Content-Length field.
80   *     See <a href="https://tools.ietf.org/html/rfc7230#section-3.3.2">RFC 7230, Section 3.3.2</a>.</td>
81   * </tr>
82   * <tr>
83   * <td>{@code allowPartialChunks}</td>
84   * <td>{@value #DEFAULT_ALLOW_PARTIAL_CHUNKS}</td>
85   * <td>If the length of a chunk exceeds the {@link ByteBuf}s readable bytes and {@code allowPartialChunks}
86   *     is set to {@code true}, the chunk will be split into multiple {@link HttpContent}s.
87   *     Otherwise, if the chunk size does not exceed {@code maxChunkSize} and {@code allowPartialChunks}
88   *     is set to {@code false}, the {@link ByteBuf} is not decoded into an {@link HttpContent} until
89   *     the readable bytes are greater or equal to the chunk size.</td>
90   * </tr>
91   * </table>
92   *
93   * <h3>Chunked Content</h3>
94   *
95   * If the content of an HTTP message is greater than {@code maxChunkSize} or
96   * the transfer encoding of the HTTP message is 'chunked', this decoder
97   * generates one {@link HttpMessage} instance and its following
98   * {@link HttpContent}s per single HTTP message to avoid excessive memory
99   * consumption. For example, the following HTTP message:
100  * <pre>
101  * GET / HTTP/1.1
102  * Transfer-Encoding: chunked
103  *
104  * 1a
105  * abcdefghijklmnopqrstuvwxyz
106  * 10
107  * 1234567890abcdef
108  * 0
109  * Content-MD5: ...
110  * <i>[blank line]</i>
111  * </pre>
112  * triggers {@link HttpRequestDecoder} to generate 3 objects:
113  * <ol>
114  * <li>An {@link HttpRequest},</li>
115  * <li>The first {@link HttpContent} whose content is {@code 'abcdefghijklmnopqrstuvwxyz'},</li>
116  * <li>The second {@link LastHttpContent} whose content is {@code '1234567890abcdef'}, which marks
117  * the end of the content.</li>
118  * </ol>
119  *
120  * If you prefer not to handle {@link HttpContent}s by yourself for your
121  * convenience, insert {@link HttpObjectAggregator} after this decoder in the
122  * {@link ChannelPipeline}.  However, please note that your server might not
123  * be as memory efficient as without the aggregator.
124  *
125  * <h3>Extensibility</h3>
126  *
127  * Please note that this decoder is designed to be extended to implement
128  * a protocol derived from HTTP, such as
129  * <a href="https://en.wikipedia.org/wiki/Real_Time_Streaming_Protocol">RTSP</a> and
130  * <a href="https://en.wikipedia.org/wiki/Internet_Content_Adaptation_Protocol">ICAP</a>.
131  * To implement the decoder of such a derived protocol, extend this class and
132  * implement all abstract methods properly.
133  *
134  * <h3>Header Validation</h3>
135  *
136  * It is recommended to always enable header validation.
137  * <p>
138  * Without header validation, your system can become vulnerable to
139  * <a href="https://cwe.mitre.org/data/definitions/113.html">
140  *     CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')
141  * </a>.
142  * <p>
143  * This recommendation stands even when both peers in the HTTP exchange are trusted,
144  * as it helps with defence-in-depth.
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      * This field is no longer used. It is only kept around for backwards compatibility purpose.
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     // These will be updated by splitHeader(...)
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      * The internal state of {@link HttpObjectDecoder}.
220      * <em>Internal use only</em>.
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      * Creates a new instance with the default
241      * {@code maxInitialLineLength (4096)}, {@code maxHeaderSize (8192)}, and
242      * {@code maxChunkSize (8192)}.
243      */
244     protected HttpObjectDecoder() {
245         this(new HttpDecoderConfig());
246     }
247 
248     /**
249      * Creates a new instance with the specified parameters.
250      *
251      * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead.
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      * Creates a new instance with the specified parameters.
265      *
266      * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead.
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      * Creates a new instance with the specified parameters.
282      *
283      * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead.
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      * Creates a new instance with the specified parameters.
300      *
301      * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead.
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      * Creates a new instance with the specified parameters.
320      *
321      * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead.
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      * Creates a new instance with the specified configuration.
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; // We can't actually tell in this case, but we assume some validation is taking place.
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             // Fall-through
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             // fall-through
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                 // fast-path
400                 // No content is expected.
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                 // Chunked encoding - generate HttpMessage first.  HttpChunks will follow.
410                 addCurrentMessage(out);
411                 return;
412             default:
413                 /*
414                  * RFC 7230, 3.3.3 (https://tools.ietf.org/html/rfc7230#section-3.3.3) states that if a
415                  * request does not have either a transfer-encoding or a content-length header then the message body
416                  * length is 0. However, for a response the body length is the number of octets received prior to the
417                  * server closing the connection. So we treat this as variable length chunked encoding.
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                     // chunkSize will be decreased as the READ_FIXED_LENGTH_CONTENT state reads data chunk by chunk.
433                     chunkSize = contentLength;
434                 }
435 
436                 // We return here, this forces decode to be called again where we will decode the content
437                 return;
438             }
439         } catch (Exception e) {
440             out.add(invalidMessage(message, buffer, e));
441             return;
442         }
443         case READ_VARIABLE_LENGTH_CONTENT: {
444             // Keep reading data as a chunk until the end of connection is reached.
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             // Check if the buffer is readable first as we use the readable byte count
456             // to create the HttpChunk. This is needed as otherwise we may end up with
457             // create an HttpChunk instance that contains an empty buffer and so is
458             // handled like it is the last HttpChunk.
459             //
460             // See https://github.com/netty/netty/issues/433
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                 // Read all content.
474                 out.add(new DefaultLastHttpContent(content, trailersFactory));
475                 resetNow();
476             } else {
477                 out.add(new DefaultHttpContent(content));
478             }
479             return;
480         }
481         /*
482          * Everything else after this point takes care of reading chunked content. Basically, read chunk size,
483          * read chunk, read and ignore the CRLF and repeat until 0
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             // fall-through
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             // fall-through
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             // Keep discarding until disconnection.
551             buffer.skipBytes(buffer.readableBytes());
552             break;
553         }
554         case UPGRADED: {
555             int readableBytes = buffer.readableBytes();
556             if (readableBytes > 0) {
557                 // Keep on consuming as otherwise we may trigger an DecoderException,
558                 // other handler will replace this codec with the upgraded protocol codec to
559                 // take the traffic over at some point then.
560                 // See https://github.com/netty/netty/issues/2173
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             // If a reset was requested by decodeLast() we need to do it now otherwise we may produce a
576             // LastHttpContent while there was already one.
577             resetNow();
578         }
579 
580         // Handle the last unfinished message.
581         switch (currentState) {
582             case READ_VARIABLE_LENGTH_CONTENT:
583                 if (!chunked && !in.isReadable()) {
584                     // End of connection.
585                     out.add(LastHttpContent.EMPTY_LAST_CONTENT);
586                     resetNow();
587                 }
588                 return;
589             case READ_HEADER:
590                 // If we are still in the state of reading headers we need to create a new invalid message that
591                 // signals that the connection was closed before we received the headers.
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: // fall-trough
597             case READ_CHUNK_FOOTER: // fall-trough
598             case READ_CHUNKED_CONTENT: // fall-trough
599             case READ_CHUNK_SIZE: // fall-trough
600             case READ_FIXED_LENGTH_CONTENT:
601                 // Check if the closure of the connection signifies the end of the content.
602                 boolean prematureClosure;
603                 if (isDecodingRequest() || chunked) {
604                     // The last request did not wait for a response.
605                     prematureClosure = true;
606                 } else {
607                     // Compare the length of the received content and the 'Content-Length' header.
608                     // If the 'Content-Length' header is absent, the length of the content is determined by the end of
609                     // the connection, so it is perfectly fine.
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: // fall-trough
618             case SKIP_INITIAL_LINE_CHARS: // fall-trough
619             case READ_INITIAL:// fall-trough
620             case BAD_MESSAGE: // fall-trough
621             case UPGRADED: // fall-trough
622                 // Do nothing
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             // Correctly handle return codes of 1xx.
660             //
661             // See:
662             //     - https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html Section 4.4
663             //     - https://github.com/netty/netty/issues/222
664             if (statusClass == HttpStatusClass.INFORMATIONAL) {
665                 // One exception: Hixie 76 websocket handshake response
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      * Returns true if the server switched to a different protocol than HTTP/1.0 or HTTP/1.1, e.g. HTTP/2 or Websocket.
682      * Returns false if the upgrade happened in a different layer, e.g. upgrade from HTTP/1.1 to HTTP/1.1 over TLS.
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      * Resets the state of the decoder so that it is ready to decode a new message.
696      * This method is useful for handling a rejected request with {@code Expect: 100-continue} header.
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         // Advance the readerIndex so that ByteToMessageDecoder does not complain
727         // when we produced an invalid message without consuming anything.
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         // Advance the readerIndex so that ByteToMessageDecoder does not complain
754         // when we produced an invalid message without consuming anything.
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                 //please do not make one line from below code
779                 //as it breaks +XX:OptimizeStringConcat optimization
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         // Add the last header.
798         if (name != null) {
799             headers.add(name, value);
800         }
801 
802         // reset name and value fields
803         name = null;
804         value = null;
805 
806         // Done parsing initial line and headers. Set decoder result.
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             // Guard against multiple Content-Length headers as stated in
816             // https://tools.ietf.org/html/rfc7230#section-3.3.2:
817             contentLength = HttpUtil.normalizeAndGetContentLength(contentLengthFields,
818                     isHttp10OrEarlier, allowDuplicateContentLengths);
819             if (contentLength != -1) {
820                 String lengthValue = contentLengthFields.get(0).trim();
821                 if (contentLengthFields.size() > 1 || // don't unnecessarily re-order headers
822                         !isLengthEqual(lengthValue, contentLength)) {
823                     headers.set(HttpHeaderNames.CONTENT_LENGTH, contentLength);
824                 }
825             }
826         } else {
827             // We know the content length if it's a Web Socket message even if
828             // Content-Length header is missing.
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             // The Transfer-Encoding header is not permitted at all with HTTP protocols older than 1.1,
844             // and such requests must be rejected.
845             throw TRANSFER_ENCODING_NOT_ALLOWED;
846         }
847         boolean isTransferEncodingChunked = HttpUtil.isTransferEncodingChunked(message);
848         // Unlike responses, requests without a final chunked coding cannot use connection close for framing.
849         // See https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-4
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             // The "chunked must be the last encoding" rule (RFC 9112 6.1) is not specific to
856             // HTTP/1.1 -- it applies to any message that carries a Transfer-Encoding header at
857             // all. This validation must not be gated on protocolVersion(), since a decoder
858             // configured with useRfc9112TransferEncoding(false) (see HttpDecoderConfig) can
859             // still reach this point for HTTP/1.0 and other non-1.1 messages, and the ordering
860             // requirement applies to those just as much as it does to HTTP/1.1.
861             // See https://datatracker.ietf.org/doc/html/rfc9112#name-message-body-length
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      * Invoked when a message with both a "Transfer-Encoding: chunked" and a "Content-Length" header field is detected.
925      * The default behavior is to throw a {@link ContentLengthNotAllowedException} exception, but this method could
926      * be overridden to change the behavior (to, e.g., remove the {@code Content-Length} header value.
927      * <p>
928      * See: <a href="https://www.rfc-editor.org/rfc/rfc9112.html#section-6.1-15">RFC 9112, Section 6.1-15</a>.
929      * <pre>
930      *     A server MAY reject a request that contains both Content-Length and Transfer-Encoding
931      *     or process such a request in accordance with the Transfer-Encoding alone.
932      *     Regardless, the server MUST close the connection after responding to such a request
933      *     to avoid the potential attacks.
934      * </pre>
935      * Since Netty itself cannot track the request/response pairing, it cannot guarantee that the connection is closed
936      * immediately after the response is sent. As such, it is safer to immediately reject the request.
937      * <p>
938      * <strong>Note:</strong> RFC 7230 (the previous HTTP/1.1 RFC) allowed the {@code Content-Length} header to simply
939      * be ignored, in the presence of a {@code Transfer-Encoding} header, but this practice is now obsolete
940      * and considered unsafe.
941      * The RFC 7230 behavior can be restored in the following ways:
942      * <ul>
943      *     <li>
944      *         Process-wide, by setting the {@value PROP_RFC9112_TRANSFER_ENCODING} system property to {@code false}.
945      *     </li>
946      *     <li>
947      *         Configured for a specific decoder, by setting
948      *         {@link HttpDecoderConfig#setUseRfc9112TransferEncoding(boolean)} to {@code false}.
949      *     </li>
950      *     <li>
951      *         Hard-coded for a specific decoder, by overriding this method with an implementation like the following:
952      *         <pre>{@code
953      * @Override
954      * protected void handleTransferEncodingChunkedWithContentLength(HttpMessage message) {
955      *     clearContentLength();
956      *     message.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
957      * }
958      *         }</pre>
959      *     </li>
960      * </ul>
961      * <p>
962      * <strong>Note:</strong> This method is only called for {@code HTTP/1.1} requests. Under the
963      * default configuration, earlier HTTP protocol versions carrying a {@code Transfer-Encoding}
964      * header are rejected before reaching this point. However, if
965      * {@link HttpDecoderConfig#setUseRfc9112TransferEncoding(boolean)} is set to {@code false}
966      * (see above), that rejection does not happen — a non-{@code HTTP/1.1} message can then
967      * legitimately carry {@code Transfer-Encoding} without being rejected for it, though this
968      * method specifically remains {@code HTTP/1.1}-only and is not invoked for such messages.
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             // We have received the empty line which signals the trailer is complete and did not parse any trailers
998             // before. Just return an empty last content to reduce allocations.
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                 //please do not make one line from below code
1011                 //as it breaks +XX:OptimizeStringConcat optimization
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         // Add the last trailer
1030         if (name != null && isPermittedTrailingHeader(name)) {
1031             trailer.trailingHeaders().add(name, value);
1032         }
1033 
1034         // reset name and value fields
1035         name = null;
1036         value = null;
1037 
1038         this.trailer = null;
1039         return trailer;
1040     }
1041 
1042     /**
1043      * Checks whether the given trailer field name is permitted per RFC 9110 section 6.5
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) { // Empty case - not allowed
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                 // Uncommon path:
1064                 // We must either hit the chunk header line (implicit CRLF from the header line parser),
1065                 // or a ';' character for chunk-extensions, or the "bad whitespace" allowed to precede ';'.
1066                 byte b = hex[start + i];
1067                 int j = 0;
1068                 while (b == HttpConstants.SP || b == HttpConstants.HT) { // Skip BWS
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) { // Empty case - not allowed
1077                         throw new NumberFormatException("Empty chunk size");
1078                     }
1079                     return (int) result;
1080                 }
1081                 // non-hex char fail-fast path
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                 // There should no extra control or whitespace char in case of a request.
1106                 // In case of a response there might be a SP if there is no reason-phrase given.
1107                 // See
1108                 //  - https://datatracker.ietf.org/doc/html/rfc2616#section-5.1
1109                 //  - https://datatracker.ietf.org/doc/html/rfc9112#name-status-line
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      * This method shouldn't exist: look at https://bugs.openjdk.org/browse/JDK-8295496 for more context
1144      */
1145     private static String langAsciiString(final byte[] asciiContent, int start, int length) {
1146         if (length == 0) {
1147             return StringUtil.EMPTY_STRING;
1148         }
1149         // DON'T REMOVE: it helps JIT to use a simpler intrinsic stub for System::arrayCopy based on the call-site
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         // hoist this load out of the loop, because it won't change!
1164         final boolean isDecodingRequest = isDecodingRequest();
1165         for (nameEnd = nameStart; nameEnd < end; nameEnd ++) {
1166             byte ch = line[nameEnd];
1167             // https://tools.ietf.org/html/rfc7230#section-3.2.4
1168             //
1169             // No whitespace is allowed between the header field-name and colon. In
1170             // the past, differences in the handling of such whitespace have led to
1171             // security vulnerabilities in request routing and response handling. A
1172             // server MUST reject any received request message that contains
1173             // whitespace between a header field-name and colon with a response code
1174             // of 400 (Bad Request). A proxy MUST remove any such whitespace from a
1175             // response message before forwarding the message downstream.
1176             if (ch == ':' ||
1177                     // In case of decoding a request we will just continue processing and header validation
1178                     // is done in the DefaultHttpHeaders implementation.
1179                     //
1180                     // In the case of decoding a response we will "skip" the whitespace.
1181                     (!isDecodingRequest && isOWS(ch))) {
1182                 break;
1183             }
1184         }
1185 
1186         if (nameEnd == end) {
1187             // There was no colon present at all.
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             // no need to make uses of the ByteBuf's toString ASCII method here, and risk to get JIT confused
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             // See https://tools.ietf.org/html/rfc7230#section-3.5
1216             if (isSPLenient(c)) {
1217                 continue;
1218             }
1219             if (isWhitespace(c)) {
1220                 // Any other whitespace delimiter is invalid
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         // See https://tools.ietf.org/html/rfc7230#section-3.5
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         // TO SAVE PERFORMING Character::isWhitespace ceremony
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         // See https://tools.ietf.org/html/rfc7230#section-3.5
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                 // Only OWS is supported for whitespace
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             // adding 2 to account for both CR (if present) and LF
1307             // don't remove 2L: it's key to cover maxLength = Integer.MAX_VALUE
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                     // TODO: Respond with Bad Request and discard the traffic
1316                     //    or close the connection.
1317                     //       No need to notify the upstream handlers - just log.
1318                     //       If decoding a response, just throw an exception.
1319                     throw newException(maxLength);
1320                 }
1321                 return null;
1322             }
1323             final int endOfSeqIncluded;
1324             if (indexOfLf > readerIndex && buffer.getByte(indexOfLf - 1) == HttpConstants.CR) {
1325                 // Drop CR if we had a CRLF pair
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             // Suppress a warning because HeaderParser.reset() is supposed to be called
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             // from now on we don't care about control chars
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 }