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    *   http://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.ChannelFuture;
21  import io.netty.channel.ChannelFutureListener;
22  import io.netty.channel.ChannelHandler;
23  import io.netty.channel.ChannelHandlerContext;
24  import io.netty.channel.ChannelPipeline;
25  import io.netty.handler.codec.DecoderResult;
26  import io.netty.handler.codec.MessageAggregator;
27  import io.netty.handler.codec.TooLongFrameException;
28  import io.netty.util.internal.logging.InternalLogger;
29  import io.netty.util.internal.logging.InternalLoggerFactory;
30  
31  import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
32  import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
33  import static io.netty.handler.codec.http.HttpHeaderNames.EXPECT;
34  import static io.netty.handler.codec.http.HttpUtil.getContentLength;
35  
36  /**
37   * A {@link ChannelHandler} that aggregates an {@link HttpMessage}
38   * and its following {@link HttpContent}s into a single {@link FullHttpRequest}
39   * or {@link FullHttpResponse} (depending on if it used to handle requests or responses)
40   * with no following {@link HttpContent}s.  It is useful when you don't want to take
41   * care of HTTP messages whose transfer encoding is 'chunked'.  Insert this
42   * handler after {@link HttpResponseDecoder} in the {@link ChannelPipeline} if being used to handle
43   * responses, or after {@link HttpRequestDecoder} and {@link HttpResponseEncoder} in the
44   * {@link ChannelPipeline} if being used to handle requests.
45   * <blockquote>
46   *  <pre>
47   *  {@link ChannelPipeline} p = ...;
48   *  ...
49   *  p.addLast("decoder", <b>new {@link HttpRequestDecoder}()</b>);
50   *  p.addLast("encoder", <b>new {@link HttpResponseEncoder}()</b>);
51   *  p.addLast("aggregator", <b>new {@link HttpObjectAggregator}(1048576)</b>);
52   *  ...
53   *  p.addLast("handler", new HttpRequestHandler());
54   *  </pre>
55   * </blockquote>
56   * <p>
57   * For convenience, consider putting a {@link HttpServerCodec} before the {@link HttpObjectAggregator}
58   * as it functions as both a {@link HttpRequestDecoder} and a {@link HttpResponseEncoder}.
59   * </p>
60   * Be aware that {@link HttpObjectAggregator} may end up sending a {@link HttpResponse}:
61   * <table border summary="Possible Responses">
62   *   <tbody>
63   *     <tr>
64   *       <th>Response Status</th>
65   *       <th>Condition When Sent</th>
66   *     </tr>
67   *     <tr>
68   *       <td>100 Continue</td>
69   *       <td>A '100-continue' expectation is received and the 'content-length' doesn't exceed maxContentLength</td>
70   *     </tr>
71   *     <tr>
72   *       <td>417 Expectation Failed</td>
73   *       <td>A '100-continue' expectation is received and the 'content-length' exceeds maxContentLength</td>
74   *     </tr>
75   *     <tr>
76   *       <td>413 Request Entity Too Large</td>
77   *       <td>Either the 'content-length' or the bytes received so far exceed maxContentLength</td>
78   *     </tr>
79   *   </tbody>
80   * </table>
81   *
82   * @see FullHttpRequest
83   * @see FullHttpResponse
84   * @see HttpResponseDecoder
85   * @see HttpServerCodec
86   */
87  public class HttpObjectAggregator
88          extends MessageAggregator<HttpObject, HttpMessage, HttpContent, FullHttpMessage> {
89      private static final InternalLogger logger = InternalLoggerFactory.getInstance(HttpObjectAggregator.class);
90      private static final FullHttpResponse CONTINUE =
91              new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE, Unpooled.EMPTY_BUFFER);
92      private static final FullHttpResponse EXPECTATION_FAILED = new DefaultFullHttpResponse(
93              HttpVersion.HTTP_1_1, HttpResponseStatus.EXPECTATION_FAILED, Unpooled.EMPTY_BUFFER);
94      private static final FullHttpResponse TOO_LARGE_CLOSE = new DefaultFullHttpResponse(
95              HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, Unpooled.EMPTY_BUFFER);
96      private static final FullHttpResponse TOO_LARGE = new DefaultFullHttpResponse(
97          HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, Unpooled.EMPTY_BUFFER);
98  
99      static {
100         EXPECTATION_FAILED.headers().set(CONTENT_LENGTH, 0);
101         TOO_LARGE.headers().set(CONTENT_LENGTH, 0);
102 
103         TOO_LARGE_CLOSE.headers().set(CONTENT_LENGTH, 0);
104         TOO_LARGE_CLOSE.headers().set(CONNECTION, HttpHeaderValues.CLOSE);
105     }
106 
107     private final boolean closeOnExpectationFailed;
108 
109     /**
110      * Creates a new instance.
111      * @param maxContentLength the maximum length of the aggregated content in bytes.
112      * If the length of the aggregated content exceeds this value,
113      * {@link #handleOversizedMessage(ChannelHandlerContext, HttpMessage)} will be called.
114      */
115     public HttpObjectAggregator(int maxContentLength) {
116         this(maxContentLength, false);
117     }
118 
119     /**
120      * Creates a new instance.
121      * @param maxContentLength the maximum length of the aggregated content in bytes.
122      * If the length of the aggregated content exceeds this value,
123      * {@link #handleOversizedMessage(ChannelHandlerContext, HttpMessage)} will be called.
124      * @param closeOnExpectationFailed If a 100-continue response is detected but the content length is too large
125      * then {@code true} means close the connection. otherwise the connection will remain open and data will be
126      * consumed and discarded until the next request is received.
127      */
128     public HttpObjectAggregator(int maxContentLength, boolean closeOnExpectationFailed) {
129         super(maxContentLength);
130         this.closeOnExpectationFailed = closeOnExpectationFailed;
131     }
132 
133     @Override
134     protected boolean isStartMessage(HttpObject msg) throws Exception {
135         return msg instanceof HttpMessage;
136     }
137 
138     @Override
139     protected boolean isContentMessage(HttpObject msg) throws Exception {
140         return msg instanceof HttpContent;
141     }
142 
143     @Override
144     protected boolean isLastContentMessage(HttpContent msg) throws Exception {
145         return msg instanceof LastHttpContent;
146     }
147 
148     @Override
149     protected boolean isAggregated(HttpObject msg) throws Exception {
150         return msg instanceof FullHttpMessage;
151     }
152 
153     @Override
154     protected boolean isContentLengthInvalid(HttpMessage start, int maxContentLength) {
155         try {
156             return getContentLength(start, -1L) > maxContentLength;
157         } catch (final NumberFormatException e) {
158             return false;
159         }
160     }
161 
162     private static Object continueResponse(HttpMessage start, int maxContentLength, ChannelPipeline pipeline) {
163         if (HttpUtil.isUnsupportedExpectation(start)) {
164             // if the request contains an unsupported expectation, we return 417
165             pipeline.fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE);
166             return EXPECTATION_FAILED.retainedDuplicate();
167         } else if (HttpUtil.is100ContinueExpected(start)) {
168             // if the request contains 100-continue but the content-length is too large, we return 413
169             if (getContentLength(start, -1L) <= maxContentLength) {
170                 return CONTINUE.retainedDuplicate();
171             }
172             pipeline.fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE);
173             return TOO_LARGE.retainedDuplicate();
174         }
175 
176         return null;
177     }
178 
179     @Override
180     protected Object newContinueResponse(HttpMessage start, int maxContentLength, ChannelPipeline pipeline) {
181         Object response = continueResponse(start, maxContentLength, pipeline);
182         // we're going to respond based on the request expectation so there's no
183         // need to propagate the expectation further.
184         if (response != null) {
185             start.headers().remove(EXPECT);
186         }
187         return response;
188     }
189 
190     @Override
191     protected boolean closeAfterContinueResponse(Object msg) {
192         return closeOnExpectationFailed && ignoreContentAfterContinueResponse(msg);
193     }
194 
195     @Override
196     protected boolean ignoreContentAfterContinueResponse(Object msg) {
197         if (msg instanceof HttpResponse) {
198             final HttpResponse httpResponse = (HttpResponse) msg;
199             return httpResponse.status().codeClass().equals(HttpStatusClass.CLIENT_ERROR);
200         }
201         return false;
202     }
203 
204     @Override
205     protected FullHttpMessage beginAggregation(HttpMessage start, ByteBuf content) throws Exception {
206         assert !(start instanceof FullHttpMessage);
207 
208         HttpUtil.setTransferEncodingChunked(start, false);
209 
210         AggregatedFullHttpMessage ret;
211         if (start instanceof HttpRequest) {
212             ret = new AggregatedFullHttpRequest((HttpRequest) start, content, null);
213         } else if (start instanceof HttpResponse) {
214             ret = new AggregatedFullHttpResponse((HttpResponse) start, content, null);
215         } else {
216             throw new Error();
217         }
218         return ret;
219     }
220 
221     @Override
222     protected void aggregate(FullHttpMessage aggregated, HttpContent content) throws Exception {
223         if (content instanceof LastHttpContent) {
224             // Merge trailing headers into the message.
225             ((AggregatedFullHttpMessage) aggregated).setTrailingHeaders(((LastHttpContent) content).trailingHeaders());
226         }
227     }
228 
229     @Override
230     protected void finishAggregation(FullHttpMessage aggregated) throws Exception {
231         // Set the 'Content-Length' header. If one isn't already set.
232         // This is important as HEAD responses will use a 'Content-Length' header which
233         // does not match the actual body, but the number of bytes that would be
234         // transmitted if a GET would have been used.
235         //
236         // See rfc2616 14.13 Content-Length
237         if (!HttpUtil.isContentLengthSet(aggregated)) {
238             aggregated.headers().set(
239                     CONTENT_LENGTH,
240                     String.valueOf(aggregated.content().readableBytes()));
241         }
242     }
243 
244     @Override
245     protected void handleOversizedMessage(final ChannelHandlerContext ctx, HttpMessage oversized) throws Exception {
246         if (oversized instanceof HttpRequest) {
247             // send back a 413 and close the connection
248 
249             // If the client started to send data already, close because it's impossible to recover.
250             // If keep-alive is off and 'Expect: 100-continue' is missing, no need to leave the connection open.
251             if (oversized instanceof FullHttpMessage ||
252                 !HttpUtil.is100ContinueExpected(oversized) && !HttpUtil.isKeepAlive(oversized)) {
253                 ChannelFuture future = ctx.writeAndFlush(TOO_LARGE_CLOSE.retainedDuplicate());
254                 future.addListener(new ChannelFutureListener() {
255                     @Override
256                     public void operationComplete(ChannelFuture future) throws Exception {
257                         if (!future.isSuccess()) {
258                             logger.debug("Failed to send a 413 Request Entity Too Large.", future.cause());
259                         }
260                         ctx.close();
261                     }
262                 });
263             } else {
264                 ctx.writeAndFlush(TOO_LARGE.retainedDuplicate()).addListener(new ChannelFutureListener() {
265                     @Override
266                     public void operationComplete(ChannelFuture future) throws Exception {
267                         if (!future.isSuccess()) {
268                             logger.debug("Failed to send a 413 Request Entity Too Large.", future.cause());
269                             ctx.close();
270                         }
271                     }
272                 });
273             }
274         } else if (oversized instanceof HttpResponse) {
275             ctx.close();
276             throw new TooLongFrameException("Response entity too large: " + oversized);
277         } else {
278             throw new IllegalStateException();
279         }
280     }
281 
282     private abstract static class AggregatedFullHttpMessage implements FullHttpMessage {
283         protected final HttpMessage message;
284         private final ByteBuf content;
285         private HttpHeaders trailingHeaders;
286 
287         AggregatedFullHttpMessage(HttpMessage message, ByteBuf content, HttpHeaders trailingHeaders) {
288             this.message = message;
289             this.content = content;
290             this.trailingHeaders = trailingHeaders;
291         }
292 
293         @Override
294         public HttpHeaders trailingHeaders() {
295             HttpHeaders trailingHeaders = this.trailingHeaders;
296             if (trailingHeaders == null) {
297                 return EmptyHttpHeaders.INSTANCE;
298             } else {
299                 return trailingHeaders;
300             }
301         }
302 
303         void setTrailingHeaders(HttpHeaders trailingHeaders) {
304             this.trailingHeaders = trailingHeaders;
305         }
306 
307         @Override
308         public HttpVersion getProtocolVersion() {
309             return message.protocolVersion();
310         }
311 
312         @Override
313         public HttpVersion protocolVersion() {
314             return message.protocolVersion();
315         }
316 
317         @Override
318         public FullHttpMessage setProtocolVersion(HttpVersion version) {
319             message.setProtocolVersion(version);
320             return this;
321         }
322 
323         @Override
324         public HttpHeaders headers() {
325             return message.headers();
326         }
327 
328         @Override
329         public DecoderResult decoderResult() {
330             return message.decoderResult();
331         }
332 
333         @Override
334         public DecoderResult getDecoderResult() {
335             return message.decoderResult();
336         }
337 
338         @Override
339         public void setDecoderResult(DecoderResult result) {
340             message.setDecoderResult(result);
341         }
342 
343         @Override
344         public ByteBuf content() {
345             return content;
346         }
347 
348         @Override
349         public int refCnt() {
350             return content.refCnt();
351         }
352 
353         @Override
354         public FullHttpMessage retain() {
355             content.retain();
356             return this;
357         }
358 
359         @Override
360         public FullHttpMessage retain(int increment) {
361             content.retain(increment);
362             return this;
363         }
364 
365         @Override
366         public FullHttpMessage touch(Object hint) {
367             content.touch(hint);
368             return this;
369         }
370 
371         @Override
372         public FullHttpMessage touch() {
373             content.touch();
374             return this;
375         }
376 
377         @Override
378         public boolean release() {
379             return content.release();
380         }
381 
382         @Override
383         public boolean release(int decrement) {
384             return content.release(decrement);
385         }
386 
387         @Override
388         public abstract FullHttpMessage copy();
389 
390         @Override
391         public abstract FullHttpMessage duplicate();
392 
393         @Override
394         public abstract FullHttpMessage retainedDuplicate();
395     }
396 
397     private static final class AggregatedFullHttpRequest extends AggregatedFullHttpMessage implements FullHttpRequest {
398 
399         AggregatedFullHttpRequest(HttpRequest request, ByteBuf content, HttpHeaders trailingHeaders) {
400             super(request, content, trailingHeaders);
401         }
402 
403         @Override
404         public FullHttpRequest copy() {
405             return replace(content().copy());
406         }
407 
408         @Override
409         public FullHttpRequest duplicate() {
410             return replace(content().duplicate());
411         }
412 
413         @Override
414         public FullHttpRequest retainedDuplicate() {
415             return replace(content().retainedDuplicate());
416         }
417 
418         @Override
419         public FullHttpRequest replace(ByteBuf content) {
420             DefaultFullHttpRequest dup = new DefaultFullHttpRequest(protocolVersion(), method(), uri(), content,
421                     headers().copy(), trailingHeaders().copy());
422             dup.setDecoderResult(decoderResult());
423             return dup;
424         }
425 
426         @Override
427         public FullHttpRequest retain(int increment) {
428             super.retain(increment);
429             return this;
430         }
431 
432         @Override
433         public FullHttpRequest retain() {
434             super.retain();
435             return this;
436         }
437 
438         @Override
439         public FullHttpRequest touch() {
440             super.touch();
441             return this;
442         }
443 
444         @Override
445         public FullHttpRequest touch(Object hint) {
446             super.touch(hint);
447             return this;
448         }
449 
450         @Override
451         public FullHttpRequest setMethod(HttpMethod method) {
452             ((HttpRequest) message).setMethod(method);
453             return this;
454         }
455 
456         @Override
457         public FullHttpRequest setUri(String uri) {
458             ((HttpRequest) message).setUri(uri);
459             return this;
460         }
461 
462         @Override
463         public HttpMethod getMethod() {
464             return ((HttpRequest) message).method();
465         }
466 
467         @Override
468         public String getUri() {
469             return ((HttpRequest) message).uri();
470         }
471 
472         @Override
473         public HttpMethod method() {
474             return getMethod();
475         }
476 
477         @Override
478         public String uri() {
479             return getUri();
480         }
481 
482         @Override
483         public FullHttpRequest setProtocolVersion(HttpVersion version) {
484             super.setProtocolVersion(version);
485             return this;
486         }
487 
488         @Override
489         public String toString() {
490             return HttpMessageUtil.appendFullRequest(new StringBuilder(256), this).toString();
491         }
492     }
493 
494     private static final class AggregatedFullHttpResponse extends AggregatedFullHttpMessage
495             implements FullHttpResponse {
496 
497         AggregatedFullHttpResponse(HttpResponse message, ByteBuf content, HttpHeaders trailingHeaders) {
498             super(message, content, trailingHeaders);
499         }
500 
501         @Override
502         public FullHttpResponse copy() {
503             return replace(content().copy());
504         }
505 
506         @Override
507         public FullHttpResponse duplicate() {
508             return replace(content().duplicate());
509         }
510 
511         @Override
512         public FullHttpResponse retainedDuplicate() {
513             return replace(content().retainedDuplicate());
514         }
515 
516         @Override
517         public FullHttpResponse replace(ByteBuf content) {
518             DefaultFullHttpResponse dup = new DefaultFullHttpResponse(getProtocolVersion(), getStatus(), content,
519                     headers().copy(), trailingHeaders().copy());
520             dup.setDecoderResult(decoderResult());
521             return dup;
522         }
523 
524         @Override
525         public FullHttpResponse setStatus(HttpResponseStatus status) {
526             ((HttpResponse) message).setStatus(status);
527             return this;
528         }
529 
530         @Override
531         public HttpResponseStatus getStatus() {
532             return ((HttpResponse) message).status();
533         }
534 
535         @Override
536         public HttpResponseStatus status() {
537             return getStatus();
538         }
539 
540         @Override
541         public FullHttpResponse setProtocolVersion(HttpVersion version) {
542             super.setProtocolVersion(version);
543             return this;
544         }
545 
546         @Override
547         public FullHttpResponse retain(int increment) {
548             super.retain(increment);
549             return this;
550         }
551 
552         @Override
553         public FullHttpResponse retain() {
554             super.retain();
555             return this;
556         }
557 
558         @Override
559         public FullHttpResponse touch(Object hint) {
560             super.touch(hint);
561             return this;
562         }
563 
564         @Override
565         public FullHttpResponse touch() {
566             super.touch();
567             return this;
568         }
569 
570         @Override
571         public String toString() {
572             return HttpMessageUtil.appendFullResponse(new StringBuilder(256), this).toString();
573         }
574     }
575 }