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.ChannelPipeline;
21  
22  /**
23   * Decodes {@link ByteBuf}s into {@link HttpResponse}s and
24   * {@link HttpContent}s.
25   *
26   * <h3>Parameters that prevents excessive memory consumption</h3>
27   * <table border="1">
28   * <tr>
29   * <th>Name</th><th>Meaning</th>
30   * </tr>
31   * <tr>
32   * <td>{@code maxInitialLineLength}</td>
33   * <td>The maximum length of the initial line (e.g. {@code "HTTP/1.0 200 OK"})
34   *     If the length of the initial line exceeds this value, a
35   *     {@link TooLongHttpLineException} will be raised.</td>
36   * </tr>
37   * <tr>
38   * <td>{@code maxHeaderSize}</td>
39   * <td>The maximum length of all headers.  If the sum of the length of each
40   *     header exceeds this value, a {@link TooLongHttpHeaderException} will be raised.</td>
41   * </tr>
42   * <tr>
43   * <td>{@code maxChunkSize}</td>
44   * <td>The maximum length of the content or each chunk.  If the content length
45   *     exceeds this value, the transfer encoding of the decoded response will be
46   *     converted to 'chunked' and the content will be split into multiple
47   *     {@link HttpContent}s.  If the transfer encoding of the HTTP response is
48   *     'chunked' already, each chunk will be split into smaller chunks if the
49   *     length of the chunk exceeds this value.  If you prefer not to handle
50   *     {@link HttpContent}s in your handler, insert {@link HttpObjectAggregator}
51   *     after this decoder in the {@link ChannelPipeline}.</td>
52   * </tr>
53   * </table>
54   *
55   * <h3>Parameters that control parsing behavior</h3>
56   * <table border="1">
57   * <tr>
58   * <th>Name</th><th>Default value</th><th>Meaning</th>
59   * </tr>
60   * <tr>
61   * <td>{@code allowDuplicateContentLengths}</td>
62   * <td>{@value #DEFAULT_ALLOW_DUPLICATE_CONTENT_LENGTHS}</td>
63   * <td>When set to {@code false}, will reject any messages that contain multiple Content-Length header fields.
64   *     When set to {@code true}, will allow multiple Content-Length headers only if they are all the same decimal value.
65   *     The duplicated field-values will be replaced with a single valid Content-Length field.
66   *     See <a href="https://tools.ietf.org/html/rfc7230#section-3.3.2">RFC 7230, Section 3.3.2</a>.</td>
67   * </tr>
68   * <tr>
69   * <td>{@code allowPartialChunks}</td>
70   * <td>{@value #DEFAULT_ALLOW_PARTIAL_CHUNKS}</td>
71   * <td>If the length of a chunk exceeds the {@link ByteBuf}s readable bytes and {@code allowPartialChunks}
72   *     is set to {@code true}, the chunk will be split into multiple {@link HttpContent}s.
73   *     Otherwise, if the chunk size does not exceed {@code maxChunkSize} and {@code allowPartialChunks}
74   *     is set to {@code false}, the {@link ByteBuf} is not decoded into an {@link HttpContent} until
75   *     the readable bytes are greater or equal to the chunk size.</td>
76   * </tr>
77   * </table>
78   *
79   * <h3>Decoding a response for a <tt>HEAD</tt> request</h3>
80   * <p>
81   * Unlike other HTTP requests, the successful response of a <tt>HEAD</tt>
82   * request does not have any content even if there is <tt>Content-Length</tt>
83   * header.  Because {@link HttpResponseDecoder} is not able to determine if the
84   * response currently being decoded is associated with a <tt>HEAD</tt> request,
85   * you must override {@link #isContentAlwaysEmpty(HttpMessage)} to return
86   * <tt>true</tt> for the response of the <tt>HEAD</tt> request.
87   * </p><p>
88   * If you are writing an HTTP client that issues a <tt>HEAD</tt> request,
89   * please use {@link HttpClientCodec} instead of this decoder.  It will perform
90   * additional state management to handle the responses for <tt>HEAD</tt>
91   * requests correctly.
92   * </p>
93   *
94   * <h3>Decoding a response for a <tt>CONNECT</tt> request</h3>
95   * <p>
96   * You also need to do additional state management to handle the response of a
97   * <tt>CONNECT</tt> request properly, like you did for <tt>HEAD</tt>.  One
98   * difference is that the decoder should stop decoding completely after decoding
99   * the successful 200 response since the connection is not an HTTP connection
100  * anymore.
101  * </p><p>
102  * {@link HttpClientCodec} also handles this edge case correctly, so you have to
103  * use {@link HttpClientCodec} if you are writing an HTTP client that issues a
104  * <tt>CONNECT</tt> request.
105  * </p>
106  *
107  * <h3>Header Validation</h3>
108  *
109  * It is recommended to always enable header validation.
110  * <p>
111  * Without header validation, your system can become vulnerable to
112  * <a href="https://cwe.mitre.org/data/definitions/113.html">
113  *     CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')
114  * </a>.
115  * <p>
116  * This recommendation stands even when both peers in the HTTP exchange are trusted,
117  * as it helps with defence-in-depth.
118  */
119 public class HttpResponseDecoder extends HttpObjectDecoder {
120 
121     private static final HttpResponseStatus UNKNOWN_STATUS = new HttpResponseStatus(999, "Unknown");
122 
123     /**
124      * Creates a new instance with the default
125      * {@code maxInitialLineLength (4096)}, {@code maxHeaderSize (8192)}, and
126      * {@code maxChunkSize (8192)}.
127      */
128     public HttpResponseDecoder() {
129     }
130 
131     /**
132      * Creates a new instance with the specified parameters.
133      */
134     public HttpResponseDecoder(
135             int maxInitialLineLength, int maxHeaderSize, int maxChunkSize) {
136         super(new HttpDecoderConfig()
137                 .setMaxInitialLineLength(maxInitialLineLength)
138                 .setMaxHeaderSize(maxHeaderSize)
139                 .setMaxChunkSize(maxChunkSize));
140     }
141 
142     /**
143      * @deprecated Prefer the {@link #HttpResponseDecoder(HttpDecoderConfig)} constructor.
144      */
145     @Deprecated
146     public HttpResponseDecoder(
147             int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean validateHeaders) {
148         super(maxInitialLineLength, maxHeaderSize, maxChunkSize, DEFAULT_CHUNKED_SUPPORTED, validateHeaders);
149     }
150 
151     /**
152      * @deprecated Prefer the {@link #HttpResponseDecoder(HttpDecoderConfig)} constructor.
153      */
154     @Deprecated
155     public HttpResponseDecoder(
156             int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean validateHeaders,
157             int initialBufferSize) {
158         super(maxInitialLineLength, maxHeaderSize, maxChunkSize, DEFAULT_CHUNKED_SUPPORTED, validateHeaders,
159               initialBufferSize);
160     }
161 
162     /**
163      * @deprecated Prefer the {@link #HttpResponseDecoder(HttpDecoderConfig)} constructor.
164      */
165     @Deprecated
166     public HttpResponseDecoder(
167             int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean validateHeaders,
168             int initialBufferSize, boolean allowDuplicateContentLengths) {
169         super(maxInitialLineLength, maxHeaderSize, maxChunkSize, DEFAULT_CHUNKED_SUPPORTED, validateHeaders,
170               initialBufferSize, allowDuplicateContentLengths);
171     }
172 
173     /**
174      * @deprecated Prefer the {@link #HttpResponseDecoder(HttpDecoderConfig)} constructor.
175      */
176     @Deprecated
177     public HttpResponseDecoder(
178             int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean validateHeaders,
179             int initialBufferSize, boolean allowDuplicateContentLengths, boolean allowPartialChunks) {
180         super(maxInitialLineLength, maxHeaderSize, maxChunkSize, DEFAULT_CHUNKED_SUPPORTED, validateHeaders,
181               initialBufferSize, allowDuplicateContentLengths, allowPartialChunks);
182     }
183 
184     /**
185      * Creates a new instance with the specified configuration.
186      */
187     public HttpResponseDecoder(HttpDecoderConfig config) {
188         super(config);
189     }
190 
191     @Override
192     protected HttpMessage createMessage(String[] initialLine) {
193         return new DefaultHttpResponse(
194                 HttpVersion.valueOf(initialLine[0]),
195                 HttpResponseStatus.valueOf(Integer.parseInt(initialLine[1]), initialLine[2]), headersFactory);
196     }
197 
198     @Override
199     protected HttpMessage createInvalidMessage() {
200         return new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, UNKNOWN_STATUS, Unpooled.buffer(0),
201                 headersFactory, trailersFactory);
202     }
203 
204     @Override
205     protected boolean isDecodingRequest() {
206         return false;
207     }
208 }