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 io.netty.handler.codec.http.websocketx;
17  
18  import io.netty.buffer.Unpooled;
19  import io.netty.handler.codec.http.DefaultFullHttpRequest;
20  import io.netty.handler.codec.http.FullHttpRequest;
21  import io.netty.handler.codec.http.FullHttpResponse;
22  import io.netty.handler.codec.http.HttpHeaderNames;
23  import io.netty.handler.codec.http.HttpHeaderValues;
24  import io.netty.handler.codec.http.HttpHeaders;
25  import io.netty.handler.codec.http.HttpMethod;
26  import io.netty.handler.codec.http.HttpResponseStatus;
27  import io.netty.handler.codec.http.HttpVersion;
28  import io.netty.util.CharsetUtil;
29  import io.netty.util.internal.logging.InternalLogger;
30  import io.netty.util.internal.logging.InternalLoggerFactory;
31  
32  import java.net.URI;
33  
34  /**
35   * <p>
36   * Performs client side opening and closing handshakes for web socket specification version <a
37   * href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07" >draft-ietf-hybi-thewebsocketprotocol-
38   * 10</a>
39   * </p>
40   */
41  public class WebSocketClientHandshaker07 extends WebSocketClientHandshaker {
42  
43      private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker07.class);
44      public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
45  
46      private String expectedChallengeResponseString;
47  
48      private final boolean allowExtensions;
49      private final boolean performMasking;
50      private final boolean allowMaskMismatch;
51  
52      /**
53       * Creates a new instance.
54       *
55       * @param webSocketURL
56       *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
57       *            sent to this URL.
58       * @param version
59       *            Version of web socket specification to use to connect to the server
60       * @param subprotocol
61       *            Sub protocol request sent to the server.
62       * @param allowExtensions
63       *            Allow extensions to be used in the reserved bits of the web socket frame
64       * @param customHeaders
65       *            Map of custom headers to add to the client request
66       * @param maxFramePayloadLength
67       *            Maximum length of a frame's payload
68       */
69      public WebSocketClientHandshaker07(URI webSocketURL, WebSocketVersion version, String subprotocol,
70                                         boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength) {
71          this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength, true, false);
72      }
73  
74      /**
75       * Creates a new instance.
76       *
77       * @param webSocketURL
78       *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
79       *            sent to this URL.
80       * @param version
81       *            Version of web socket specification to use to connect to the server
82       * @param subprotocol
83       *            Sub protocol request sent to the server.
84       * @param allowExtensions
85       *            Allow extensions to be used in the reserved bits of the web socket frame
86       * @param customHeaders
87       *            Map of custom headers to add to the client request
88       * @param maxFramePayloadLength
89       *            Maximum length of a frame's payload
90       * @param performMasking
91       *            Whether to mask all written websocket frames. This must be set to true in order to be fully compatible
92       *            with the websocket specifications. Client applications that communicate with a non-standard server
93       *            which doesn't require masking might set this to false to achieve a higher performance.
94       * @param allowMaskMismatch
95       *            When set to true, frames which are not masked properly according to the standard will still be
96       *            accepted.
97       */
98      public WebSocketClientHandshaker07(URI webSocketURL, WebSocketVersion version, String subprotocol,
99                                         boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength,
100                                        boolean performMasking, boolean allowMaskMismatch) {
101         this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength, performMasking,
102                 allowMaskMismatch, DEFAULT_FORCE_CLOSE_TIMEOUT_MILLIS);
103     }
104 
105     /**
106      * Creates a new instance.
107      *
108      * @param webSocketURL
109      *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
110      *            sent to this URL.
111      * @param version
112      *            Version of web socket specification to use to connect to the server
113      * @param subprotocol
114      *            Sub protocol request sent to the server.
115      * @param allowExtensions
116      *            Allow extensions to be used in the reserved bits of the web socket frame
117      * @param customHeaders
118      *            Map of custom headers to add to the client request
119      * @param maxFramePayloadLength
120      *            Maximum length of a frame's payload
121      * @param performMasking
122      *            Whether to mask all written websocket frames. This must be set to true in order to be fully compatible
123      *            with the websocket specifications. Client applications that communicate with a non-standard server
124      *            which doesn't require masking might set this to false to achieve a higher performance.
125      * @param allowMaskMismatch
126      *            When set to true, frames which are not masked properly according to the standard will still be
127      *            accepted
128      * @param forceCloseTimeoutMillis
129      *            Close the connection if it was not closed by the server after timeout specified.
130      */
131     public WebSocketClientHandshaker07(URI webSocketURL, WebSocketVersion version, String subprotocol,
132             boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength,
133             boolean performMasking, boolean allowMaskMismatch, long forceCloseTimeoutMillis) {
134         this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength, performMasking,
135                 allowMaskMismatch, forceCloseTimeoutMillis, false);
136     }
137 
138     /**
139      * Creates a new instance.
140      *
141      * @param webSocketURL
142      *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
143      *            sent to this URL.
144      * @param version
145      *            Version of web socket specification to use to connect to the server
146      * @param subprotocol
147      *            Sub protocol request sent to the server.
148      * @param allowExtensions
149      *            Allow extensions to be used in the reserved bits of the web socket frame
150      * @param customHeaders
151      *            Map of custom headers to add to the client request
152      * @param maxFramePayloadLength
153      *            Maximum length of a frame's payload
154      * @param performMasking
155      *            Whether to mask all written websocket frames. This must be set to true in order to be fully compatible
156      *            with the websocket specifications. Client applications that communicate with a non-standard server
157      *            which doesn't require masking might set this to false to achieve a higher performance.
158      * @param allowMaskMismatch
159      *            When set to true, frames which are not masked properly according to the standard will still be
160      *            accepted
161      * @param forceCloseTimeoutMillis
162      *            Close the connection if it was not closed by the server after timeout specified.
163      * @param  absoluteUpgradeUrl
164      *            Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over
165      *            clear HTTP
166      */
167     WebSocketClientHandshaker07(URI webSocketURL, WebSocketVersion version, String subprotocol,
168                                 boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength,
169                                 boolean performMasking, boolean allowMaskMismatch, long forceCloseTimeoutMillis,
170                                 boolean absoluteUpgradeUrl) {
171         super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength, forceCloseTimeoutMillis,
172                 absoluteUpgradeUrl);
173         this.allowExtensions = allowExtensions;
174         this.performMasking = performMasking;
175         this.allowMaskMismatch = allowMaskMismatch;
176     }
177 
178     /**
179      * /**
180      * <p>
181      * Sends the opening request to the server:
182      * </p>
183      *
184      * <pre>
185      * GET /chat HTTP/1.1
186      * Host: server.example.com
187      * Upgrade: websocket
188      * Connection: Upgrade
189      * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
190      * Sec-WebSocket-Origin: http://example.com
191      * Sec-WebSocket-Protocol: chat, superchat
192      * Sec-WebSocket-Version: 7
193      * </pre>
194      *
195      */
196     @Override
197     protected FullHttpRequest newHandshakeRequest() {
198         URI wsURL = uri();
199 
200         // Get 16 bit nonce and base 64 encode it
201         byte[] nonce = WebSocketUtil.randomBytes(16);
202         String key = WebSocketUtil.base64(nonce);
203 
204         String acceptSeed = key + MAGIC_GUID;
205         byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
206         expectedChallengeResponseString = WebSocketUtil.base64(sha1);
207 
208         if (logger.isDebugEnabled()) {
209             logger.debug(
210                     "WebSocket version 07 client handshake key: {}, expected response: {}",
211                     key, expectedChallengeResponseString);
212         }
213 
214         // Format request
215         FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, upgradeUrl(wsURL),
216                 Unpooled.EMPTY_BUFFER);
217         HttpHeaders headers = request.headers();
218 
219         if (customHeaders != null) {
220             headers.add(customHeaders);
221             if (!headers.contains(HttpHeaderNames.HOST)) {
222                 // Only add HOST header if customHeaders did not contain it.
223                 //
224                 // See https://github.com/netty/netty/issues/10101
225                 headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL));
226             }
227         } else {
228             headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL));
229         }
230 
231         headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
232                .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
233                .set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key);
234 
235         if (!headers.contains(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN)) {
236             headers.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, websocketOriginValue(wsURL));
237         }
238 
239         String expectedSubprotocol = expectedSubprotocol();
240         if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
241             headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
242         }
243 
244         headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, version().toAsciiString());
245         return request;
246     }
247 
248     /**
249      * <p>
250      * Process server response:
251      * </p>
252      *
253      * <pre>
254      * HTTP/1.1 101 Switching Protocols
255      * Upgrade: websocket
256      * Connection: Upgrade
257      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
258      * Sec-WebSocket-Protocol: chat
259      * </pre>
260      *
261      * @param response
262      *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
263      * @throws WebSocketHandshakeException
264      */
265     @Override
266     protected void verify(FullHttpResponse response) {
267         final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
268         final HttpHeaders headers = response.headers();
269 
270         if (!response.status().equals(status)) {
271             throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
272         }
273 
274         CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
275         if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
276             throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
277         }
278 
279         if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
280             throw new WebSocketHandshakeException("Invalid handshake response connection: "
281                     + headers.get(HttpHeaderNames.CONNECTION));
282         }
283 
284         CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
285         if (accept == null || !accept.equals(expectedChallengeResponseString)) {
286             throw new WebSocketHandshakeException(String.format(
287                     "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
288         }
289     }
290 
291     @Override
292     protected WebSocketFrameDecoder newWebsocketDecoder() {
293         return new WebSocket07FrameDecoder(false, allowExtensions, maxFramePayloadLength(), allowMaskMismatch);
294     }
295 
296     @Override
297     protected WebSocketFrameEncoder newWebSocketEncoder() {
298         return new WebSocket07FrameEncoder(performMasking);
299     }
300 
301     @Override
302     public WebSocketClientHandshaker07 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) {
303         super.setForceCloseTimeoutMillis(forceCloseTimeoutMillis);
304         return this;
305     }
306 
307 }