View Javadoc

1   /*
2    * Copyright 2012 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    *   http://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 org.jboss.netty.handler.codec.http.websocketx;
17  
18  import org.jboss.netty.buffer.ChannelBuffer;
19  import org.jboss.netty.buffer.ChannelBuffers;
20  import org.jboss.netty.channel.Channel;
21  import org.jboss.netty.channel.ChannelFuture;
22  import org.jboss.netty.channel.ChannelFutureListener;
23  import org.jboss.netty.channel.ChannelPipeline;
24  import org.jboss.netty.channel.DefaultChannelFuture;
25  import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
26  import org.jboss.netty.handler.codec.http.HttpHeaders.Names;
27  import org.jboss.netty.handler.codec.http.HttpHeaders.Values;
28  import org.jboss.netty.handler.codec.http.HttpMethod;
29  import org.jboss.netty.handler.codec.http.HttpRequest;
30  import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
31  import org.jboss.netty.handler.codec.http.HttpResponse;
32  import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
33  import org.jboss.netty.handler.codec.http.HttpResponseStatus;
34  import org.jboss.netty.handler.codec.http.HttpVersion;
35  import org.jboss.netty.logging.InternalLogger;
36  import org.jboss.netty.logging.InternalLoggerFactory;
37  import org.jboss.netty.util.CharsetUtil;
38  
39  import java.net.URI;
40  import java.util.Map;
41  
42  /**
43   * <p>
44   * Performs client side opening and closing handshakes for web socket specification version <a
45   * href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07" >draft-ietf-hybi-thewebsocketprotocol-
46   * 07</a>
47   * </p>
48   */
49  public class WebSocketClientHandshaker07 extends WebSocketClientHandshaker {
50  
51      private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker07.class);
52  
53      public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
54  
55      private String expectedChallengeResponseString;
56  
57      private final boolean allowExtensions;
58  
59      /**
60       * Creates a new instance.
61       *
62       * @param webSocketURL
63       *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
64       *            sent to this URL.
65       * @param version
66       *            Version of web socket specification to use to connect to the server
67       * @param subprotocol
68       *            Sub protocol request sent to the server.
69       * @param allowExtensions
70       *            Allow extensions to be used in the reserved bits of the web socket frame
71       * @param customHeaders
72       *            Map of custom headers to add to the client request
73       * @param maxFramePayloadLength
74       *            Maximum length of a frame's payload
75       */
76      public WebSocketClientHandshaker07(URI webSocketURL, WebSocketVersion version, String subprotocol,
77                                         boolean allowExtensions, Map<String, String> customHeaders,
78                                         long maxFramePayloadLength) {
79          super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength);
80          this.allowExtensions = allowExtensions;
81      }
82  
83      /**
84       * /**
85       * <p>
86       * Sends the opening request to the server:
87       * </p>
88       *
89       * <pre>
90       * GET /chat HTTP/1.1
91       * Host: server.example.com
92       * Upgrade: websocket
93       * Connection: Upgrade
94       * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
95       * Sec-WebSocket-Origin: http://example.com
96       * Sec-WebSocket-Protocol: chat, superchat
97       * Sec-WebSocket-Version: 7
98       * </pre>
99       *
100      * @param channel
101      *            Channel into which we can write our request
102      */
103     @Override
104     public ChannelFuture handshake(Channel channel) {
105         // Get path
106         URI wsURL = getWebSocketUrl();
107         String path = wsURL.getPath();
108         if (wsURL.getQuery() != null && wsURL.getQuery().length() > 0) {
109             path = wsURL.getPath() + '?' + wsURL.getQuery();
110         }
111 
112         if (path == null || path.length() == 0) {
113             path = "/";
114         }
115 
116         // Get 16 bit nonce and base 64 encode it
117         byte[] nonce = WebSocketUtil.randomBytes(16);
118         String key = WebSocketUtil.base64(ChannelBuffers.wrappedBuffer(nonce));
119 
120         String acceptSeed = key + MAGIC_GUID;
121         ChannelBuffer sha1 = WebSocketUtil.sha1(ChannelBuffers.copiedBuffer(acceptSeed, CharsetUtil.US_ASCII));
122         expectedChallengeResponseString = WebSocketUtil.base64(sha1);
123 
124         if (logger.isDebugEnabled()) {
125             logger.debug(String.format("WS Version 07 Client Handshake key: %s. Expected response: %s.", key,
126                     expectedChallengeResponseString));
127         }
128 
129         // Format request
130         HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
131         request.addHeader(Names.UPGRADE, Values.WEBSOCKET.toLowerCase());
132         request.addHeader(Names.CONNECTION, Values.UPGRADE);
133         request.addHeader(Names.SEC_WEBSOCKET_KEY, key);
134         request.addHeader(Names.HOST, wsURL.getHost());
135 
136         int wsPort = wsURL.getPort();
137         String originValue = "http://" + wsURL.getHost();
138         if (wsPort != 80 && wsPort != 443) {
139             // if the port is not standard (80/443) its needed to add the port to the header.
140             // See http://tools.ietf.org/html/rfc6454#section-6.2
141             originValue = originValue + ':' + wsPort;
142         }
143         request.addHeader(Names.SEC_WEBSOCKET_ORIGIN, originValue);
144 
145         String expectedSubprotocol = getExpectedSubprotocol();
146         if (expectedSubprotocol != null && expectedSubprotocol.length() > 0) {
147             request.addHeader(Names.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
148         }
149 
150         request.addHeader(Names.SEC_WEBSOCKET_VERSION, "7");
151 
152         if (customHeaders != null) {
153             for (Map.Entry<String, String> e : customHeaders.entrySet()) {
154                 request.addHeader(e.getKey(), e.getValue());
155             }
156         }
157 
158         final ChannelFuture handshakeFuture = new DefaultChannelFuture(channel, false);
159         ChannelFuture future = channel.write(request);
160         future.addListener(new ChannelFutureListener() {
161 
162             public void operationComplete(ChannelFuture future) {
163                 ChannelPipeline p = future.getChannel().getPipeline();
164                 p.addAfter(
165                         p.getContext(HttpRequestEncoder.class).getName(),
166                         "ws-encoder", new WebSocket07FrameEncoder(true));
167 
168                 if (future.isSuccess()) {
169                     handshakeFuture.setSuccess();
170                 } else {
171                     handshakeFuture.setFailure(future.getCause());
172                 }
173             }
174         });
175 
176         return handshakeFuture;
177     }
178 
179     /**
180      * <p>
181      * Process server response:
182      * </p>
183      *
184      * <pre>
185      * HTTP/1.1 101 Switching Protocols
186      * Upgrade: websocket
187      * Connection: Upgrade
188      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
189      * Sec-WebSocket-Protocol: chat
190      * </pre>
191      *
192      * @param channel
193      *            Channel
194      * @param response
195      *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
196      * @throws WebSocketHandshakeException
197      */
198     @Override
199     public void finishHandshake(Channel channel, HttpResponse response) {
200         final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
201 
202         if (!response.getStatus().equals(status)) {
203             throw new WebSocketHandshakeException("Invalid handshake response status: " + response.getStatus());
204         }
205 
206         String upgrade = response.getHeader(Names.UPGRADE);
207         if (!Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
208             throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
209                     + response.getHeader(Names.UPGRADE));
210         }
211 
212         String connection = response.getHeader(Names.CONNECTION);
213         if (!Values.UPGRADE.equalsIgnoreCase(connection)) {
214             throw new WebSocketHandshakeException("Invalid handshake response connection: "
215                     + response.getHeader(Names.CONNECTION));
216         }
217 
218         String accept = response.getHeader(Names.SEC_WEBSOCKET_ACCEPT);
219         if (accept == null || !accept.equals(expectedChallengeResponseString)) {
220             throw new WebSocketHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept,
221                     expectedChallengeResponseString));
222         }
223 
224         String subprotocol = response.getHeader(Names.SEC_WEBSOCKET_PROTOCOL);
225         setActualSubprotocol(subprotocol);
226 
227         setHandshakeComplete();
228 
229         ChannelPipeline p = channel.getPipeline();
230         p.get(HttpResponseDecoder.class).replace(
231                 "ws-decoder",
232                 new WebSocket07FrameDecoder(false, allowExtensions, getMaxFramePayloadLength()));
233     }
234 }