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