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.handler.codec.http.DefaultFullHttpRequest;
19  import io.netty.handler.codec.http.FullHttpRequest;
20  import io.netty.handler.codec.http.FullHttpResponse;
21  import io.netty.handler.codec.http.HttpHeaderNames;
22  import io.netty.handler.codec.http.HttpHeaderValues;
23  import io.netty.handler.codec.http.HttpHeaders;
24  import io.netty.handler.codec.http.HttpMethod;
25  import io.netty.handler.codec.http.HttpResponseStatus;
26  import io.netty.handler.codec.http.HttpVersion;
27  import io.netty.util.CharsetUtil;
28  import io.netty.util.internal.logging.InternalLogger;
29  import io.netty.util.internal.logging.InternalLoggerFactory;
30  
31  import java.net.URI;
32  
33  /**
34   * <p>
35   * Performs client side opening and closing handshakes for web socket specification version <a
36   * href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10" >draft-ietf-hybi-thewebsocketprotocol-
37   * 10</a>
38   * </p>
39   */
40  public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
41  
42      private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker08.class);
43  
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 WebSocketClientHandshaker08(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       *            Allows to loosen the masking requirement on received frames. When this is set to false then also
96       *            frames which are not masked properly according to the standard will still be accepted.
97       */
98      public WebSocketClientHandshaker08(URI webSocketURL, WebSocketVersion version, String subprotocol,
99              boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength,
100             boolean performMasking, boolean allowMaskMismatch) {
101         super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength);
102         this.allowExtensions = allowExtensions;
103         this.performMasking = performMasking;
104         this.allowMaskMismatch = allowMaskMismatch;
105     }
106 
107     /**
108      * /**
109      * <p>
110      * Sends the opening request to the server:
111      * </p>
112      *
113      * <pre>
114      * GET /chat HTTP/1.1
115      * Host: server.example.com
116      * Upgrade: websocket
117      * Connection: Upgrade
118      * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
119      * Sec-WebSocket-Origin: http://example.com
120      * Sec-WebSocket-Protocol: chat, superchat
121      * Sec-WebSocket-Version: 8
122      * </pre>
123      *
124      */
125     @Override
126     protected FullHttpRequest newHandshakeRequest() {
127         // Get path
128         URI wsURL = uri();
129         String path = wsURL.getPath();
130         if (wsURL.getQuery() != null && !wsURL.getQuery().isEmpty()) {
131             path = wsURL.getPath() + '?' + wsURL.getQuery();
132         }
133 
134         if (path == null || path.isEmpty()) {
135             path = "/";
136         }
137 
138         // Get 16 bit nonce and base 64 encode it
139         byte[] nonce = WebSocketUtil.randomBytes(16);
140         String key = WebSocketUtil.base64(nonce);
141 
142         String acceptSeed = key + MAGIC_GUID;
143         byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
144         expectedChallengeResponseString = WebSocketUtil.base64(sha1);
145 
146         if (logger.isDebugEnabled()) {
147             logger.debug(
148                     "WebSocket version 08 client handshake key: {}, expected response: {}",
149                     key, expectedChallengeResponseString);
150         }
151 
152         // Format request
153         FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
154         HttpHeaders headers = request.headers();
155 
156         headers.add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
157                .add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
158                .add(HttpHeaderNames.SEC_WEBSOCKET_KEY, key)
159                .add(HttpHeaderNames.HOST, wsURL.getHost());
160 
161         int wsPort = wsURL.getPort();
162         String originValue = "http://" + wsURL.getHost();
163         if (wsPort != 80 && wsPort != 443) {
164             // if the port is not standard (80/443) its needed to add the port to the header.
165             // See http://tools.ietf.org/html/rfc6454#section-6.2
166             originValue = originValue + ':' + wsPort;
167         }
168         headers.add(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, originValue);
169 
170         String expectedSubprotocol = expectedSubprotocol();
171         if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
172             headers.add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
173         }
174 
175         headers.add(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "8");
176 
177         if (customHeaders != null) {
178             headers.add(customHeaders);
179         }
180         return request;
181     }
182 
183     /**
184      * <p>
185      * Process server response:
186      * </p>
187      *
188      * <pre>
189      * HTTP/1.1 101 Switching Protocols
190      * Upgrade: websocket
191      * Connection: Upgrade
192      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
193      * Sec-WebSocket-Protocol: chat
194      * </pre>
195      *
196      * @param response
197      *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
198      * @throws WebSocketHandshakeException
199      */
200     @Override
201     protected void verify(FullHttpResponse response) {
202         final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
203         final HttpHeaders headers = response.headers();
204 
205         if (!response.status().equals(status)) {
206             throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
207         }
208 
209         CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
210         if (!HttpHeaderValues.WEBSOCKET.equalsIgnoreCase(upgrade)) {
211             throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
212         }
213 
214         CharSequence connection = headers.get(HttpHeaderNames.CONNECTION);
215         if (!HttpHeaderValues.UPGRADE.equalsIgnoreCase(connection)) {
216             throw new WebSocketHandshakeException("Invalid handshake response connection: " + connection);
217         }
218 
219         CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
220         if (accept == null || !accept.equals(expectedChallengeResponseString)) {
221             throw new WebSocketHandshakeException(String.format(
222                     "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
223         }
224     }
225 
226     @Override
227     protected WebSocketFrameDecoder newWebsocketDecoder() {
228         return new WebSocket08FrameDecoder(false, allowExtensions, maxFramePayloadLength(), allowMaskMismatch);
229     }
230 
231     @Override
232     protected WebSocketFrameEncoder newWebSocketEncoder() {
233         return new WebSocket08FrameEncoder(performMasking);
234     }
235 }