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.http;
16  
17  import static io.netty.util.AsciiString.containsContentEqualsIgnoreCase;
18  import static io.netty.util.AsciiString.containsAllContentEqualsIgnoreCase;
19  
20  import io.netty.buffer.Unpooled;
21  import io.netty.channel.ChannelFuture;
22  import io.netty.channel.ChannelFutureListener;
23  import io.netty.channel.ChannelHandlerContext;
24  import io.netty.util.ReferenceCountUtil;
25  import io.netty.util.ReferenceCounted;
26  
27  import java.util.ArrayList;
28  import java.util.Collection;
29  import java.util.List;
30  
31  import static io.netty.handler.codec.http.HttpResponseStatus.SWITCHING_PROTOCOLS;
32  import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
33  import static io.netty.util.internal.ObjectUtil.checkNotNull;
34  
35  /**
36   * A server-side handler that receives HTTP requests and optionally performs a protocol switch if
37   * the requested protocol is supported. Once an upgrade is performed, this handler removes itself
38   * from the pipeline.
39   */
40  public class HttpServerUpgradeHandler extends HttpObjectAggregator {
41  
42      /**
43       * The source codec that is used in the pipeline initially.
44       */
45      public interface SourceCodec {
46          /**
47           * Removes this codec (i.e. all associated handlers) from the pipeline.
48           */
49          void upgradeFrom(ChannelHandlerContext ctx);
50      }
51  
52      /**
53       * A codec that the source can be upgraded to.
54       */
55      public interface UpgradeCodec {
56          /**
57           * Gets all protocol-specific headers required by this protocol for a successful upgrade.
58           * Any supplied header will be required to appear in the {@link HttpHeaderNames#CONNECTION} header as well.
59           */
60          Collection<CharSequence> requiredUpgradeHeaders();
61  
62          /**
63           * Prepares the {@code upgradeHeaders} for a protocol update based upon the contents of {@code upgradeRequest}.
64           * This method returns a boolean value to proceed or abort the upgrade in progress. If {@code false} is
65           * returned, the upgrade is aborted and the {@code upgradeRequest} will be passed through the inbound pipeline
66           * as if no upgrade was performed. If {@code true} is returned, the upgrade will proceed to the next
67           * step which invokes {@link #upgradeTo}. When returning {@code true}, you can add headers to
68           * the {@code upgradeHeaders} so that they are added to the 101 Switching protocols response.
69           */
70          boolean prepareUpgradeResponse(ChannelHandlerContext ctx, FullHttpRequest upgradeRequest,
71                                      HttpHeaders upgradeHeaders);
72  
73          /**
74           * Performs an HTTP protocol upgrade from the source codec. This method is responsible for
75           * adding all handlers required for the new protocol.
76           *
77           * @param ctx the context for the current handler.
78           * @param upgradeRequest the request that triggered the upgrade to this protocol.
79           */
80          void upgradeTo(ChannelHandlerContext ctx, FullHttpRequest upgradeRequest);
81      }
82  
83      /**
84       * Creates a new {@link UpgradeCodec} for the requested protocol name.
85       */
86      public interface UpgradeCodecFactory {
87          /**
88           * Invoked by {@link HttpServerUpgradeHandler} for all the requested protocol names in the order of
89           * the client preference. The first non-{@code null} {@link UpgradeCodec} returned by this method
90           * will be selected.
91           *
92           * @return a new {@link UpgradeCodec}, or {@code null} if the specified protocol name is not supported
93           */
94          UpgradeCodec newUpgradeCodec(CharSequence protocol);
95      }
96  
97      /**
98       * User event that is fired to notify about the completion of an HTTP upgrade
99       * to another protocol. Contains the original upgrade request so that the response
100      * (if required) can be sent using the new protocol.
101      */
102     public static final class UpgradeEvent implements ReferenceCounted {
103         private final CharSequence protocol;
104         private final FullHttpRequest upgradeRequest;
105 
106         UpgradeEvent(CharSequence protocol, FullHttpRequest upgradeRequest) {
107             this.protocol = protocol;
108             this.upgradeRequest = upgradeRequest;
109         }
110 
111         /**
112          * The protocol that the channel has been upgraded to.
113          */
114         public CharSequence protocol() {
115             return protocol;
116         }
117 
118         /**
119          * Gets the request that triggered the protocol upgrade.
120          */
121         public FullHttpRequest upgradeRequest() {
122             return upgradeRequest;
123         }
124 
125         @Override
126         public int refCnt() {
127             return upgradeRequest.refCnt();
128         }
129 
130         @Override
131         public UpgradeEvent retain() {
132             upgradeRequest.retain();
133             return this;
134         }
135 
136         @Override
137         public UpgradeEvent retain(int increment) {
138             upgradeRequest.retain(increment);
139             return this;
140         }
141 
142         @Override
143         public UpgradeEvent touch() {
144             upgradeRequest.touch();
145             return this;
146         }
147 
148         @Override
149         public UpgradeEvent touch(Object hint) {
150             upgradeRequest.touch(hint);
151             return this;
152         }
153 
154         @Override
155         public boolean release() {
156             return upgradeRequest.release();
157         }
158 
159         @Override
160         public boolean release(int decrement) {
161             return upgradeRequest.release(decrement);
162         }
163 
164         @Override
165         public String toString() {
166             return "UpgradeEvent [protocol=" + protocol + ", upgradeRequest=" + upgradeRequest + ']';
167         }
168     }
169 
170     private final SourceCodec sourceCodec;
171     private final UpgradeCodecFactory upgradeCodecFactory;
172     private boolean handlingUpgrade;
173 
174     /**
175      * Constructs the upgrader with the supported codecs.
176      * <p>
177      * The handler instantiated by this constructor will reject an upgrade request with non-empty content.
178      * It should not be a concern because an upgrade request is most likely a GET request.
179      * If you have a client that sends a non-GET upgrade request, please consider using
180      * {@link #HttpServerUpgradeHandler(SourceCodec, UpgradeCodecFactory, int)} to specify the maximum
181      * length of the content of an upgrade request.
182      * </p>
183      *
184      * @param sourceCodec the codec that is being used initially
185      * @param upgradeCodecFactory the factory that creates a new upgrade codec
186      *                            for one of the requested upgrade protocols
187      */
188     public HttpServerUpgradeHandler(SourceCodec sourceCodec, UpgradeCodecFactory upgradeCodecFactory) {
189         this(sourceCodec, upgradeCodecFactory, 0);
190     }
191 
192     /**
193      * Constructs the upgrader with the supported codecs.
194      *
195      * @param sourceCodec the codec that is being used initially
196      * @param upgradeCodecFactory the factory that creates a new upgrade codec
197      *                            for one of the requested upgrade protocols
198      * @param maxContentLength the maximum length of the content of an upgrade request
199      */
200     public HttpServerUpgradeHandler(
201             SourceCodec sourceCodec, UpgradeCodecFactory upgradeCodecFactory, int maxContentLength) {
202         super(maxContentLength);
203 
204         this.sourceCodec = checkNotNull(sourceCodec, "sourceCodec");
205         this.upgradeCodecFactory = checkNotNull(upgradeCodecFactory, "upgradeCodecFactory");
206     }
207 
208     @Override
209     protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out)
210             throws Exception {
211         // Determine if we're already handling an upgrade request or just starting a new one.
212         handlingUpgrade |= isUpgradeRequest(msg);
213         if (!handlingUpgrade) {
214             // Not handling an upgrade request, just pass it to the next handler.
215             ReferenceCountUtil.retain(msg);
216             out.add(msg);
217             return;
218         }
219 
220         FullHttpRequest fullRequest;
221         if (msg instanceof FullHttpRequest) {
222             fullRequest = (FullHttpRequest) msg;
223             ReferenceCountUtil.retain(msg);
224             out.add(msg);
225         } else {
226             // Call the base class to handle the aggregation of the full request.
227             super.decode(ctx, msg, out);
228             if (out.isEmpty()) {
229                 // The full request hasn't been created yet, still awaiting more data.
230                 return;
231             }
232 
233             // Finished aggregating the full request, get it from the output list.
234             assert out.size() == 1;
235             handlingUpgrade = false;
236             fullRequest = (FullHttpRequest) out.get(0);
237         }
238 
239         if (upgrade(ctx, fullRequest)) {
240             // The upgrade was successful, remove the message from the output list
241             // so that it's not propagated to the next handler. This request will
242             // be propagated as a user event instead.
243             out.clear();
244         }
245 
246         // The upgrade did not succeed, just allow the full request to propagate to the
247         // next handler.
248     }
249 
250     /**
251      * Determines whether or not the message is an HTTP upgrade request.
252      */
253     private static boolean isUpgradeRequest(HttpObject msg) {
254         return msg instanceof HttpRequest && ((HttpRequest) msg).headers().get(HttpHeaderNames.UPGRADE) != null;
255     }
256 
257     /**
258      * Attempts to upgrade to the protocol(s) identified by the {@link HttpHeaderNames#UPGRADE} header (if provided
259      * in the request).
260      *
261      * @param ctx the context for this handler.
262      * @param request the HTTP request.
263      * @return {@code true} if the upgrade occurred, otherwise {@code false}.
264      */
265     private boolean upgrade(final ChannelHandlerContext ctx, final FullHttpRequest request) {
266         // Select the best protocol based on those requested in the UPGRADE header.
267         final List<CharSequence> requestedProtocols = splitHeader(request.headers().get(HttpHeaderNames.UPGRADE));
268         final int numRequestedProtocols = requestedProtocols.size();
269         UpgradeCodec upgradeCodec = null;
270         CharSequence upgradeProtocol = null;
271         for (int i = 0; i < numRequestedProtocols; i ++) {
272             final CharSequence p = requestedProtocols.get(i);
273             final UpgradeCodec c = upgradeCodecFactory.newUpgradeCodec(p);
274             if (c != null) {
275                 upgradeProtocol = p;
276                 upgradeCodec = c;
277                 break;
278             }
279         }
280 
281         if (upgradeCodec == null) {
282             // None of the requested protocols are supported, don't upgrade.
283             return false;
284         }
285 
286         // Make sure the CONNECTION header is present.
287         CharSequence connectionHeader = request.headers().get(HttpHeaderNames.CONNECTION);
288         if (connectionHeader == null) {
289             return false;
290         }
291 
292         // Make sure the CONNECTION header contains UPGRADE as well as all protocol-specific headers.
293         Collection<CharSequence> requiredHeaders = upgradeCodec.requiredUpgradeHeaders();
294         List<CharSequence> values = splitHeader(connectionHeader);
295         if (!containsContentEqualsIgnoreCase(values, HttpHeaderNames.UPGRADE) ||
296             !containsAllContentEqualsIgnoreCase(values, requiredHeaders)) {
297             return false;
298         }
299 
300         // Ensure that all required protocol-specific headers are found in the request.
301         for (CharSequence requiredHeader : requiredHeaders) {
302             if (!request.headers().contains(requiredHeader)) {
303                 return false;
304             }
305         }
306 
307         // Prepare and send the upgrade response. Wait for this write to complete before upgrading,
308         // since we need the old codec in-place to properly encode the response.
309         final FullHttpResponse upgradeResponse = createUpgradeResponse(upgradeProtocol);
310         if (!upgradeCodec.prepareUpgradeResponse(ctx, request, upgradeResponse.headers())) {
311             return false;
312         }
313 
314         // Create the user event to be fired once the upgrade completes.
315         final UpgradeEvent event = new UpgradeEvent(upgradeProtocol, request);
316 
317         final UpgradeCodec finalUpgradeCodec = upgradeCodec;
318         ctx.writeAndFlush(upgradeResponse).addListener(new ChannelFutureListener() {
319             @Override
320             public void operationComplete(ChannelFuture future) throws Exception {
321                 try {
322                     if (future.isSuccess()) {
323                         // Perform the upgrade to the new protocol.
324                         sourceCodec.upgradeFrom(ctx);
325                         finalUpgradeCodec.upgradeTo(ctx, request);
326 
327                         // Notify that the upgrade has occurred. Retain the event to offset
328                         // the release() in the finally block.
329                         ctx.fireUserEventTriggered(event.retain());
330 
331                         // Remove this handler from the pipeline.
332                         ctx.pipeline().remove(HttpServerUpgradeHandler.this);
333                     } else {
334                         future.channel().close();
335                     }
336                 } finally {
337                     // Release the event if the upgrade event wasn't fired.
338                     event.release();
339                 }
340             }
341         });
342         return true;
343     }
344 
345     /**
346      * Creates the 101 Switching Protocols response message.
347      */
348     private static FullHttpResponse createUpgradeResponse(CharSequence upgradeProtocol) {
349         DefaultFullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS,
350                 Unpooled.EMPTY_BUFFER, false);
351         res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
352         res.headers().add(HttpHeaderNames.UPGRADE, upgradeProtocol);
353         return res;
354     }
355 
356     /**
357      * Splits a comma-separated header value. The returned set is case-insensitive and contains each
358      * part with whitespace removed.
359      */
360     private static List<CharSequence> splitHeader(CharSequence header) {
361         final StringBuilder builder = new StringBuilder(header.length());
362         final List<CharSequence> protocols = new ArrayList<CharSequence>(4);
363         for (int i = 0; i < header.length(); ++i) {
364             char c = header.charAt(i);
365             if (Character.isWhitespace(c)) {
366                 // Don't include any whitespace.
367                 continue;
368             }
369             if (c == ',') {
370                 // Add the string and reset the builder for the next protocol.
371                 protocols.add(builder.toString());
372                 builder.setLength(0);
373             } else {
374                 builder.append(c);
375             }
376         }
377 
378         // Add the last protocol
379         if (builder.length() > 0) {
380             protocols.add(builder.toString());
381         }
382 
383         return protocols;
384     }
385 }