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