View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a 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
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec.http.websocketx.extensions;
17  
18  import static io.netty.util.internal.ObjectUtil.checkNonEmpty;
19  
20  import io.netty.channel.ChannelDuplexHandler;
21  import io.netty.channel.ChannelHandlerContext;
22  import io.netty.channel.ChannelPromise;
23  import io.netty.handler.codec.CodecException;
24  import io.netty.handler.codec.http.HttpHeaderNames;
25  import io.netty.handler.codec.http.HttpRequest;
26  import io.netty.handler.codec.http.HttpResponse;
27  import io.netty.util.ReferenceCountUtil;
28  
29  import java.util.ArrayList;
30  import java.util.Arrays;
31  import java.util.Iterator;
32  import java.util.List;
33  
34  /**
35   * This handler negotiates and initializes the WebSocket Extensions.
36   *
37   * This implementation negotiates the extension with the server in a defined order,
38   * ensures that the successfully negotiated extensions are consistent between them,
39   * and initializes the channel pipeline with the extension decoder and encoder.
40   *
41   * Find a basic implementation for compression extensions at
42   * <tt>io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler</tt>.
43   */
44  public class WebSocketClientExtensionHandler extends ChannelDuplexHandler {
45  
46      private final List<WebSocketClientExtensionHandshaker> extensionHandshakers;
47  
48      /**
49       * Constructor
50       *
51       * @param extensionHandshakers
52       *      The extension handshaker in priority order. A handshaker could be repeated many times
53       *      with fallback configuration.
54       */
55      public WebSocketClientExtensionHandler(WebSocketClientExtensionHandshaker... extensionHandshakers) {
56          this.extensionHandshakers = Arrays.asList(checkNonEmpty(extensionHandshakers, "extensionHandshakers"));
57      }
58  
59      @Override
60      public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
61          if (msg instanceof HttpRequest && WebSocketExtensionUtil.isWebsocketUpgrade(((HttpRequest) msg).headers())) {
62              HttpRequest request = (HttpRequest) msg;
63              String headerValue = request.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
64              List<WebSocketExtensionData> extraExtensions =
65                new ArrayList<WebSocketExtensionData>(extensionHandshakers.size());
66              for (WebSocketClientExtensionHandshaker extensionHandshaker : extensionHandshakers) {
67                  extraExtensions.add(extensionHandshaker.newRequestData());
68              }
69              String newHeaderValue = WebSocketExtensionUtil
70                .computeMergeExtensionsHeaderValue(headerValue, extraExtensions);
71  
72              request.headers().set(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS, newHeaderValue);
73          }
74  
75          super.write(ctx, msg, promise);
76      }
77  
78      @Override
79      public void channelRead(ChannelHandlerContext ctx, Object msg)
80              throws Exception {
81          if (msg instanceof HttpResponse) {
82              HttpResponse response = (HttpResponse) msg;
83  
84              if (WebSocketExtensionUtil.isWebsocketUpgrade(response.headers())) {
85                  String extensionsHeader = response.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
86  
87                  if (extensionsHeader != null) {
88                      List<WebSocketExtensionData> extensions =
89                              WebSocketExtensionUtil.extractExtensions(extensionsHeader);
90                      List<WebSocketClientExtension> validExtensions =
91                              new ArrayList<WebSocketClientExtension>(extensions.size());
92                      int rsv = 0;
93  
94                      for (WebSocketExtensionData extensionData : extensions) {
95                          Iterator<WebSocketClientExtensionHandshaker> extensionHandshakersIterator =
96                                  extensionHandshakers.iterator();
97                          WebSocketClientExtension validExtension = null;
98  
99                          while (validExtension == null && extensionHandshakersIterator.hasNext()) {
100                             WebSocketClientExtensionHandshaker extensionHandshaker =
101                                     extensionHandshakersIterator.next();
102                             validExtension = extensionHandshaker.handshakeExtension(extensionData);
103                         }
104 
105                         if (validExtension != null && ((validExtension.rsv() & rsv) == 0)) {
106                             rsv = rsv | validExtension.rsv();
107                             validExtensions.add(validExtension);
108                         } else {
109                             ReferenceCountUtil.release(response);
110                             throw new CodecException(
111                                     "invalid WebSocket Extension handshake for \"" + extensionsHeader + '"');
112                         }
113                     }
114 
115                     for (WebSocketClientExtension validExtension : validExtensions) {
116                         WebSocketExtensionDecoder decoder = validExtension.newExtensionDecoder();
117                         WebSocketExtensionEncoder encoder = validExtension.newExtensionEncoder();
118                         ctx.pipeline().addAfter(ctx.name(), decoder.getClass().getName(), decoder);
119                         ctx.pipeline().addAfter(ctx.name(), encoder.getClass().getName(), encoder);
120                     }
121                 }
122 
123                 ctx.pipeline().remove(ctx.name());
124             }
125         }
126 
127         super.channelRead(ctx, msg);
128     }
129 }
130