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.channel.ChannelHandlerContext;
20  import io.netty.channel.CombinedChannelDuplexHandler;
21  
22  import java.util.ArrayDeque;
23  import java.util.List;
24  import java.util.Queue;
25  
26  /**
27   * A combination of {@link HttpRequestDecoder} and {@link HttpResponseEncoder}
28   * which enables easier server side HTTP implementation.
29   *
30   * @see HttpClientCodec
31   */
32  public final class HttpServerCodec extends CombinedChannelDuplexHandler<HttpRequestDecoder, HttpResponseEncoder>
33          implements HttpServerUpgradeHandler.SourceCodec {
34  
35      /** A queue that is used for correlating a request and a response. */
36      private final Queue<HttpMethod> queue = new ArrayDeque<HttpMethod>();
37  
38      /**
39       * Creates a new instance with the default decoder options
40       * ({@code maxInitialLineLength (4096}}, {@code maxHeaderSize (8192)}, and
41       * {@code maxChunkSize (8192)}).
42       */
43      public HttpServerCodec() {
44          this(4096, 8192, 8192);
45      }
46  
47      /**
48       * Creates a new instance with the specified decoder options.
49       */
50      public HttpServerCodec(int maxInitialLineLength, int maxHeaderSize, int maxChunkSize) {
51          init(new HttpServerRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize),
52                  new HttpServerResponseEncoder());
53      }
54  
55      /**
56       * Creates a new instance with the specified decoder options.
57       */
58      public HttpServerCodec(int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean validateHeaders) {
59          init(new HttpServerRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize, validateHeaders),
60                  new HttpServerResponseEncoder());
61      }
62  
63      /**
64       * Creates a new instance with the specified decoder options.
65       */
66      public HttpServerCodec(int maxInitialLineLength, int maxHeaderSize, int maxChunkSize, boolean validateHeaders,
67                             int initialBufferSize) {
68          init(
69            new HttpServerRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize,
70                    validateHeaders, initialBufferSize),
71            new HttpServerResponseEncoder());
72      }
73  
74      /**
75       * Upgrades to another protocol from HTTP. Removes the {@link HttpRequestDecoder} and
76       * {@link HttpResponseEncoder} from the pipeline.
77       */
78      @Override
79      public void upgradeFrom(ChannelHandlerContext ctx) {
80          ctx.pipeline().remove(this);
81      }
82  
83      private final class HttpServerRequestDecoder extends HttpRequestDecoder {
84          public HttpServerRequestDecoder(int maxInitialLineLength, int maxHeaderSize, int maxChunkSize) {
85              super(maxInitialLineLength, maxHeaderSize, maxChunkSize);
86          }
87  
88          public HttpServerRequestDecoder(int maxInitialLineLength, int maxHeaderSize, int maxChunkSize,
89                                          boolean validateHeaders) {
90              super(maxInitialLineLength, maxHeaderSize, maxChunkSize, validateHeaders);
91          }
92  
93          public HttpServerRequestDecoder(int maxInitialLineLength, int maxHeaderSize, int maxChunkSize,
94                                          boolean validateHeaders, int initialBufferSize) {
95              super(maxInitialLineLength, maxHeaderSize, maxChunkSize, validateHeaders, initialBufferSize);
96          }
97  
98          @Override
99          protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
100             int oldSize = out.size();
101             super.decode(ctx, buffer, out);
102             int size = out.size();
103             for (int i = oldSize; i < size; i++) {
104                 Object obj = out.get(i);
105                 if (obj instanceof HttpRequest) {
106                     queue.add(((HttpRequest) obj).method());
107                 }
108             }
109         }
110     }
111 
112     private final class HttpServerResponseEncoder extends HttpResponseEncoder {
113 
114         private HttpMethod method;
115 
116         @Override
117         protected void sanitizeHeadersBeforeEncode(HttpResponse msg, boolean isAlwaysEmpty) {
118             if (!isAlwaysEmpty && method == HttpMethod.CONNECT && msg.status().codeClass() == HttpStatusClass.SUCCESS) {
119                 // Stripping Transfer-Encoding:
120                 // See https://tools.ietf.org/html/rfc7230#section-3.3.1
121                 msg.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
122                 return;
123             }
124 
125             super.sanitizeHeadersBeforeEncode(msg, isAlwaysEmpty);
126         }
127 
128         @Override
129         protected boolean isContentAlwaysEmpty(@SuppressWarnings("unused") HttpResponse msg) {
130             method = queue.poll();
131             return HttpMethod.HEAD.equals(method) || super.isContentAlwaysEmpty(msg);
132         }
133     }
134 }