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