View Javadoc
1   /*
2    * Copyright 2016 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  
17  package io.netty.handler.codec.http2;
18  
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.buffer.Unpooled;
21  import io.netty.channel.Channel;
22  import io.netty.channel.ChannelHandler;
23  import io.netty.channel.ChannelHandler.Sharable;
24  import io.netty.channel.ChannelHandlerContext;
25  import io.netty.handler.codec.EncoderException;
26  import io.netty.handler.codec.MessageToMessageCodec;
27  import io.netty.handler.codec.http.DefaultHttpContent;
28  import io.netty.handler.codec.http.DefaultLastHttpContent;
29  import io.netty.handler.codec.http.FullHttpMessage;
30  import io.netty.handler.codec.http.FullHttpResponse;
31  import io.netty.handler.codec.http.HttpContent;
32  import io.netty.handler.codec.http.HttpHeaderNames;
33  import io.netty.handler.codec.http.HttpHeaderValues;
34  import io.netty.handler.codec.http.HttpMessage;
35  import io.netty.handler.codec.http.HttpObject;
36  import io.netty.handler.codec.http.HttpRequest;
37  import io.netty.handler.codec.http.HttpResponse;
38  import io.netty.handler.codec.http.HttpResponseStatus;
39  import io.netty.handler.codec.http.HttpScheme;
40  import io.netty.handler.codec.http.HttpUtil;
41  import io.netty.handler.codec.http.HttpVersion;
42  import io.netty.handler.codec.http.LastHttpContent;
43  import io.netty.handler.ssl.SslHandler;
44  import io.netty.util.internal.UnstableApi;
45  
46  import java.util.List;
47  
48  /**
49   * This handler converts from {@link Http2StreamFrame} to {@link HttpObject},
50   * and back. It can be used as an adapter in conjunction with {@link
51   * Http2MultiplexCodec} to make http/2 connections backward-compatible with
52   * {@link ChannelHandler}s expecting {@link HttpObject}
53   *
54   * For simplicity, it converts to chunked encoding unless the entire stream
55   * is a single header.
56   */
57  @UnstableApi
58  @Sharable
59  public class Http2StreamFrameToHttpObjectCodec extends MessageToMessageCodec<Http2StreamFrame, HttpObject> {
60      private final boolean isServer;
61      private final boolean validateHeaders;
62  
63      private HttpScheme scheme;
64  
65      public Http2StreamFrameToHttpObjectCodec(final boolean isServer,
66                                               final boolean validateHeaders) {
67          this.isServer = isServer;
68          this.validateHeaders = validateHeaders;
69          scheme = HttpScheme.HTTP;
70      }
71  
72      public Http2StreamFrameToHttpObjectCodec(final boolean isServer) {
73          this(isServer, true);
74      }
75  
76      @Override
77      public boolean acceptInboundMessage(Object msg) throws Exception {
78          return (msg instanceof Http2HeadersFrame) || (msg instanceof Http2DataFrame);
79      }
80  
81      @Override
82      protected void decode(ChannelHandlerContext ctx, Http2StreamFrame frame, List<Object> out) throws Exception {
83          if (frame instanceof Http2HeadersFrame) {
84              int id = 0; // not really the id
85              Http2HeadersFrame headersFrame = (Http2HeadersFrame) frame;
86              Http2Headers headers = headersFrame.headers();
87  
88              final CharSequence status = headers.status();
89  
90              // 100-continue response is a special case where Http2HeadersFrame#isEndStream=false
91              // but we need to decode it as a FullHttpResponse to play nice with HttpObjectAggregator.
92              if (null != status && HttpResponseStatus.CONTINUE.codeAsText().contentEquals(status)) {
93                  final FullHttpMessage fullMsg = newFullMessage(id, headers, ctx.alloc());
94                  out.add(fullMsg);
95                  return;
96              }
97  
98              if (headersFrame.isEndStream()) {
99                  if (headers.method() == null && status == null) {
100                     LastHttpContent last = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER, validateHeaders);
101                     HttpConversionUtil.addHttp2ToHttpHeaders(id, headers, last.trailingHeaders(),
102                                                              HttpVersion.HTTP_1_1, true, true);
103                     out.add(last);
104                 } else {
105                     FullHttpMessage full = newFullMessage(id, headers, ctx.alloc());
106                     out.add(full);
107                 }
108             } else {
109                 HttpMessage req = newMessage(id, headers);
110                 if (!HttpUtil.isContentLengthSet(req)) {
111                     req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
112                 }
113                 out.add(req);
114             }
115         } else if (frame instanceof Http2DataFrame) {
116             Http2DataFrame dataFrame = (Http2DataFrame) frame;
117             if (dataFrame.isEndStream()) {
118                 out.add(new DefaultLastHttpContent(dataFrame.content().retain(), validateHeaders));
119             } else {
120                 out.add(new DefaultHttpContent(dataFrame.content().retain()));
121             }
122         }
123     }
124 
125     private void encodeLastContent(LastHttpContent last, List<Object> out) {
126         boolean needFiller = !(last instanceof FullHttpMessage) && last.trailingHeaders().isEmpty();
127         if (last.content().isReadable() || needFiller) {
128             out.add(new DefaultHttp2DataFrame(last.content().retain(), last.trailingHeaders().isEmpty()));
129         }
130         if (!last.trailingHeaders().isEmpty()) {
131             Http2Headers headers = HttpConversionUtil.toHttp2Headers(last.trailingHeaders(), validateHeaders);
132             out.add(new DefaultHttp2HeadersFrame(headers, true));
133         }
134     }
135 
136     /**
137      * Encode from an {@link HttpObject} to an {@link Http2StreamFrame}. This method will
138      * be called for each written message that can be handled by this encoder.
139      *
140      * NOTE: 100-Continue responses that are NOT {@link FullHttpResponse} will be rejected.
141      *
142      * @param ctx           the {@link ChannelHandlerContext} which this handler belongs to
143      * @param obj           the {@link HttpObject} message to encode
144      * @param out           the {@link List} into which the encoded msg should be added
145      *                      needs to do some kind of aggregation
146      * @throws Exception    is thrown if an error occurs
147      */
148     @Override
149     protected void encode(ChannelHandlerContext ctx, HttpObject obj, List<Object> out) throws Exception {
150         // 100-continue is typically a FullHttpResponse, but the decoded
151         // Http2HeadersFrame should not be marked as endStream=true
152         if (obj instanceof HttpResponse) {
153             final HttpResponse res = (HttpResponse) obj;
154             if (res.status().equals(HttpResponseStatus.CONTINUE)) {
155                 if (res instanceof FullHttpResponse) {
156                     final Http2Headers headers = toHttp2Headers(res);
157                     out.add(new DefaultHttp2HeadersFrame(headers, false));
158                     return;
159                 } else {
160                     throw new EncoderException(
161                             HttpResponseStatus.CONTINUE.toString() + " must be a FullHttpResponse");
162                 }
163             }
164         }
165 
166         if (obj instanceof HttpMessage) {
167             Http2Headers headers = toHttp2Headers((HttpMessage) obj);
168             boolean noMoreFrames = false;
169             if (obj instanceof FullHttpMessage) {
170                 FullHttpMessage full = (FullHttpMessage) obj;
171                 noMoreFrames = !full.content().isReadable() && full.trailingHeaders().isEmpty();
172             }
173 
174             out.add(new DefaultHttp2HeadersFrame(headers, noMoreFrames));
175         }
176 
177         if (obj instanceof LastHttpContent) {
178             LastHttpContent last = (LastHttpContent) obj;
179             encodeLastContent(last, out);
180         } else if (obj instanceof HttpContent) {
181             HttpContent cont = (HttpContent) obj;
182             out.add(new DefaultHttp2DataFrame(cont.content().retain(), false));
183         }
184     }
185 
186     private Http2Headers toHttp2Headers(final HttpMessage msg) {
187         if (msg instanceof HttpRequest) {
188             msg.headers().set(
189                     HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(),
190                     scheme.name());
191         }
192 
193         return HttpConversionUtil.toHttp2Headers(msg, validateHeaders);
194     }
195 
196     private HttpMessage newMessage(final int id,
197                                    final Http2Headers headers) throws Http2Exception {
198         return isServer ?
199                 HttpConversionUtil.toHttpRequest(id, headers, validateHeaders) :
200                 HttpConversionUtil.toHttpResponse(id, headers, validateHeaders);
201     }
202 
203     private FullHttpMessage newFullMessage(final int id,
204                                            final Http2Headers headers,
205                                            final ByteBufAllocator alloc) throws Http2Exception {
206         return isServer ?
207                 HttpConversionUtil.toFullHttpRequest(id, headers, alloc, validateHeaders) :
208                 HttpConversionUtil.toFullHttpResponse(id, headers, alloc, validateHeaders);
209     }
210 
211     @Override
212     public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
213         super.handlerAdded(ctx);
214 
215         // this handler is typically used on an Http2StreamChannel. at this
216         // stage, ssl handshake should've been established. checking for the
217         // presence of SslHandler in the parent's channel pipeline to
218         // determine the HTTP scheme should suffice, even for the case where
219         // SniHandler is used.
220         scheme = isSsl(ctx) ? HttpScheme.HTTPS : HttpScheme.HTTP;
221     }
222 
223     protected boolean isSsl(final ChannelHandlerContext ctx) {
224         final Channel ch = ctx.channel();
225         final Channel connChannel = (ch instanceof Http2StreamChannel) ? ch.parent() : ch;
226         return null != connChannel.pipeline().get(SslHandler.class);
227     }
228 }