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    *   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  
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.HttpStatusClass;
41  import io.netty.handler.codec.http.HttpUtil;
42  import io.netty.handler.codec.http.HttpVersion;
43  import io.netty.handler.codec.http.LastHttpContent;
44  import io.netty.handler.ssl.SslHandler;
45  import io.netty.util.Attribute;
46  import io.netty.util.AttributeKey;
47  
48  import java.util.List;
49  
50  /**
51   * This handler converts from {@link Http2StreamFrame} to {@link HttpObject},
52   * and back. It can be used as an adapter in conjunction with {@link
53   * Http2MultiplexCodec} to make http/2 connections backward-compatible with
54   * {@link ChannelHandler}s expecting {@link HttpObject}
55   *
56   * For simplicity, it converts to chunked encoding unless the entire stream
57   * is a single header.
58   */
59  @Sharable
60  public class Http2StreamFrameToHttpObjectCodec extends MessageToMessageCodec<Http2StreamFrame, HttpObject> {
61  
62      private static final AttributeKey<HttpScheme> SCHEME_ATTR_KEY =
63          AttributeKey.valueOf(HttpScheme.class, "STREAMFRAMECODEC_SCHEME");
64  
65      private final boolean isServer;
66      private final boolean validateHeaders;
67  
68      public Http2StreamFrameToHttpObjectCodec(final boolean isServer,
69                                               final boolean validateHeaders) {
70          super(Http2StreamFrame.class, HttpObject.class);
71          this.isServer = isServer;
72          this.validateHeaders = validateHeaders;
73      }
74  
75      public Http2StreamFrameToHttpObjectCodec(final boolean isServer) {
76          this(isServer, true);
77      }
78  
79      @Override
80      public boolean acceptInboundMessage(Object msg) throws Exception {
81          return msg instanceof Http2HeadersFrame || msg instanceof Http2DataFrame;
82      }
83  
84      @Override
85      protected void decode(ChannelHandlerContext ctx, Http2StreamFrame frame, List<Object> out) throws Exception {
86          if (frame instanceof Http2HeadersFrame) {
87              Http2HeadersFrame headersFrame = (Http2HeadersFrame) frame;
88              Http2Headers headers = headersFrame.headers();
89              Http2FrameStream stream = headersFrame.stream();
90              int id = stream == null ? 0 : stream.id();
91  
92              final CharSequence status = headers.status();
93  
94              // 1xx response (excluding 101) is a special case where Http2HeadersFrame#isEndStream=false
95              // but we need to decode it as a FullHttpResponse to play nice with HttpObjectAggregator.
96              if (null != status && isInformationalResponseHeaderFrame(status)) {
97                  final FullHttpMessage fullMsg = newFullMessage(id, headers, ctx.alloc());
98                  out.add(fullMsg);
99                  return;
100             }
101 
102             if (headersFrame.isEndStream()) {
103                 if (headers.method() == null && status == null) {
104                     LastHttpContent last = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER, validateHeaders);
105                     HttpConversionUtil.addHttp2ToHttpHeaders(id, headers, last.trailingHeaders(),
106                                                              HttpVersion.HTTP_1_1, true, true);
107                     out.add(last);
108                 } else {
109                     FullHttpMessage full = newFullMessage(id, headers, ctx.alloc());
110                     out.add(full);
111                 }
112             } else {
113                 HttpMessage req = newMessage(id, headers);
114                 if ((status == null || !isContentAlwaysEmpty(status)) && !HttpUtil.isContentLengthSet(req)) {
115                     req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
116                 }
117                 out.add(req);
118             }
119         } else if (frame instanceof Http2DataFrame) {
120             Http2DataFrame dataFrame = (Http2DataFrame) frame;
121             if (dataFrame.isEndStream()) {
122                 out.add(new DefaultLastHttpContent(dataFrame.content().retain(), validateHeaders));
123             } else {
124                 out.add(new DefaultHttpContent(dataFrame.content().retain()));
125             }
126         }
127     }
128 
129     private void encodeLastContent(LastHttpContent last, List<Object> out) {
130         boolean needFiller = !(last instanceof FullHttpMessage) && last.trailingHeaders().isEmpty();
131         if (last.content().isReadable() || needFiller) {
132             out.add(new DefaultHttp2DataFrame(last.content().retain(), last.trailingHeaders().isEmpty()));
133         }
134         if (!last.trailingHeaders().isEmpty()) {
135             Http2Headers headers = HttpConversionUtil.toHttp2Headers(last.trailingHeaders(), validateHeaders);
136             out.add(new DefaultHttp2HeadersFrame(headers, true));
137         }
138     }
139 
140     /**
141      * Encode from an {@link HttpObject} to an {@link Http2StreamFrame}. This method will
142      * be called for each written message that can be handled by this encoder.
143      *
144      * NOTE: 100-Continue responses that are NOT {@link FullHttpResponse} will be rejected.
145      *
146      * @param ctx           the {@link ChannelHandlerContext} which this handler belongs to
147      * @param obj           the {@link HttpObject} message to encode
148      * @param out           the {@link List} into which the encoded msg should be added
149      *                      needs to do some kind of aggregation
150      * @throws Exception    is thrown if an error occurs
151      */
152     @Override
153     protected void encode(ChannelHandlerContext ctx, HttpObject obj, List<Object> out) throws Exception {
154         // 1xx (excluding 101) is typically a FullHttpResponse, but the decoded
155         // Http2HeadersFrame should not be marked as endStream=true
156         if (obj instanceof HttpResponse) {
157             final HttpResponse res = (HttpResponse) obj;
158             final HttpResponseStatus status = res.status();
159             final int code = status.code();
160             final HttpStatusClass statusClass = status.codeClass();
161             // An informational response using a 1xx status code other than 101 is
162             // transmitted as a HEADERS frame
163             if (statusClass == HttpStatusClass.INFORMATIONAL && code != 101) {
164                 if (res instanceof FullHttpResponse) {
165                     final Http2Headers headers = toHttp2Headers(ctx, res);
166                     out.add(new DefaultHttp2HeadersFrame(headers, false));
167                     return;
168                 } else {
169                     throw new EncoderException(status + " must be a FullHttpResponse");
170                 }
171             }
172         }
173 
174         if (obj instanceof HttpMessage) {
175             Http2Headers headers = toHttp2Headers(ctx, (HttpMessage) obj);
176             boolean noMoreFrames = false;
177             if (obj instanceof FullHttpMessage) {
178                 FullHttpMessage full = (FullHttpMessage) obj;
179                 noMoreFrames = !full.content().isReadable() && full.trailingHeaders().isEmpty();
180             }
181 
182             out.add(new DefaultHttp2HeadersFrame(headers, noMoreFrames));
183         }
184 
185         if (obj instanceof LastHttpContent) {
186             LastHttpContent last = (LastHttpContent) obj;
187             encodeLastContent(last, out);
188         } else if (obj instanceof HttpContent) {
189             HttpContent cont = (HttpContent) obj;
190             out.add(new DefaultHttp2DataFrame(cont.content().retain(), false));
191         }
192     }
193 
194     private Http2Headers toHttp2Headers(final ChannelHandlerContext ctx, final HttpMessage msg) {
195         if (msg instanceof HttpRequest) {
196             msg.headers().set(
197                     HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(),
198                     connectionScheme(ctx));
199         }
200 
201         return HttpConversionUtil.toHttp2Headers(msg, validateHeaders);
202     }
203 
204     private HttpMessage newMessage(final int id,
205                                    final Http2Headers headers) throws Http2Exception {
206         return isServer ?
207                 HttpConversionUtil.toHttpRequest(id, headers, validateHeaders) :
208                 HttpConversionUtil.toHttpResponse(id, headers, validateHeaders);
209     }
210 
211     private FullHttpMessage newFullMessage(final int id,
212                                            final Http2Headers headers,
213                                            final ByteBufAllocator alloc) throws Http2Exception {
214         return isServer ?
215                 HttpConversionUtil.toFullHttpRequest(id, headers, alloc, validateHeaders) :
216                 HttpConversionUtil.toFullHttpResponse(id, headers, alloc, validateHeaders);
217     }
218 
219     @Override
220     public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
221         super.handlerAdded(ctx);
222 
223         // this handler is typically used on an Http2StreamChannel. At this
224         // stage, ssl handshake should've been established. checking for the
225         // presence of SslHandler in the parent's channel pipeline to
226         // determine the HTTP scheme should suffice, even for the case where
227         // SniHandler is used.
228         final Attribute<HttpScheme> schemeAttribute = connectionSchemeAttribute(ctx);
229         if (schemeAttribute.get() == null) {
230             final HttpScheme scheme = isSsl(ctx) ? HttpScheme.HTTPS : HttpScheme.HTTP;
231             schemeAttribute.set(scheme);
232         }
233     }
234 
235     protected boolean isSsl(final ChannelHandlerContext ctx) {
236         final Channel connChannel = connectionChannel(ctx);
237         return null != connChannel.pipeline().get(SslHandler.class);
238     }
239 
240     private static HttpScheme connectionScheme(ChannelHandlerContext ctx) {
241         final HttpScheme scheme = connectionSchemeAttribute(ctx).get();
242         return scheme == null ? HttpScheme.HTTP : scheme;
243     }
244 
245     private static Attribute<HttpScheme> connectionSchemeAttribute(ChannelHandlerContext ctx) {
246         final Channel ch = connectionChannel(ctx);
247         return ch.attr(SCHEME_ATTR_KEY);
248     }
249 
250     private static Channel connectionChannel(ChannelHandlerContext ctx) {
251         final Channel ch = ctx.channel();
252         return ch instanceof Http2StreamChannel ? ch.parent() : ch;
253     }
254 
255     /**
256      *    An informational response using a 1xx status code other than 101 is
257      *    transmitted as a HEADERS frame
258      */
259     private static boolean isInformationalResponseHeaderFrame(CharSequence status) {
260         if (status.length() == 3) {
261             char char0 = status.charAt(0);
262             char char1 = status.charAt(1);
263             char char2 = status.charAt(2);
264             return char0 == '1'
265                 && char1 >= '0' && char1 <= '9'
266                 && char2 >= '0' && char2 <= '9' && char2 != '1';
267         }
268         return false;
269     }
270 
271     /*
272      * https://datatracker.ietf.org/doc/html/rfc9113#section-8.1.1
273      * '204' or '304' responses contain no content
274      */
275     private static boolean isContentAlwaysEmpty(CharSequence status) {
276         if (status.length() == 3) {
277             char char0 = status.charAt(0);
278             char char1 = status.charAt(1);
279             char char2 = status.charAt(2);
280             return (char0 == '2' || char0 == '3')
281                 && char1 == '0'
282                 && char2 == '4';
283         }
284         return false;
285     }
286 }