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       *            When set to true, frames which are not masked properly according to the standard will still be
96       *            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 = rawPath(wsURL);
130 
131         // Get 16 bit nonce and base 64 encode it
132         byte[] nonce = WebSocketUtil.randomBytes(16);
133         String key = WebSocketUtil.base64(nonce);
134 
135         String acceptSeed = key + MAGIC_GUID;
136         byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
137         expectedChallengeResponseString = WebSocketUtil.base64(sha1);
138 
139         if (logger.isDebugEnabled()) {
140             logger.debug(
141                     "WebSocket version 08 client handshake key: {}, expected response: {}",
142                     key, expectedChallengeResponseString);
143         }
144 
145         // Format request
146         FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
147         HttpHeaders headers = request.headers();
148 
149         if (customHeaders != null) {
150             headers.add(customHeaders);
151         }
152 
153         headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
154                .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
155                .set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key)
156                .set(HttpHeaderNames.HOST, websocketHostValue(wsURL))
157                .set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, websocketOriginValue(wsURL));
158 
159         String expectedSubprotocol = expectedSubprotocol();
160         if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
161             headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
162         }
163 
164         headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "8");
165         return request;
166     }
167 
168     /**
169      * <p>
170      * Process server response:
171      * </p>
172      *
173      * <pre>
174      * HTTP/1.1 101 Switching Protocols
175      * Upgrade: websocket
176      * Connection: Upgrade
177      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
178      * Sec-WebSocket-Protocol: chat
179      * </pre>
180      *
181      * @param response
182      *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
183      * @throws WebSocketHandshakeException
184      */
185     @Override
186     protected void verify(FullHttpResponse response) {
187         final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
188         final HttpHeaders headers = response.headers();
189 
190         if (!response.status().equals(status)) {
191             throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
192         }
193 
194         CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
195         if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
196             throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
197         }
198 
199         if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
200             throw new WebSocketHandshakeException("Invalid handshake response connection: "
201                     + headers.get(HttpHeaderNames.CONNECTION));
202         }
203 
204         CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
205         if (accept == null || !accept.equals(expectedChallengeResponseString)) {
206             throw new WebSocketHandshakeException(String.format(
207                     "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
208         }
209     }
210 
211     @Override
212     protected WebSocketFrameDecoder newWebsocketDecoder() {
213         return new WebSocket08FrameDecoder(false, allowExtensions, maxFramePayloadLength(), allowMaskMismatch);
214     }
215 
216     @Override
217     protected WebSocketFrameEncoder newWebSocketEncoder() {
218         return new WebSocket08FrameEncoder(performMasking);
219     }
220 }