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