View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License, version 2.0 (the
5    * "License"); you may not use this file except in compliance with the License. You may obtain a
6    * 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 distributed under the License
11   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing permissions and limitations under
13   * the License.
14   */
15  package io.netty.handler.codec.http2;
16  
17  import io.netty.buffer.ByteBuf;
18  import io.netty.buffer.ByteBufUtil;
19  import io.netty.channel.ChannelHandler;
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.handler.codec.base64.Base64;
22  import io.netty.handler.codec.http.FullHttpRequest;
23  import io.netty.handler.codec.http.HttpHeaders;
24  import io.netty.handler.codec.http.HttpServerUpgradeHandler;
25  import io.netty.util.CharsetUtil;
26  import io.netty.util.internal.logging.InternalLogger;
27  import io.netty.util.internal.logging.InternalLoggerFactory;
28  
29  import java.nio.CharBuffer;
30  import java.util.Collection;
31  import java.util.Collections;
32  import java.util.List;
33  
34  import static io.netty.handler.codec.base64.Base64Dialect.URL_SAFE;
35  import static io.netty.handler.codec.http2.Http2CodecUtil.FRAME_HEADER_LENGTH;
36  import static io.netty.handler.codec.http2.Http2CodecUtil.HTTP_UPGRADE_SETTINGS_HEADER;
37  import static io.netty.handler.codec.http2.Http2CodecUtil.writeFrameHeader;
38  import static io.netty.handler.codec.http2.Http2FrameTypes.SETTINGS;
39  
40  /**
41   * Server-side codec for performing a cleartext upgrade from HTTP/1.x to HTTP/2.
42   */
43  public class Http2ServerUpgradeCodec implements HttpServerUpgradeHandler.UpgradeCodec {
44  
45      private static final InternalLogger logger = InternalLoggerFactory.getInstance(Http2ServerUpgradeCodec.class);
46      private static final List<CharSequence> REQUIRED_UPGRADE_HEADERS =
47              Collections.singletonList(HTTP_UPGRADE_SETTINGS_HEADER);
48      private static final ChannelHandler[] EMPTY_HANDLERS = new ChannelHandler[0];
49  
50      private final String handlerName;
51      private final Http2ConnectionHandler connectionHandler;
52      private final ChannelHandler[] handlers;
53      private final Http2FrameReader frameReader;
54  
55      private Http2Settings settings;
56  
57      /**
58       * Creates the codec using a default name for the connection handler when adding to the
59       * pipeline.
60       *
61       * @param connectionHandler the HTTP/2 connection handler
62       */
63      public Http2ServerUpgradeCodec(Http2ConnectionHandler connectionHandler) {
64          this(null, connectionHandler, EMPTY_HANDLERS);
65      }
66  
67      /**
68       * Creates the codec using a default name for the connection handler when adding to the
69       * pipeline.
70       *
71       * @param http2Codec the HTTP/2 multiplexing handler.
72       */
73      public Http2ServerUpgradeCodec(Http2MultiplexCodec http2Codec) {
74          this(null, http2Codec, EMPTY_HANDLERS);
75      }
76  
77      /**
78       * Creates the codec providing an upgrade to the given handler for HTTP/2.
79       *
80       * @param handlerName the name of the HTTP/2 connection handler to be used in the pipeline,
81       *                    or {@code null} to auto-generate the name
82       * @param connectionHandler the HTTP/2 connection handler
83       */
84      public Http2ServerUpgradeCodec(String handlerName, Http2ConnectionHandler connectionHandler) {
85          this(handlerName, connectionHandler, EMPTY_HANDLERS);
86      }
87  
88      /**
89       * Creates the codec providing an upgrade to the given handler for HTTP/2.
90       *
91       * @param handlerName the name of the HTTP/2 connection handler to be used in the pipeline.
92       * @param http2Codec the HTTP/2 multiplexing handler.
93       */
94      public Http2ServerUpgradeCodec(String handlerName, Http2MultiplexCodec http2Codec) {
95          this(handlerName, http2Codec, EMPTY_HANDLERS);
96      }
97  
98      /**
99       * Creates the codec using a default name for the connection handler when adding to the
100      * pipeline.
101      *
102      * @param http2Codec the HTTP/2 frame handler.
103      * @param handlers the handlers that will handle the {@link Http2Frame}s.
104      */
105     public Http2ServerUpgradeCodec(Http2FrameCodec http2Codec, ChannelHandler... handlers) {
106         this(null, http2Codec, handlers);
107     }
108 
109     private Http2ServerUpgradeCodec(String handlerName, Http2ConnectionHandler connectionHandler,
110             ChannelHandler... handlers) {
111         this.handlerName = handlerName;
112         this.connectionHandler = connectionHandler;
113         this.handlers = handlers;
114         frameReader = new DefaultHttp2FrameReader();
115     }
116 
117     @Override
118     public Collection<CharSequence> requiredUpgradeHeaders() {
119         return REQUIRED_UPGRADE_HEADERS;
120     }
121 
122     @Override
123     public boolean prepareUpgradeResponse(ChannelHandlerContext ctx, FullHttpRequest upgradeRequest,
124             HttpHeaders headers) {
125         try {
126             // Decode the HTTP2-Settings header and set the settings on the handler to make
127             // sure everything is fine with the request.
128             List<String> upgradeHeaders = upgradeRequest.headers().getAll(HTTP_UPGRADE_SETTINGS_HEADER);
129             if (upgradeHeaders.size() != 1) {
130                 throw new IllegalArgumentException("There must be 1 and only 1 "
131                         + HTTP_UPGRADE_SETTINGS_HEADER + " header.");
132             }
133             settings = decodeSettingsHeader(ctx, upgradeHeaders.get(0));
134             // Everything looks good.
135             return true;
136         } catch (Throwable cause) {
137             logger.info("Error during upgrade to HTTP/2", cause);
138             return false;
139         }
140     }
141 
142     @Override
143     public void upgradeTo(final ChannelHandlerContext ctx, FullHttpRequest upgradeRequest) {
144         try {
145             // Add the HTTP/2 connection handler to the pipeline immediately following the current handler.
146             ctx.pipeline().addAfter(ctx.name(), handlerName, connectionHandler);
147 
148             // Add also all extra handlers as these may handle events / messages produced by the connectionHandler.
149             // See https://github.com/netty/netty/issues/9314
150             if (handlers != null) {
151                 final String name = ctx.pipeline().context(connectionHandler).name();
152                 for (int i = handlers.length - 1; i >= 0; i--) {
153                     ctx.pipeline().addAfter(name, null, handlers[i]);
154                 }
155             }
156             connectionHandler.onHttpServerUpgrade(settings);
157         } catch (Http2Exception e) {
158             ctx.fireExceptionCaught(e);
159             ctx.close();
160         }
161     }
162 
163     /**
164      * Decodes the settings header and returns a {@link Http2Settings} object.
165      */
166     private Http2Settings decodeSettingsHeader(ChannelHandlerContext ctx, CharSequence settingsHeader)
167             throws Http2Exception {
168         ByteBuf header = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(settingsHeader), CharsetUtil.UTF_8);
169         try {
170             // Decode the SETTINGS payload.
171             ByteBuf payload = Base64.decode(header, URL_SAFE);
172 
173             // Create an HTTP/2 frame for the settings.
174             ByteBuf frame = createSettingsFrame(ctx, payload);
175 
176             // Decode the SETTINGS frame and return the settings object.
177             return decodeSettings(ctx, frame);
178         } finally {
179             header.release();
180         }
181     }
182 
183     /**
184      * Decodes the settings frame and returns the settings.
185      */
186     private Http2Settings decodeSettings(ChannelHandlerContext ctx, ByteBuf frame) throws Http2Exception {
187         try {
188             final Http2Settings decodedSettings = new Http2Settings();
189             frameReader.readFrame(ctx, frame, new Http2FrameAdapter() {
190                 @Override
191                 public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) {
192                     decodedSettings.copyFrom(settings);
193                 }
194             });
195             return decodedSettings;
196         } finally {
197             frame.release();
198         }
199     }
200 
201     /**
202      * Creates an HTTP2-Settings header with the given payload. The payload buffer is released.
203      */
204     private static ByteBuf createSettingsFrame(ChannelHandlerContext ctx, ByteBuf payload) {
205         ByteBuf frame = ctx.alloc().buffer(FRAME_HEADER_LENGTH + payload.readableBytes());
206         writeFrameHeader(frame, payload.readableBytes(), SETTINGS, new Http2Flags(), 0);
207         frame.writeBytes(payload);
208         payload.release();
209         return frame;
210     }
211 }