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-10" >draft-ietf-hybi-thewebsocketprotocol-
46   * 10</a>
47   * </p>
48   */
49  public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
50  
51      private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker08.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       * Constructor with default values
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       */
74      public WebSocketClientHandshaker08(URI webSocketURL, WebSocketVersion version, String subprotocol,
75              boolean allowExtensions, Map<String, String> customHeaders) {
76          this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, Long.MAX_VALUE);
77      }
78  
79      /**
80       * Constructor
81       *
82       * @param webSocketURL
83       *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
84       *            sent to this URL.
85       * @param version
86       *            Version of web socket specification to use to connect to the server
87       * @param subprotocol
88       *            Sub protocol request sent to the server.
89       * @param allowExtensions
90       *            Allow extensions to be used in the reserved bits of the web socket frame
91       * @param customHeaders
92       *            Map of custom headers to add to the client request
93       * @param maxFramePayloadLength
94       *            Maximum length of a frame's payload
95       */
96      public WebSocketClientHandshaker08(URI webSocketURL, WebSocketVersion version, String subprotocol,
97              boolean allowExtensions, Map<String, String> customHeaders, long maxFramePayloadLength) {
98          super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength);
99          this.allowExtensions = allowExtensions;
100     }
101 
102 
103     /**
104      * /**
105      * <p>
106      * Sends the opening request to the server:
107      * </p>
108      *
109      * <pre>
110      * GET /chat HTTP/1.1
111      * Host: server.example.com
112      * Upgrade: websocket
113      * Connection: Upgrade
114      * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
115      * Sec-WebSocket-Origin: http://example.com
116      * Sec-WebSocket-Protocol: chat, superchat
117      * Sec-WebSocket-Version: 8
118      * </pre>
119      *
120      * @param channel
121      *            Channel into which we can write our request
122      */
123     @Override
124     public ChannelFuture handshake(Channel channel) throws Exception {
125         // Get path
126         URI wsURL = getWebSocketUrl();
127         String path = wsURL.getPath();
128         if (wsURL.getQuery() != null && wsURL.getQuery().length() > 0) {
129             path = wsURL.getPath() + '?' + wsURL.getQuery();
130         }
131 
132         if (path == null || path.length() == 0) {
133             path = "/";
134         }
135 
136         // Get 16 bit nonce and base 64 encode it
137         ChannelBuffer nonce = ChannelBuffers.wrappedBuffer(WebSocketUtil.randomBytes(16));
138         String key = WebSocketUtil.base64(nonce);
139 
140         String acceptSeed = key + MAGIC_GUID;
141         ChannelBuffer sha1 = WebSocketUtil.sha1(ChannelBuffers.copiedBuffer(acceptSeed, CharsetUtil.US_ASCII));
142         expectedChallengeResponseString = WebSocketUtil.base64(sha1);
143 
144         if (logger.isDebugEnabled()) {
145             logger.debug(String.format("WS Version 08 Client Handshake key: %s. Expected response: %s.", key,
146                     expectedChallengeResponseString));
147         }
148 
149         // Format request
150         HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
151         request.addHeader(Names.UPGRADE, Values.WEBSOCKET.toLowerCase());
152         request.addHeader(Names.CONNECTION, Values.UPGRADE);
153         request.addHeader(Names.SEC_WEBSOCKET_KEY, key);
154         request.addHeader(Names.HOST, wsURL.getHost());
155 
156         int wsPort = wsURL.getPort();
157         String originValue = "http://" + wsURL.getHost();
158         if (wsPort != 80 && wsPort != 443) {
159             // if the port is not standard (80/443) its needed to add the port to the header.
160             // See http://tools.ietf.org/html/rfc6454#section-6.2
161             originValue = originValue + ':' + wsPort;
162         }
163 
164         // Use Sec-WebSocket-Origin
165         // See https://github.com/netty/netty/issues/264
166         request.addHeader(Names.SEC_WEBSOCKET_ORIGIN, originValue);
167 
168         String expectedSubprotocol = getExpectedSubprotocol();
169         if (expectedSubprotocol != null && expectedSubprotocol.length() != 0) {
170             request.addHeader(Names.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
171         }
172 
173         request.addHeader(Names.SEC_WEBSOCKET_VERSION, "8");
174 
175         if (customHeaders != null) {
176             for (Map.Entry<String, String> e: customHeaders.entrySet()) {
177                 request.addHeader(e.getKey(), e.getValue());
178             }
179         }
180 
181         final ChannelFuture handshakeFuture = new DefaultChannelFuture(channel, false);
182         ChannelFuture future = channel.write(request);
183 
184         future.addListener(new ChannelFutureListener() {
185             public void operationComplete(ChannelFuture future) {
186                 ChannelPipeline p = future.getChannel().getPipeline();
187                 p.replace(HttpRequestEncoder.class, "ws-encoder", new WebSocket08FrameEncoder(true));
188 
189                 if (future.isSuccess()) {
190                     handshakeFuture.setSuccess();
191                 } else {
192                     handshakeFuture.setFailure(future.getCause());
193                 }
194             }
195         });
196 
197         return handshakeFuture;
198     }
199 
200     /**
201      * <p>
202      * Process server response:
203      * </p>
204      *
205      * <pre>
206      * HTTP/1.1 101 Switching Protocols
207      * Upgrade: websocket
208      * Connection: Upgrade
209      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
210      * Sec-WebSocket-Protocol: chat
211      * </pre>
212      *
213      * @param channel
214      *            Channel
215      * @param response
216      *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
217      * @throws WebSocketHandshakeException
218      */
219     @Override
220     public void finishHandshake(Channel channel, HttpResponse response) {
221         final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
222 
223         if (!response.getStatus().equals(status)) {
224             throw new WebSocketHandshakeException("Invalid handshake response status: " + response.getStatus());
225         }
226 
227         String upgrade = response.getHeader(Names.UPGRADE);
228         // Upgrade header should be matched case-insensitive.
229         // See https://github.com/netty/netty/issues/278
230         if (upgrade == null || !upgrade.toLowerCase().equals(Values.WEBSOCKET.toLowerCase())) {
231             throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
232                     + response.getHeader(Names.UPGRADE));
233         }
234 
235         // Connection header should be matched case-insensitive.
236         // See https://github.com/netty/netty/issues/278
237         String connection = response.getHeader(Names.CONNECTION);
238         if (connection == null || !connection.toLowerCase().equals(Values.UPGRADE.toLowerCase())) {
239             throw new WebSocketHandshakeException("Invalid handshake response connection: "
240                     + response.getHeader(Names.CONNECTION));
241         }
242 
243         String accept = response.getHeader(Names.SEC_WEBSOCKET_ACCEPT);
244         if (accept == null || !accept.equals(expectedChallengeResponseString)) {
245             throw new WebSocketHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept,
246                     expectedChallengeResponseString));
247         }
248 
249         String subprotocol = response.getHeader(Names.SEC_WEBSOCKET_PROTOCOL);
250         setActualSubprotocol(subprotocol);
251 
252 
253         setHandshakeComplete();
254 
255         channel.getPipeline().get(HttpResponseDecoder.class).replace("ws-decoder",
256                 new WebSocket08FrameDecoder(false, allowExtensions, getMaxFramePayloadLength()));
257 
258 
259     }
260 }