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.http;
16  
17  import io.netty.buffer.Unpooled;
18  import io.netty.channel.ChannelFuture;
19  import io.netty.channel.ChannelFutureListener;
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.util.ReferenceCountUtil;
22  import io.netty.util.ReferenceCounted;
23  
24  import java.util.ArrayList;
25  import java.util.Collection;
26  import java.util.List;
27  
28  import static io.netty.handler.codec.http.HttpResponseStatus.SWITCHING_PROTOCOLS;
29  import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
30  import static io.netty.util.AsciiString.containsAllContentEqualsIgnoreCase;
31  import static io.netty.util.AsciiString.containsContentEqualsIgnoreCase;
32  import static io.netty.util.internal.ObjectUtil.checkNotNull;
33  import static io.netty.util.internal.StringUtil.COMMA;
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 final boolean validateHeaders;
173     private boolean handlingUpgrade;
174 
175     /**
176      * Constructs the upgrader with the supported codecs.
177      * <p>
178      * The handler instantiated by this constructor will reject an upgrade request with non-empty content.
179      * It should not be a concern because an upgrade request is most likely a GET request.
180      * If you have a client that sends a non-GET upgrade request, please consider using
181      * {@link #HttpServerUpgradeHandler(SourceCodec, UpgradeCodecFactory, int)} to specify the maximum
182      * length of the content of an upgrade request.
183      * </p>
184      *
185      * @param sourceCodec the codec that is being used initially
186      * @param upgradeCodecFactory the factory that creates a new upgrade codec
187      *                            for one of the requested upgrade protocols
188      */
189     public HttpServerUpgradeHandler(SourceCodec sourceCodec, UpgradeCodecFactory upgradeCodecFactory) {
190         this(sourceCodec, upgradeCodecFactory, 0);
191     }
192 
193     /**
194      * Constructs the upgrader with the supported codecs.
195      *
196      * @param sourceCodec the codec that is being used initially
197      * @param upgradeCodecFactory the factory that creates a new upgrade codec
198      *                            for one of the requested upgrade protocols
199      * @param maxContentLength the maximum length of the content of an upgrade request
200      */
201     public HttpServerUpgradeHandler(
202             SourceCodec sourceCodec, UpgradeCodecFactory upgradeCodecFactory, int maxContentLength) {
203         this(sourceCodec, upgradeCodecFactory, maxContentLength, true);
204     }
205 
206     /**
207      * Constructs the upgrader with the supported codecs.
208      *
209      * @param sourceCodec the codec that is being used initially
210      * @param upgradeCodecFactory the factory that creates a new upgrade codec
211      *                            for one of the requested upgrade protocols
212      * @param maxContentLength the maximum length of the content of an upgrade request
213      * @param validateHeaders validate the header names and values of the upgrade response.
214      */
215     public HttpServerUpgradeHandler(SourceCodec sourceCodec, UpgradeCodecFactory upgradeCodecFactory,
216                                     int maxContentLength, boolean validateHeaders) {
217         super(maxContentLength);
218 
219         this.sourceCodec = checkNotNull(sourceCodec, "sourceCodec");
220         this.upgradeCodecFactory = checkNotNull(upgradeCodecFactory, "upgradeCodecFactory");
221         this.validateHeaders = validateHeaders;
222     }
223 
224     @Override
225     protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out)
226             throws Exception {
227 
228         if (!handlingUpgrade) {
229             // Not handling an upgrade request yet. Check if we received a new upgrade request.
230             if (msg instanceof HttpRequest) {
231                 HttpRequest req = (HttpRequest) msg;
232                 if (req.headers().contains(HttpHeaderNames.UPGRADE) &&
233                     shouldHandleUpgradeRequest(req)) {
234                     handlingUpgrade = true;
235                 } else {
236                     ReferenceCountUtil.retain(msg);
237                     ctx.fireChannelRead(msg);
238                     return;
239                 }
240             } else {
241                 ReferenceCountUtil.retain(msg);
242                 ctx.fireChannelRead(msg);
243                 return;
244             }
245         }
246 
247         FullHttpRequest fullRequest;
248         if (msg instanceof FullHttpRequest) {
249             fullRequest = (FullHttpRequest) msg;
250             ReferenceCountUtil.retain(msg);
251             out.add(msg);
252         } else {
253             // Call the base class to handle the aggregation of the full request.
254             super.decode(ctx, msg, out);
255             if (out.isEmpty()) {
256                 // The full request hasn't been created yet, still awaiting more data.
257                 return;
258             }
259 
260             // Finished aggregating the full request, get it from the output list.
261             assert out.size() == 1;
262             handlingUpgrade = false;
263             fullRequest = (FullHttpRequest) out.get(0);
264         }
265 
266         if (upgrade(ctx, fullRequest)) {
267             // The upgrade was successful, remove the message from the output list
268             // so that it's not propagated to the next handler. This request will
269             // be propagated as a user event instead.
270             out.clear();
271         }
272 
273         // The upgrade did not succeed, just allow the full request to propagate to the
274         // next handler.
275     }
276 
277     /**
278      * Determines whether the specified upgrade {@link HttpRequest} should be handled by this handler or not.
279      * This method will be invoked only when the request contains an {@code Upgrade} header.
280      * It always returns {@code true} by default, which means any request with an {@code Upgrade} header
281      * will be handled. You can override this method to ignore certain {@code Upgrade} headers, for example:
282      * <pre>{@code
283      * @Override
284      * protected boolean isUpgradeRequest(HttpRequest req) {
285      *   // Do not handle WebSocket upgrades.
286      *   return !req.headers().contains(HttpHeaderNames.UPGRADE, "websocket", false);
287      * }
288      * }</pre>
289      */
290     protected boolean shouldHandleUpgradeRequest(HttpRequest req) {
291         return true;
292     }
293 
294     /**
295      * Attempts to upgrade to the protocol(s) identified by the {@link HttpHeaderNames#UPGRADE} header (if provided
296      * in the request).
297      *
298      * @param ctx the context for this handler.
299      * @param request the HTTP request.
300      * @return {@code true} if the upgrade occurred, otherwise {@code false}.
301      */
302     private boolean upgrade(final ChannelHandlerContext ctx, final FullHttpRequest request) {
303         // Select the best protocol based on those requested in the UPGRADE header.
304         final List<CharSequence> requestedProtocols = splitHeader(request.headers().get(HttpHeaderNames.UPGRADE));
305         final int numRequestedProtocols = requestedProtocols.size();
306         UpgradeCodec upgradeCodec = null;
307         CharSequence upgradeProtocol = null;
308         for (int i = 0; i < numRequestedProtocols; i ++) {
309             final CharSequence p = requestedProtocols.get(i);
310             final UpgradeCodec c = upgradeCodecFactory.newUpgradeCodec(p);
311             if (c != null) {
312                 upgradeProtocol = p;
313                 upgradeCodec = c;
314                 break;
315             }
316         }
317 
318         if (upgradeCodec == null) {
319             // None of the requested protocols are supported, don't upgrade.
320             return false;
321         }
322 
323         // Make sure the CONNECTION header is present.
324         List<String> connectionHeaderValues = request.headers().getAll(HttpHeaderNames.CONNECTION);
325 
326         if (connectionHeaderValues == null || connectionHeaderValues.isEmpty()) {
327             return false;
328         }
329 
330         final StringBuilder concatenatedConnectionValue = new StringBuilder(connectionHeaderValues.size() * 10);
331         for (CharSequence connectionHeaderValue : connectionHeaderValues) {
332             concatenatedConnectionValue.append(connectionHeaderValue).append(COMMA);
333         }
334         concatenatedConnectionValue.setLength(concatenatedConnectionValue.length() - 1);
335 
336         // Make sure the CONNECTION header contains UPGRADE as well as all protocol-specific headers.
337         Collection<CharSequence> requiredHeaders = upgradeCodec.requiredUpgradeHeaders();
338         List<CharSequence> values = splitHeader(concatenatedConnectionValue);
339         if (!containsContentEqualsIgnoreCase(values, HttpHeaderNames.UPGRADE) ||
340                 !containsAllContentEqualsIgnoreCase(values, requiredHeaders)) {
341             return false;
342         }
343 
344         // Ensure that all required protocol-specific headers are found in the request.
345         for (CharSequence requiredHeader : requiredHeaders) {
346             if (!request.headers().contains(requiredHeader)) {
347                 return false;
348             }
349         }
350 
351         // Prepare and send the upgrade response. Wait for this write to complete before upgrading,
352         // since we need the old codec in-place to properly encode the response.
353         final FullHttpResponse upgradeResponse = createUpgradeResponse(upgradeProtocol);
354         if (!upgradeCodec.prepareUpgradeResponse(ctx, request, upgradeResponse.headers())) {
355             return false;
356         }
357 
358         // Create the user event to be fired once the upgrade completes.
359         final UpgradeEvent event = new UpgradeEvent(upgradeProtocol, request);
360 
361         // After writing the upgrade response we immediately prepare the
362         // pipeline for the next protocol to avoid a race between completion
363         // of the write future and receiving data before the pipeline is
364         // restructured.
365         try {
366             final ChannelFuture writeComplete = ctx.writeAndFlush(upgradeResponse);
367             // Perform the upgrade to the new protocol.
368             sourceCodec.upgradeFrom(ctx);
369             upgradeCodec.upgradeTo(ctx, request);
370 
371             // Remove this handler from the pipeline.
372             ctx.pipeline().remove(HttpServerUpgradeHandler.this);
373 
374             // Notify that the upgrade has occurred. Retain the event to offset
375             // the release() in the finally block.
376             ctx.fireUserEventTriggered(event.retain());
377 
378             // Add the listener last to avoid firing upgrade logic after
379             // the channel is already closed since the listener may fire
380             // immediately if the write failed eagerly.
381             writeComplete.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
382         } finally {
383             // Release the event if the upgrade event wasn't fired.
384             event.release();
385         }
386         return true;
387     }
388 
389     /**
390      * Creates the 101 Switching Protocols response message.
391      */
392     private FullHttpResponse createUpgradeResponse(CharSequence upgradeProtocol) {
393         DefaultFullHttpResponse res = new DefaultFullHttpResponse(
394                 HTTP_1_1, SWITCHING_PROTOCOLS, Unpooled.EMPTY_BUFFER, validateHeaders);
395         res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
396         res.headers().add(HttpHeaderNames.UPGRADE, upgradeProtocol);
397         return res;
398     }
399 
400     /**
401      * Splits a comma-separated header value. The returned set is case-insensitive and contains each
402      * part with whitespace removed.
403      */
404     private static List<CharSequence> splitHeader(CharSequence header) {
405         final StringBuilder builder = new StringBuilder(header.length());
406         final List<CharSequence> protocols = new ArrayList<CharSequence>(4);
407         for (int i = 0; i < header.length(); ++i) {
408             char c = header.charAt(i);
409             if (Character.isWhitespace(c)) {
410                 // Don't include any whitespace.
411                 continue;
412             }
413             if (c == ',') {
414                 // Add the string and reset the builder for the next protocol.
415                 protocols.add(builder.toString());
416                 builder.setLength(0);
417             } else {
418                 builder.append(c);
419             }
420         }
421 
422         // Add the last protocol
423         if (builder.length() > 0) {
424             protocols.add(builder.toString());
425         }
426 
427         return protocols;
428     }
429 }