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 
178     private final int maxChunkSize;
179     private final boolean chunkedSupported;
180     private final boolean allowPartialChunks;
181     /**
182      * This field is no longer used. It is only kept around for backwards compatibility purpose.
183      */
184     @Deprecated
185     protected final boolean validateHeaders;
186     protected final HttpHeadersFactory headersFactory;
187     protected final HttpHeadersFactory trailersFactory;
188     private final boolean allowDuplicateContentLengths;
189     private final boolean useRfc9112TransferEncoding;
190     private final ByteBuf parserScratchBuffer;
191     private final Runnable defaultStrictCRLFCheck;
192     private final HeaderParser headerParser;
193     private final LineParser lineParser;
194 
195     private HttpMessage message;
196     private long chunkSize;
197     private long contentLength = Long.MIN_VALUE;
198     private boolean chunked;
199     private boolean isSwitchingToNonHttp1Protocol;
200 
201     private final AtomicBoolean resetRequested = new AtomicBoolean();
202 
203     // These will be updated by splitHeader(...)
204     private AsciiString name;
205     private String value;
206     private LastHttpContent trailer;
207 
208     @Override
209     protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
210         try {
211             parserScratchBuffer.release();
212         } finally {
213             super.handlerRemoved0(ctx);
214         }
215     }
216 
217     /**
218      * The internal state of {@link HttpObjectDecoder}.
219      * <em>Internal use only</em>.
220      */
221     private enum State {
222         SKIP_INITIAL_LINE_CHARS,
223         SKIP_CONTROL_CHARS,
224         READ_INITIAL,
225         READ_HEADER,
226         READ_VARIABLE_LENGTH_CONTENT,
227         READ_FIXED_LENGTH_CONTENT,
228         READ_CHUNK_SIZE,
229         READ_CHUNKED_CONTENT,
230         READ_CHUNK_DELIMITER,
231         READ_CHUNK_FOOTER,
232         BAD_MESSAGE,
233         UPGRADED
234     }
235 
236     private State currentState = State.SKIP_INITIAL_LINE_CHARS;
237 
238     /**
239      * Creates a new instance with the default
240      * {@code maxInitialLineLength (4096)}, {@code maxHeaderSize (8192)}, and
241      * {@code maxChunkSize (8192)}.
242      */
243     protected HttpObjectDecoder() {
244         this(new HttpDecoderConfig());
245     }
246 
247     /**
248      * Creates a new instance with the specified parameters.
249      *
250      * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead.
251      */
252     @Deprecated
253     protected HttpObjectDecoder(
254             int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean chunkedSupported) {
255         this(new HttpDecoderConfig()
256                 .setMaxInitialLineLength(maxInitialLineLength)
257                 .setMaxHeaderSize(maxHeaderSize)
258                 .setMaxChunkSize(maxChunkSize)
259                 .setChunkedSupported(chunkedSupported));
260     }
261 
262     /**
263      * Creates a new instance with the specified parameters.
264      *
265      * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead.
266      */
267     @Deprecated
268     protected HttpObjectDecoder(
269             int maxInitialLineLength, int maxHeaderSize, int maxChunkSize,
270             boolean chunkedSupported, boolean validateHeaders) {
271         this(new HttpDecoderConfig()
272                 .setMaxInitialLineLength(maxInitialLineLength)
273                 .setMaxHeaderSize(maxHeaderSize)
274                 .setMaxChunkSize(maxChunkSize)
275                 .setChunkedSupported(chunkedSupported)
276                 .setValidateHeaders(validateHeaders));
277     }
278 
279     /**
280      * Creates a new instance with the specified parameters.
281      *
282      * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead.
283      */
284     @Deprecated
285     protected HttpObjectDecoder(
286             int maxInitialLineLength, int maxHeaderSize, int maxChunkSize,
287             boolean chunkedSupported, boolean validateHeaders, int initialBufferSize) {
288         this(new HttpDecoderConfig()
289                 .setMaxInitialLineLength(maxInitialLineLength)
290                 .setMaxHeaderSize(maxHeaderSize)
291                 .setMaxChunkSize(maxChunkSize)
292                 .setChunkedSupported(chunkedSupported)
293                 .setValidateHeaders(validateHeaders)
294                 .setInitialBufferSize(initialBufferSize));
295     }
296 
297     /**
298      * Creates a new instance with the specified parameters.
299      *
300      * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead.
301      */
302     @Deprecated
303     protected HttpObjectDecoder(
304             int maxInitialLineLength, int maxHeaderSize, int maxChunkSize,
305             boolean chunkedSupported, boolean validateHeaders, int initialBufferSize,
306             boolean allowDuplicateContentLengths) {
307         this(new HttpDecoderConfig()
308                 .setMaxInitialLineLength(maxInitialLineLength)
309                 .setMaxHeaderSize(maxHeaderSize)
310                 .setMaxChunkSize(maxChunkSize)
311                 .setChunkedSupported(chunkedSupported)
312                 .setValidateHeaders(validateHeaders)
313                 .setInitialBufferSize(initialBufferSize)
314                 .setAllowDuplicateContentLengths(allowDuplicateContentLengths));
315     }
316 
317     /**
318      * Creates a new instance with the specified parameters.
319      *
320      * @deprecated Use {@link #HttpObjectDecoder(HttpDecoderConfig)} instead.
321      */
322     @Deprecated
323     protected HttpObjectDecoder(
324             int maxInitialLineLength, int maxHeaderSize, int maxChunkSize,
325             boolean chunkedSupported, boolean validateHeaders, int initialBufferSize,
326             boolean allowDuplicateContentLengths, boolean allowPartialChunks) {
327         this(new HttpDecoderConfig()
328                 .setMaxInitialLineLength(maxInitialLineLength)
329                 .setMaxHeaderSize(maxHeaderSize)
330                 .setMaxChunkSize(maxChunkSize)
331                 .setChunkedSupported(chunkedSupported)
332                 .setValidateHeaders(validateHeaders)
333                 .setInitialBufferSize(initialBufferSize)
334                 .setAllowDuplicateContentLengths(allowDuplicateContentLengths)
335                 .setAllowPartialChunks(allowPartialChunks));
336     }
337 
338     /**
339      * Creates a new instance with the specified configuration.
340      */
341     protected HttpObjectDecoder(HttpDecoderConfig config) {
342         checkNotNull(config, "config");
343 
344         parserScratchBuffer = Unpooled.buffer(config.getInitialBufferSize());
345         defaultStrictCRLFCheck = config.isStrictLineParsing() ? THROW_INVALID_LINE_SEPARATOR : null;
346         lineParser = new LineParser(parserScratchBuffer, config.getMaxInitialLineLength());
347         headerParser = new HeaderParser(parserScratchBuffer, config.getMaxHeaderSize());
348         maxChunkSize = config.getMaxChunkSize();
349         chunkedSupported = config.isChunkedSupported();
350         headersFactory = config.getHeadersFactory();
351         trailersFactory = config.getTrailersFactory();
352         validateHeaders = isValidating(headersFactory);
353         allowDuplicateContentLengths = config.isAllowDuplicateContentLengths();
354         allowPartialChunks = config.isAllowPartialChunks();
355         useRfc9112TransferEncoding = config.isUseRfc9112TransferEncoding();
356     }
357 
358     protected boolean isValidating(HttpHeadersFactory headersFactory) {
359         if (headersFactory instanceof DefaultHttpHeadersFactory) {
360             DefaultHttpHeadersFactory builder = (DefaultHttpHeadersFactory) headersFactory;
361             return builder.isValidatingHeaderNames() || builder.isValidatingHeaderValues();
362         }
363         return true; // We can't actually tell in this case, but we assume some validation is taking place.
364     }
365 
366     @Override
367     protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
368         if (resetRequested.get()) {
369             resetNow();
370         }
371 
372         switch (currentState) {
373         case SKIP_INITIAL_LINE_CHARS:
374             // Fall-through
375         case READ_INITIAL: try {
376             ByteBuf line = lineParser.parse(buffer, defaultStrictCRLFCheck);
377             if (line == null) {
378                 return;
379             }
380             final String[] initialLine = splitInitialLine(line);
381             assert initialLine.length == 3 : "initialLine::length must be 3";
382 
383             message = createMessage(initialLine);
384             currentState = State.READ_HEADER;
385             // fall-through
386         } catch (Exception e) {
387             out.add(invalidMessage(message, buffer, e));
388             return;
389         }
390         case READ_HEADER: try {
391             State nextState = readHeaders(buffer);
392             if (nextState == null) {
393                 return;
394             }
395             currentState = nextState;
396             switch (nextState) {
397             case SKIP_CONTROL_CHARS:
398                 // fast-path
399                 // No content is expected.
400                 addCurrentMessage(out);
401                 out.add(LastHttpContent.EMPTY_LAST_CONTENT);
402                 resetNow();
403                 return;
404             case READ_CHUNK_SIZE:
405                 if (!chunkedSupported) {
406                     throw new IllegalArgumentException("Chunked messages not supported");
407                 }
408                 // Chunked encoding - generate HttpMessage first.  HttpChunks will follow.
409                 addCurrentMessage(out);
410                 return;
411             default:
412                 /*
413                  * RFC 7230, 3.3.3 (https://tools.ietf.org/html/rfc7230#section-3.3.3) states that if a
414                  * request does not have either a transfer-encoding or a content-length header then the message body
415                  * length is 0. However, for a response the body length is the number of octets received prior to the
416                  * server closing the connection. So we treat this as variable length chunked encoding.
417                  */
418                 if (contentLength == 0 || contentLength == -1 && isDecodingRequest()) {
419                     addCurrentMessage(out);
420                     out.add(LastHttpContent.EMPTY_LAST_CONTENT);
421                     resetNow();
422                     return;
423                 }
424 
425                 assert nextState == State.READ_FIXED_LENGTH_CONTENT ||
426                         nextState == State.READ_VARIABLE_LENGTH_CONTENT;
427 
428                 addCurrentMessage(out);
429 
430                 if (nextState == State.READ_FIXED_LENGTH_CONTENT) {
431                     // chunkSize will be decreased as the READ_FIXED_LENGTH_CONTENT state reads data chunk by chunk.
432                     chunkSize = contentLength;
433                 }
434 
435                 // We return here, this forces decode to be called again where we will decode the content
436                 return;
437             }
438         } catch (Exception e) {
439             out.add(invalidMessage(message, buffer, e));
440             return;
441         }
442         case READ_VARIABLE_LENGTH_CONTENT: {
443             // Keep reading data as a chunk until the end of connection is reached.
444             int toRead = Math.min(buffer.readableBytes(), maxChunkSize);
445             if (toRead > 0) {
446                 ByteBuf content = buffer.readRetainedSlice(toRead);
447                 out.add(new DefaultHttpContent(content));
448             }
449             return;
450         }
451         case READ_FIXED_LENGTH_CONTENT: {
452             int readLimit = buffer.readableBytes();
453 
454             // Check if the buffer is readable first as we use the readable byte count
455             // to create the HttpChunk. This is needed as otherwise we may end up with
456             // create an HttpChunk instance that contains an empty buffer and so is
457             // handled like it is the last HttpChunk.
458             //
459             // See https://github.com/netty/netty/issues/433
460             if (readLimit == 0) {
461                 return;
462             }
463 
464             int toRead = Math.min(readLimit, maxChunkSize);
465             if (toRead > chunkSize) {
466                 toRead = (int) chunkSize;
467             }
468             ByteBuf content = buffer.readRetainedSlice(toRead);
469             chunkSize -= toRead;
470 
471             if (chunkSize == 0) {
472                 // Read all content.
473                 out.add(new DefaultLastHttpContent(content, trailersFactory));
474                 resetNow();
475             } else {
476                 out.add(new DefaultHttpContent(content));
477             }
478             return;
479         }
480         /*
481          * Everything else after this point takes care of reading chunked content. Basically, read chunk size,
482          * read chunk, read and ignore the CRLF and repeat until 0
483          */
484         case READ_CHUNK_SIZE: try {
485             ByteBuf line = lineParser.parse(buffer, THROW_INVALID_CHUNK_EXTENSION);
486             if (line == null) {
487                 return;
488             }
489             checkChunkExtensions(line);
490             int chunkSize = getChunkSize(line.array(), line.arrayOffset() + line.readerIndex(), line.readableBytes());
491             this.chunkSize = chunkSize;
492             if (chunkSize == 0) {
493                 currentState = State.READ_CHUNK_FOOTER;
494                 return;
495             }
496             currentState = State.READ_CHUNKED_CONTENT;
497             // fall-through
498         } catch (Exception e) {
499             out.add(invalidChunk(buffer, e));
500             return;
501         }
502         case READ_CHUNKED_CONTENT: {
503             assert chunkSize <= Integer.MAX_VALUE;
504             int toRead = Math.min((int) chunkSize, maxChunkSize);
505             if (!allowPartialChunks && buffer.readableBytes() < toRead) {
506                 return;
507             }
508             toRead = Math.min(toRead, buffer.readableBytes());
509             if (toRead == 0) {
510                 return;
511             }
512             HttpContent chunk = new DefaultHttpContent(buffer.readRetainedSlice(toRead));
513             chunkSize -= toRead;
514 
515             out.add(chunk);
516 
517             if (chunkSize != 0) {
518                 return;
519             }
520             currentState = State.READ_CHUNK_DELIMITER;
521             // fall-through
522         }
523         case READ_CHUNK_DELIMITER: {
524             if (buffer.readableBytes() >= 2) {
525                 int rIdx = buffer.readerIndex();
526                 if (buffer.getByte(rIdx) == HttpConstants.CR &&
527                         buffer.getByte(rIdx + 1) == HttpConstants.LF) {
528                     buffer.skipBytes(2);
529                     currentState = State.READ_CHUNK_SIZE;
530                 } else {
531                     out.add(invalidChunk(buffer, new InvalidChunkTerminationException()));
532                 }
533             }
534             return;
535         }
536         case READ_CHUNK_FOOTER: try {
537             LastHttpContent trailer = readTrailingHeaders(buffer);
538             if (trailer == null) {
539                 return;
540             }
541             out.add(trailer);
542             resetNow();
543             return;
544         } catch (Exception e) {
545             out.add(invalidChunk(buffer, e));
546             return;
547         }
548         case BAD_MESSAGE: {
549             // Keep discarding until disconnection.
550             buffer.skipBytes(buffer.readableBytes());
551             break;
552         }
553         case UPGRADED: {
554             int readableBytes = buffer.readableBytes();
555             if (readableBytes > 0) {
556                 // Keep on consuming as otherwise we may trigger an DecoderException,
557                 // other handler will replace this codec with the upgraded protocol codec to
558                 // take the traffic over at some point then.
559                 // See https://github.com/netty/netty/issues/2173
560                 out.add(buffer.readBytes(readableBytes));
561             }
562             break;
563         }
564         default:
565             break;
566         }
567     }
568 
569     @Override
570     protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
571         super.decodeLast(ctx, in, out);
572 
573         if (resetRequested.get()) {
574             // If a reset was requested by decodeLast() we need to do it now otherwise we may produce a
575             // LastHttpContent while there was already one.
576             resetNow();
577         }
578 
579         // Handle the last unfinished message.
580         switch (currentState) {
581             case READ_VARIABLE_LENGTH_CONTENT:
582                 if (!chunked && !in.isReadable()) {
583                     // End of connection.
584                     out.add(LastHttpContent.EMPTY_LAST_CONTENT);
585                     resetNow();
586                 }
587                 return;
588             case READ_HEADER:
589                 // If we are still in the state of reading headers we need to create a new invalid message that
590                 // signals that the connection was closed before we received the headers.
591                 out.add(invalidMessage(message, Unpooled.EMPTY_BUFFER,
592                         new PrematureChannelClosureException("Connection closed before received headers")));
593                 resetNow();
594                 return;
595             case READ_CHUNK_DELIMITER: // fall-trough
596             case READ_CHUNK_FOOTER: // fall-trough
597             case READ_CHUNKED_CONTENT: // fall-trough
598             case READ_CHUNK_SIZE: // fall-trough
599             case READ_FIXED_LENGTH_CONTENT:
600                 // Check if the closure of the connection signifies the end of the content.
601                 boolean prematureClosure;
602                 if (isDecodingRequest() || chunked) {
603                     // The last request did not wait for a response.
604                     prematureClosure = true;
605                 } else {
606                     // Compare the length of the received content and the 'Content-Length' header.
607                     // If the 'Content-Length' header is absent, the length of the content is determined by the end of
608                     // the connection, so it is perfectly fine.
609                     prematureClosure = contentLength > 0;
610                 }
611                 if (!prematureClosure) {
612                     out.add(LastHttpContent.EMPTY_LAST_CONTENT);
613                 }
614                 resetNow();
615                 return;
616             case SKIP_CONTROL_CHARS: // fall-trough
617             case SKIP_INITIAL_LINE_CHARS: // fall-trough
618             case READ_INITIAL:// fall-trough
619             case BAD_MESSAGE: // fall-trough
620             case UPGRADED: // fall-trough
621                 // Do nothing
622                 break;
623             default:
624                 throw new IllegalStateException("Unhandled state " + currentState);
625         }
626     }
627 
628     @Override
629     public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
630         if (evt instanceof HttpExpectationFailedEvent) {
631             switch (currentState) {
632             case READ_FIXED_LENGTH_CONTENT:
633             case READ_VARIABLE_LENGTH_CONTENT:
634             case READ_CHUNK_SIZE:
635                 reset();
636                 break;
637             default:
638                 break;
639             }
640         }
641         super.userEventTriggered(ctx, evt);
642     }
643 
644     private void addCurrentMessage(List<Object> out) {
645         HttpMessage message = this.message;
646         assert message != null;
647         this.message = null;
648         out.add(message);
649     }
650 
651     protected boolean isContentAlwaysEmpty(HttpMessage msg) {
652         if (msg instanceof HttpResponse) {
653             HttpResponse res = (HttpResponse) msg;
654             final HttpResponseStatus status = res.status();
655             final int code = status.code();
656             final HttpStatusClass statusClass = status.codeClass();
657 
658             // Correctly handle return codes of 1xx.
659             //
660             // See:
661             //     - https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html Section 4.4
662             //     - https://github.com/netty/netty/issues/222
663             if (statusClass == HttpStatusClass.INFORMATIONAL) {
664                 // One exception: Hixie 76 websocket handshake response
665                 return !(code == 101 && !res.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT)
666                          && res.headers().contains(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET, true));
667             }
668 
669             switch (code) {
670             case 204: case 304:
671                 return true;
672             default:
673                 return false;
674             }
675         }
676         return false;
677     }
678 
679     /**
680      * Returns true if the server switched to a different protocol than HTTP/1.0 or HTTP/1.1, e.g. HTTP/2 or Websocket.
681      * Returns false if the upgrade happened in a different layer, e.g. upgrade from HTTP/1.1 to HTTP/1.1 over TLS.
682      */
683     protected boolean isSwitchingToNonHttp1Protocol(HttpResponse msg) {
684         if (msg.status().code() != HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
685             return false;
686         }
687         String newProtocol = msg.headers().get(HttpHeaderNames.UPGRADE);
688         return newProtocol == null ||
689                 !newProtocol.contains(HttpVersion.HTTP_1_0.text()) &&
690                 !newProtocol.contains(HttpVersion.HTTP_1_1.text());
691     }
692 
693     /**
694      * Resets the state of the decoder so that it is ready to decode a new message.
695      * This method is useful for handling a rejected request with {@code Expect: 100-continue} header.
696      */
697     public void reset() {
698         resetRequested.lazySet(true);
699     }
700 
701     private void resetNow() {
702         message = null;
703         name = null;
704         value = null;
705         clearContentLength();
706         chunked = false;
707         lineParser.reset();
708         headerParser.reset();
709         trailer = null;
710         if (isSwitchingToNonHttp1Protocol) {
711             isSwitchingToNonHttp1Protocol = false;
712             currentState = State.UPGRADED;
713             return;
714         }
715 
716         resetRequested.lazySet(false);
717         currentState = State.SKIP_INITIAL_LINE_CHARS;
718     }
719 
720     private HttpMessage invalidMessage(HttpMessage current, ByteBuf in, Exception cause) {
721         currentState = State.BAD_MESSAGE;
722         message = null;
723         trailer = null;
724 
725         // Advance the readerIndex so that ByteToMessageDecoder does not complain
726         // when we produced an invalid message without consuming anything.
727         in.skipBytes(in.readableBytes());
728 
729         if (current == null) {
730             current = createInvalidMessage();
731         }
732         current.setDecoderResult(DecoderResult.failure(cause));
733 
734         return current;
735     }
736 
737     private static void checkChunkExtensions(ByteBuf line) {
738         int extensionsStart = line.bytesBefore((byte) ';');
739         if (extensionsStart == -1) {
740             return;
741         }
742         HttpChunkLineValidatingByteProcessor processor = new HttpChunkLineValidatingByteProcessor();
743         line.forEachByte(processor);
744         processor.finish();
745     }
746 
747     private HttpContent invalidChunk(ByteBuf in, Exception cause) {
748         currentState = State.BAD_MESSAGE;
749         message = null;
750         trailer = null;
751 
752         // Advance the readerIndex so that ByteToMessageDecoder does not complain
753         // when we produced an invalid message without consuming anything.
754         in.skipBytes(in.readableBytes());
755 
756         HttpContent chunk = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER);
757         chunk.setDecoderResult(DecoderResult.failure(cause));
758         return chunk;
759     }
760 
761     private State readHeaders(ByteBuf buffer) {
762         final HttpMessage message = this.message;
763         final HttpHeaders headers = message.headers();
764 
765         final HeaderParser headerParser = this.headerParser;
766 
767         ByteBuf line = headerParser.parse(buffer, defaultStrictCRLFCheck);
768         if (line == null) {
769             return null;
770         }
771         int lineLength = line.readableBytes();
772         while (lineLength > 0) {
773             final byte[] lineContent = line.array();
774             final int startLine = line.arrayOffset() + line.readerIndex();
775             final byte firstChar = lineContent[startLine];
776             if (name != null && (firstChar == ' ' || firstChar == '\t')) {
777                 //please do not make one line from below code
778                 //as it breaks +XX:OptimizeStringConcat optimization
779                 String trimmedLine = langAsciiString(lineContent, startLine, lineLength).trim();
780                 String valueStr = value;
781                 value = valueStr + ' ' + trimmedLine;
782             } else {
783                 if (name != null) {
784                     headers.add(name, value);
785                 }
786                 splitHeader(lineContent, startLine, lineLength);
787             }
788 
789             line = headerParser.parse(buffer, defaultStrictCRLFCheck);
790             if (line == null) {
791                 return null;
792             }
793             lineLength = line.readableBytes();
794         }
795 
796         // Add the last header.
797         if (name != null) {
798             headers.add(name, value);
799         }
800 
801         // reset name and value fields
802         name = null;
803         value = null;
804 
805         // Done parsing initial line and headers. Set decoder result.
806         HttpMessageDecoderResult decoderResult = new HttpMessageDecoderResult(lineParser.size, headerParser.size);
807         message.setDecoderResult(decoderResult);
808 
809         List<String> contentLengthFields = headers.getAll(HttpHeaderNames.CONTENT_LENGTH);
810         if (!contentLengthFields.isEmpty()) {
811             HttpVersion version = message.protocolVersion();
812             boolean isHttp10OrEarlier = version.majorVersion() < 1 || (version.majorVersion() == 1
813                     && version.minorVersion() == 0);
814             // Guard against multiple Content-Length headers as stated in
815             // https://tools.ietf.org/html/rfc7230#section-3.3.2:
816             contentLength = HttpUtil.normalizeAndGetContentLength(contentLengthFields,
817                     isHttp10OrEarlier, allowDuplicateContentLengths);
818             if (contentLength != -1) {
819                 String lengthValue = contentLengthFields.get(0).trim();
820                 if (contentLengthFields.size() > 1 || // don't unnecessarily re-order headers
821                         !isLengthEqual(lengthValue, contentLength)) {
822                     headers.set(HttpHeaderNames.CONTENT_LENGTH, contentLength);
823                 }
824             }
825         } else {
826             // We know the content length if it's a Web Socket message even if
827             // Content-Length header is missing.
828             contentLength = HttpUtil.getWebSocketContentLength(message);
829         }
830         if (!isDecodingRequest() && message instanceof HttpResponse) {
831             HttpResponse res = (HttpResponse) message;
832             this.isSwitchingToNonHttp1Protocol = isSwitchingToNonHttp1Protocol(res);
833         }
834         if (isContentAlwaysEmpty(message)) {
835             HttpUtil.setTransferEncodingChunked(message, false);
836             return State.SKIP_CONTROL_CHARS;
837         }
838         boolean hasTransferEncoding = message.headers().contains(HttpHeaderNames.TRANSFER_ENCODING);
839         if (hasTransferEncoding &&
840                 message.protocolVersion() != HttpVersion.HTTP_1_1 &&
841                 useRfc9112TransferEncoding) {
842             // The Transfer-Encoding header is not permitted at all with HTTP protocols older than 1.1,
843             // and such requests must be rejected.
844             throw TRANSFER_ENCODING_NOT_ALLOWED;
845         }
846         boolean isTransferEncodingChunked = HttpUtil.isTransferEncodingChunked(message);
847         // Unlike responses, requests without a final chunked coding cannot use connection close for framing.
848         // See https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-4
849         if (hasTransferEncoding && !isTransferEncodingChunked && isDecodingRequest()) {
850             throw new IllegalArgumentException("The final transfer coding must be chunked for HTTP requests");
851         }
852         if (isTransferEncodingChunked) {
853             this.chunked = true;
854             // The "chunked must be the last encoding" rule (RFC 9112 6.1) is not specific to
855             // HTTP/1.1 -- it applies to any message that carries a Transfer-Encoding header at
856             // all. This validation must not be gated on protocolVersion(), since a decoder
857             // configured with useRfc9112TransferEncoding(false) (see HttpDecoderConfig) can
858             // still reach this point for HTTP/1.0 and other non-1.1 messages, and the ordering
859             // requirement applies to those just as much as it does to HTTP/1.1.
860             // See https://datatracker.ietf.org/doc/html/rfc9112#name-message-body-length
861             if (!isLastTransferEncodingChunked(headers.getAll(HttpHeaderNames.TRANSFER_ENCODING))) {
862                 throw new IllegalArgumentException(
863                         "chunked must be the last encoding present in the Transfer-Encoding header");
864             }
865             if (message.protocolVersion() == HttpVersion.HTTP_1_1) {
866                 if (!contentLengthFields.isEmpty()) {
867                     handleTransferEncodingChunkedWithContentLength(message);
868                 }
869             }
870             return State.READ_CHUNK_SIZE;
871         }
872         if (contentLength >= 0) {
873             return State.READ_FIXED_LENGTH_CONTENT;
874         }
875         return State.READ_VARIABLE_LENGTH_CONTENT;
876     }
877 
878     private static boolean isLastTransferEncodingChunked(List<String> transferEncodingFields) {
879         boolean chunkedSeen = false;
880         boolean lastChunked = false;
881         int chunkedLength = HttpHeaderValues.CHUNKED.length();
882         for (int i = 0; i < transferEncodingFields.size(); ++i) {
883             String value = transferEncodingFields.get(i);
884             int start = 0;
885             while (start <= value.length()) {
886                 int comma = value.indexOf(',', start);
887                 int end = comma == -1 ? value.length() : comma;
888                 while (start < end && (value.charAt(start) == ' ' || value.charAt(start) == '\t')) {
889                     ++start;
890                 }
891                 while (end > start && (value.charAt(end - 1) == ' ' || value.charAt(end - 1) == '\t')) {
892                     --end;
893                 }
894                 if (start < end) {
895                     lastChunked = end - start == chunkedLength &&
896                             HttpHeaderValues.CHUNKED.regionMatches(true, 0, value, start, chunkedLength);
897                     if (lastChunked) {
898                         if (chunkedSeen) {
899                             throw new IllegalArgumentException(
900                                     "chunked transfer coding must not be applied more than once");
901                         }
902                         chunkedSeen = true;
903                     }
904                 }
905                 if (comma == -1) {
906                     break;
907                 }
908                 start = comma + 1;
909             }
910         }
911         return lastChunked;
912     }
913 
914     private static boolean isLengthEqual(String lengthValue, long contentLength) {
915         try {
916             return Long.parseLong(lengthValue) == contentLength;
917         } catch (NumberFormatException e) {
918             return false;
919         }
920     }
921 
922     /**
923      * Invoked when a message with both a "Transfer-Encoding: chunked" and a "Content-Length" header field is detected.
924      * The default behavior is to throw a {@link ContentLengthNotAllowedException} exception, but this method could
925      * be overridden to change the behavior (to, e.g., remove the {@code Content-Length} header value.
926      * <p>
927      * See: <a href="https://www.rfc-editor.org/rfc/rfc9112.html#section-6.1-15">RFC 9112, Section 6.1-15</a>.
928      * <pre>
929      *     A server MAY reject a request that contains both Content-Length and Transfer-Encoding
930      *     or process such a request in accordance with the Transfer-Encoding alone.
931      *     Regardless, the server MUST close the connection after responding to such a request
932      *     to avoid the potential attacks.
933      * </pre>
934      * Since Netty itself cannot track the request/response pairing, it cannot guarantee that the connection is closed
935      * immediately after the response is sent. As such, it is safer to immediately reject the request.
936      * <p>
937      * <strong>Note:</strong> RFC 7230 (the previous HTTP/1.1 RFC) allowed the {@code Content-Length} header to simply
938      * be ignored, in the presence of a {@code Transfer-Encoding} header, but this practice is now obsolete
939      * and considered unsafe.
940      * The RFC 7230 behavior can be restored in the following ways:
941      * <ul>
942      *     <li>
943      *         Process-wide, by setting the {@value PROP_RFC9112_TRANSFER_ENCODING} system property to {@code false}.
944      *     </li>
945      *     <li>
946      *         Configured for a specific decoder, by setting
947      *         {@link HttpDecoderConfig#setUseRfc9112TransferEncoding(boolean)} to {@code false}.
948      *     </li>
949      *     <li>
950      *         Hard-coded for a specific decoder, by overriding this method with an implementation like the following:
951      *         <pre>{@code
952      * @Override
953      * protected void handleTransferEncodingChunkedWithContentLength(HttpMessage message) {
954      *     clearContentLength();
955      *     message.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
956      * }
957      *         }</pre>
958      *     </li>
959      * </ul>
960      * <p>
961      * <strong>Note:</strong> This method is only called for {@code HTTP/1.1} requests. Under the
962      * default configuration, earlier HTTP protocol versions carrying a {@code Transfer-Encoding}
963      * header are rejected before reaching this point. However, if
964      * {@link HttpDecoderConfig#setUseRfc9112TransferEncoding(boolean)} is set to {@code false}
965      * (see above), that rejection does not happen — a non-{@code HTTP/1.1} message can then
966      * legitimately carry {@code Transfer-Encoding} without being rejected for it, though this
967      * method specifically remains {@code HTTP/1.1}-only and is not invoked for such messages.
968      */
969     @SuppressWarnings("unused")
970     protected void handleTransferEncodingChunkedWithContentLength(HttpMessage message) {
971         clearContentLength();
972         if (useRfc9112TransferEncoding) {
973             throw new ContentLengthNotAllowedException(
974                     "Content-Length are not allowed in HTTP/1.1 messages that contains a Transfer-Encoding header.");
975         } else {
976             message.headers().remove(HttpHeaderNames.CONTENT_LENGTH);
977             if (isDecodingRequest()) {
978                 HttpUtil.setKeepAlive(message, false);
979             }
980         }
981     }
982 
983     protected final void clearContentLength() {
984         contentLength = Long.MIN_VALUE;
985     }
986 
987     private LastHttpContent readTrailingHeaders(ByteBuf buffer) {
988         final HeaderParser headerParser = this.headerParser;
989         ByteBuf line = headerParser.parse(buffer, defaultStrictCRLFCheck);
990         if (line == null) {
991             return null;
992         }
993         LastHttpContent trailer = this.trailer;
994         int lineLength = line.readableBytes();
995         if (lineLength == 0 && trailer == null) {
996             // We have received the empty line which signals the trailer is complete and did not parse any trailers
997             // before. Just return an empty last content to reduce allocations.
998             return LastHttpContent.EMPTY_LAST_CONTENT;
999         }
1000 
1001         if (trailer == null) {
1002             trailer = this.trailer = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER, trailersFactory);
1003         }
1004         while (lineLength > 0) {
1005             final byte[] lineContent = line.array();
1006             final int startLine = line.arrayOffset() + line.readerIndex();
1007             final byte firstChar = lineContent[startLine];
1008             if (name != null && (firstChar == ' ' || firstChar == '\t')) {
1009                 //please do not make one line from below code
1010                 //as it breaks +XX:OptimizeStringConcat optimization
1011                 String trimmedLine = langAsciiString(lineContent, startLine, lineLength).trim();
1012                 String valueStr = value;
1013                 value = valueStr + ' ' + trimmedLine;
1014             } else {
1015                 if (name != null && isPermittedTrailingHeader(name)) {
1016                     trailer.trailingHeaders().add(name, value);
1017                 }
1018                 splitHeader(lineContent, startLine, lineLength);
1019             }
1020 
1021             line = headerParser.parse(buffer, defaultStrictCRLFCheck);
1022             if (line == null) {
1023                 return null;
1024             }
1025             lineLength = line.readableBytes();
1026         }
1027 
1028         // Add the last trailer
1029         if (name != null && isPermittedTrailingHeader(name)) {
1030             trailer.trailingHeaders().add(name, value);
1031         }
1032 
1033         // reset name and value fields
1034         name = null;
1035         value = null;
1036 
1037         this.trailer = null;
1038         return trailer;
1039     }
1040 
1041     /**
1042      * Checks whether the given trailer field name is permitted per RFC 9110 section 6.5
1043      */
1044     private static boolean isPermittedTrailingHeader(final AsciiString name) {
1045         return !HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(name) &&
1046                !HttpHeaderNames.TRANSFER_ENCODING.contentEqualsIgnoreCase(name) &&
1047                !HttpHeaderNames.TRAILER.contentEqualsIgnoreCase(name);
1048     }
1049 
1050     protected abstract boolean isDecodingRequest();
1051     protected abstract HttpMessage createMessage(String[] initialLine) throws Exception;
1052     protected abstract HttpMessage createInvalidMessage();
1053 
1054     private static int getChunkSize(byte[] hex, int start, int length) {
1055         if (length == 0) { // Empty case - not allowed
1056             throw new NumberFormatException("Empty chunk size");
1057         }
1058         long result = 0;
1059         for (int i = 0; i < length; i++) {
1060             final int digit = StringUtil.decodeHexNibble(hex[start + i]);
1061             if (digit == -1) {
1062                 // Uncommon path:
1063                 // We must either hit the chunk header line (implicit CRLF from the header line parser),
1064                 // or a ';' character for chunk-extensions, or the "bad whitespace" allowed to precede ';'.
1065                 byte b = hex[start + i];
1066                 int j = 0;
1067                 while (b == HttpConstants.SP || b == HttpConstants.HT) { // Skip BWS
1068                     int index = i + (++j);
1069                     if (index >= length) {
1070                         throw new NumberFormatException("Invalid chunk size; expected extensions");
1071                     }
1072                     b = hex[start + index];
1073                 }
1074                 if (b == ';') {
1075                     if (i == 0) { // Empty case - not allowed
1076                         throw new NumberFormatException("Empty chunk size");
1077                     }
1078                     return (int) result;
1079                 }
1080                 // non-hex char fail-fast path
1081                 throw new NumberFormatException("Invalid character in chunk size");
1082             }
1083             result *= 16;
1084             result += digit;
1085             if (result > Integer.MAX_VALUE) {
1086                 throw new NumberFormatException("Chunk size overflow: " + result);
1087             }
1088         }
1089         return (int) result;
1090     }
1091 
1092     private String[] splitInitialLine(ByteBuf asciiBuffer) {
1093         final byte[] asciiBytes = asciiBuffer.array();
1094 
1095         final int arrayOffset = asciiBuffer.arrayOffset();
1096 
1097         final int startContent = arrayOffset + asciiBuffer.readerIndex();
1098 
1099         final int end = startContent + asciiBuffer.readableBytes();
1100 
1101         byte lastByte = asciiBytes[end - 1];
1102         if (isControlOrWhitespaceAsciiChar(lastByte)) {
1103             if (isDecodingRequest() || !isOWS(lastByte)) {
1104                 // There should no extra control or whitespace char in case of a request.
1105                 // In case of a response there might be a SP if there is no reason-phrase given.
1106                 // See
1107                 //  - https://datatracker.ietf.org/doc/html/rfc2616#section-5.1
1108                 //  - https://datatracker.ietf.org/doc/html/rfc9112#name-status-line
1109                 throw new IllegalArgumentException(
1110                         "Illegal character in request line: 0x" + Integer.toHexString(lastByte));
1111             }
1112         }
1113 
1114         final int aStart = findNonSPLenient(asciiBytes, startContent, end);
1115         final int aEnd = findSPLenient(asciiBytes, aStart, end);
1116 
1117         final int bStart = findNonSPLenient(asciiBytes, aEnd, end);
1118         final int bEnd = findSPLenient(asciiBytes, bStart, end);
1119 
1120         final int cStart = findNonSPLenient(asciiBytes, bEnd, end);
1121         final int cEnd = findEndOfString(asciiBytes, Math.max(cStart - 1, startContent), end);
1122 
1123         return new String[]{
1124                 splitFirstWordInitialLine(asciiBytes, aStart, aEnd - aStart),
1125                 splitSecondWordInitialLine(asciiBytes, bStart, bEnd - bStart),
1126                 cStart < cEnd ? splitThirdWordInitialLine(asciiBytes, cStart, cEnd - cStart) : StringUtil.EMPTY_STRING};
1127     }
1128 
1129     protected String splitFirstWordInitialLine(final byte[] asciiContent, int start, int length) {
1130         return langAsciiString(asciiContent, start, length);
1131     }
1132 
1133     protected String splitSecondWordInitialLine(final byte[] asciiContent, int start, int length) {
1134         return langAsciiString(asciiContent, start, length);
1135     }
1136 
1137     protected String splitThirdWordInitialLine(final byte[] asciiContent, int start, int length) {
1138         return langAsciiString(asciiContent, start, length);
1139     }
1140 
1141     /**
1142      * This method shouldn't exist: look at https://bugs.openjdk.org/browse/JDK-8295496 for more context
1143      */
1144     private static String langAsciiString(final byte[] asciiContent, int start, int length) {
1145         if (length == 0) {
1146             return StringUtil.EMPTY_STRING;
1147         }
1148         // DON'T REMOVE: it helps JIT to use a simpler intrinsic stub for System::arrayCopy based on the call-site
1149         if (start == 0) {
1150             if (length == asciiContent.length) {
1151                 return new String(asciiContent, 0, 0, asciiContent.length);
1152             }
1153             return new String(asciiContent, 0, 0, length);
1154         }
1155         return new String(asciiContent, 0, start, length);
1156     }
1157 
1158     private void splitHeader(byte[] line, int start, int length) {
1159         final int end = start + length;
1160         int nameEnd;
1161         final int nameStart = start;
1162         // hoist this load out of the loop, because it won't change!
1163         final boolean isDecodingRequest = isDecodingRequest();
1164         for (nameEnd = nameStart; nameEnd < end; nameEnd ++) {
1165             byte ch = line[nameEnd];
1166             // https://tools.ietf.org/html/rfc7230#section-3.2.4
1167             //
1168             // No whitespace is allowed between the header field-name and colon. In
1169             // the past, differences in the handling of such whitespace have led to
1170             // security vulnerabilities in request routing and response handling. A
1171             // server MUST reject any received request message that contains
1172             // whitespace between a header field-name and colon with a response code
1173             // of 400 (Bad Request). A proxy MUST remove any such whitespace from a
1174             // response message before forwarding the message downstream.
1175             if (ch == ':' ||
1176                     // In case of decoding a request we will just continue processing and header validation
1177                     // is done in the DefaultHttpHeaders implementation.
1178                     //
1179                     // In the case of decoding a response we will "skip" the whitespace.
1180                     (!isDecodingRequest && isOWS(ch))) {
1181                 break;
1182             }
1183         }
1184 
1185         if (nameEnd == end) {
1186             // There was no colon present at all.
1187             throw new IllegalArgumentException("No colon found");
1188         }
1189         int colonEnd;
1190         for (colonEnd = nameEnd; colonEnd < end; colonEnd ++) {
1191             if (line[colonEnd] == ':') {
1192                 colonEnd ++;
1193                 break;
1194             }
1195         }
1196         name = splitHeaderName(line, nameStart, nameEnd - nameStart);
1197         final int valueStart = findNonWhitespace(line, colonEnd, end);
1198         if (valueStart == end) {
1199             value = StringUtil.EMPTY_STRING;
1200         } else {
1201             final int valueEnd = findEndOfString(line, start, end);
1202             // no need to make uses of the ByteBuf's toString ASCII method here, and risk to get JIT confused
1203             value = langAsciiString(line, valueStart, valueEnd - valueStart);
1204         }
1205     }
1206 
1207     protected AsciiString splitHeaderName(byte[] sb, int start, int length) {
1208         return new AsciiString(sb, start, length, true);
1209     }
1210 
1211     private static int findNonSPLenient(byte[] sb, int offset, int end) {
1212         for (int result = offset; result < end; ++result) {
1213             byte c = sb[result];
1214             // See https://tools.ietf.org/html/rfc7230#section-3.5
1215             if (isSPLenient(c)) {
1216                 continue;
1217             }
1218             if (isWhitespace(c)) {
1219                 // Any other whitespace delimiter is invalid
1220                 throw new IllegalArgumentException("Invalid separator");
1221             }
1222             return result;
1223         }
1224         return end;
1225     }
1226 
1227     private static int findSPLenient(byte[] sb, int offset, int end) {
1228         for (int result = offset; result < end; ++result) {
1229             if (isSPLenient(sb[result])) {
1230                 return result;
1231             }
1232         }
1233         return end;
1234     }
1235 
1236     private static final boolean[] SP_LENIENT_BYTES;
1237     private static final boolean[] LATIN_WHITESPACE;
1238 
1239     static {
1240         // See https://tools.ietf.org/html/rfc7230#section-3.5
1241         SP_LENIENT_BYTES = new boolean[256];
1242         SP_LENIENT_BYTES[128 + ' '] = true;
1243         SP_LENIENT_BYTES[128 + 0x09] = true;
1244         SP_LENIENT_BYTES[128 + 0x0B] = true;
1245         SP_LENIENT_BYTES[128 + 0x0C] = true;
1246         SP_LENIENT_BYTES[128 + 0x0D] = true;
1247         // TO SAVE PERFORMING Character::isWhitespace ceremony
1248         LATIN_WHITESPACE = new boolean[256];
1249         for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) {
1250             LATIN_WHITESPACE[128 + b] = Character.isWhitespace(b);
1251         }
1252     }
1253 
1254     private static boolean isSPLenient(byte c) {
1255         // See https://tools.ietf.org/html/rfc7230#section-3.5
1256         return SP_LENIENT_BYTES[c + 128];
1257     }
1258 
1259     private static boolean isWhitespace(byte b) {
1260         return LATIN_WHITESPACE[b + 128];
1261     }
1262 
1263     private static int findNonWhitespace(byte[] sb, int offset, int end) {
1264         for (int result = offset; result < end; ++result) {
1265             byte c = sb[result];
1266             if (!isWhitespace(c)) {
1267                 return result;
1268             } else if (!isOWS(c)) {
1269                 // Only OWS is supported for whitespace
1270                 throw new IllegalArgumentException("Invalid separator, only a single space or horizontal tab allowed," +
1271                         " but received a '" + c + "' (0x" + Integer.toHexString(c) + ")");
1272             }
1273         }
1274         return end;
1275     }
1276 
1277     private static int findEndOfString(byte[] sb, int start, int end) {
1278         for (int result = end - 1; result > start; --result) {
1279             if (!isOWS(sb[result])) {
1280                 return result + 1;
1281             }
1282         }
1283         return 0;
1284     }
1285 
1286     private static boolean isOWS(byte ch) {
1287         return ch == ' ' || ch == 0x09;
1288     }
1289 
1290     private static class HeaderParser {
1291         protected final ByteBuf seq;
1292         protected final int maxLength;
1293         int size;
1294 
1295         HeaderParser(ByteBuf seq, int maxLength) {
1296             this.seq = seq;
1297             this.maxLength = maxLength;
1298         }
1299 
1300         public ByteBuf parse(ByteBuf buffer, Runnable strictCRLFCheck) {
1301             final int readableBytes = buffer.readableBytes();
1302             final int readerIndex = buffer.readerIndex();
1303             final int maxBodySize = maxLength - size;
1304             assert maxBodySize >= 0;
1305             // adding 2 to account for both CR (if present) and LF
1306             // don't remove 2L: it's key to cover maxLength = Integer.MAX_VALUE
1307             final long maxBodySizeWithCRLF = maxBodySize + 2L;
1308             final int toProcess = (int) Math.min(maxBodySizeWithCRLF, readableBytes);
1309             final int toIndexExclusive = readerIndex + toProcess;
1310             assert toIndexExclusive >= readerIndex;
1311             final int indexOfLf = buffer.indexOf(readerIndex, toIndexExclusive, HttpConstants.LF);
1312             if (indexOfLf == -1) {
1313                 if (readableBytes > maxBodySize) {
1314                     // TODO: Respond with Bad Request and discard the traffic
1315                     //    or close the connection.
1316                     //       No need to notify the upstream handlers - just log.
1317                     //       If decoding a response, just throw an exception.
1318                     throw newException(maxLength);
1319                 }
1320                 return null;
1321             }
1322             final int endOfSeqIncluded;
1323             if (indexOfLf > readerIndex && buffer.getByte(indexOfLf - 1) == HttpConstants.CR) {
1324                 // Drop CR if we had a CRLF pair
1325                 endOfSeqIncluded = indexOfLf - 1;
1326             } else {
1327                 if (strictCRLFCheck != null) {
1328                     strictCRLFCheck.run();
1329                 }
1330                 endOfSeqIncluded = indexOfLf;
1331             }
1332             final int newSize = endOfSeqIncluded - readerIndex;
1333             if (newSize == 0) {
1334                 seq.clear();
1335                 buffer.readerIndex(indexOfLf + 1);
1336                 return seq;
1337             }
1338             int size = this.size + newSize;
1339             if (size > maxLength) {
1340                 throw newException(maxLength);
1341             }
1342             this.size = size;
1343             seq.clear();
1344             seq.writeBytes(buffer, readerIndex, newSize);
1345             buffer.readerIndex(indexOfLf + 1);
1346             return seq;
1347         }
1348 
1349         public void reset() {
1350             size = 0;
1351         }
1352 
1353         protected TooLongFrameException newException(int maxLength) {
1354             return new TooLongHttpHeaderException("HTTP header is larger than " + maxLength + " bytes.");
1355         }
1356     }
1357 
1358     private final class LineParser extends HeaderParser {
1359 
1360         LineParser(ByteBuf seq, int maxLength) {
1361             super(seq, maxLength);
1362         }
1363 
1364         @Override
1365         public ByteBuf parse(ByteBuf buffer, Runnable strictCRLFCheck) {
1366             // Suppress a warning because HeaderParser.reset() is supposed to be called
1367             reset();
1368             final int readableBytes = buffer.readableBytes();
1369             if (readableBytes == 0) {
1370                 return null;
1371             }
1372             if (currentState == State.SKIP_INITIAL_LINE_CHARS &&
1373                     skipLineChars(buffer, readableBytes, buffer.readerIndex(), strictCRLFCheck)) {
1374                 return null;
1375             }
1376             return super.parse(buffer, strictCRLFCheck);
1377         }
1378 
1379         private boolean skipLineChars(ByteBuf buffer, int readableBytes, int readerIndex, Runnable strictCRLFCheck) {
1380             assert currentState == State.SKIP_INITIAL_LINE_CHARS;
1381             final int maxToSkip = Math.min(maxLength, readableBytes);
1382             final int firstNonLineIndex = buffer.forEachByte(readerIndex, maxToSkip,
1383                     strictCRLFCheck == null ? SKIP_CONTROL_CHARS_BYTES : ByteProcessor.FIND_NON_CRLF);
1384             if (firstNonLineIndex == -1) {
1385                 buffer.skipBytes(maxToSkip);
1386                 if (readableBytes > maxLength) {
1387                     throw newException(maxLength);
1388                 }
1389                 return true;
1390             }
1391             if (strictCRLFCheck != null) {
1392                 final int b = buffer.getByte(firstNonLineIndex) & 0xFF;
1393                 if (Character.isISOControl(b)) {
1394                     strictCRLFCheck.run();
1395                 }
1396             }
1397             // from now on we don't care about control chars
1398             buffer.readerIndex(firstNonLineIndex);
1399             currentState = State.READ_INITIAL;
1400             return false;
1401         }
1402 
1403         @Override
1404         protected TooLongFrameException newException(int maxLength) {
1405             return new TooLongHttpLineException("An HTTP line is larger than " + maxLength + " bytes.");
1406         }
1407     }
1408 
1409     private static final boolean[] ISO_CONTROL_OR_WHITESPACE;
1410 
1411     static {
1412         ISO_CONTROL_OR_WHITESPACE = new boolean[256];
1413         for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) {
1414             ISO_CONTROL_OR_WHITESPACE[128 + b] = Character.isISOControl(b) || isWhitespace(b);
1415         }
1416     }
1417 
1418     private static final ByteProcessor SKIP_CONTROL_CHARS_BYTES = new ByteProcessor() {
1419         @Override
1420         public boolean process(byte value) {
1421             return ISO_CONTROL_OR_WHITESPACE[128 + value];
1422         }
1423     };
1424 
1425     private static boolean isControlOrWhitespaceAsciiChar(byte b) {
1426         return ISO_CONTROL_OR_WHITESPACE[128 + b];
1427     }
1428 }