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-07" >draft-ietf-hybi-thewebsocketprotocol-
37   * 10</a>
38   * </p>
39   */
40  public class WebSocketClientHandshaker07 extends WebSocketClientHandshaker {
41  
42      private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker07.class);
43      public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
44  
45      private String expectedChallengeResponseString;
46  
47      private final boolean allowExtensions;
48      private final boolean performMasking;
49      private final boolean allowMaskMismatch;
50  
51      /**
52       * Creates a new instance.
53       *
54       * @param webSocketURL
55       *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
56       *            sent to this URL.
57       * @param version
58       *            Version of web socket specification to use to connect to the server
59       * @param subprotocol
60       *            Sub protocol request sent to the server.
61       * @param allowExtensions
62       *            Allow extensions to be used in the reserved bits of the web socket frame
63       * @param customHeaders
64       *            Map of custom headers to add to the client request
65       * @param maxFramePayloadLength
66       *            Maximum length of a frame's payload
67       */
68      public WebSocketClientHandshaker07(URI webSocketURL, WebSocketVersion version, String subprotocol,
69                                         boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength) {
70          this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength, true, false);
71      }
72  
73      /**
74       * Creates a new instance.
75       *
76       * @param webSocketURL
77       *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
78       *            sent to this URL.
79       * @param version
80       *            Version of web socket specification to use to connect to the server
81       * @param subprotocol
82       *            Sub protocol request sent to the server.
83       * @param allowExtensions
84       *            Allow extensions to be used in the reserved bits of the web socket frame
85       * @param customHeaders
86       *            Map of custom headers to add to the client request
87       * @param maxFramePayloadLength
88       *            Maximum length of a frame's payload
89       * @param performMasking
90       *            Whether to mask all written websocket frames. This must be set to true in order to be fully compatible
91       *            with the websocket specifications. Client applications that communicate with a non-standard server
92       *            which doesn't require masking might set this to false to achieve a higher performance.
93       * @param allowMaskMismatch
94       *            When set to true, frames which are not masked properly according to the standard will still be
95       *            accepted.
96       */
97      public WebSocketClientHandshaker07(URI webSocketURL, WebSocketVersion version, String subprotocol,
98              boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength,
99              boolean performMasking, boolean allowMaskMismatch) {
100         super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength);
101         this.allowExtensions = allowExtensions;
102         this.performMasking = performMasking;
103         this.allowMaskMismatch = allowMaskMismatch;
104     }
105 
106     /**
107      * /**
108      * <p>
109      * Sends the opening request to the server:
110      * </p>
111      *
112      * <pre>
113      * GET /chat HTTP/1.1
114      * Host: server.example.com
115      * Upgrade: websocket
116      * Connection: Upgrade
117      * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
118      * Sec-WebSocket-Origin: http://example.com
119      * Sec-WebSocket-Protocol: chat, superchat
120      * Sec-WebSocket-Version: 7
121      * </pre>
122      *
123      */
124     @Override
125     protected FullHttpRequest newHandshakeRequest() {
126         // Get path
127         URI wsURL = uri();
128         String path = rawPath(wsURL);
129 
130         // Get 16 bit nonce and base 64 encode it
131         byte[] nonce = WebSocketUtil.randomBytes(16);
132         String key = WebSocketUtil.base64(nonce);
133 
134         String acceptSeed = key + MAGIC_GUID;
135         byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
136         expectedChallengeResponseString = WebSocketUtil.base64(sha1);
137 
138         if (logger.isDebugEnabled()) {
139             logger.debug(
140                     "WebSocket version 07 client handshake key: {}, expected response: {}",
141                     key, expectedChallengeResponseString);
142         }
143 
144         // Format request
145         FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
146         HttpHeaders headers = request.headers();
147 
148         if (customHeaders != null) {
149             headers.add(customHeaders);
150         }
151 
152         headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
153                .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
154                .set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key)
155                .set(HttpHeaderNames.HOST, websocketHostValue(wsURL))
156                .set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, websocketOriginValue(wsURL));
157 
158         String expectedSubprotocol = expectedSubprotocol();
159         if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
160             headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
161         }
162 
163         headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "7");
164         return request;
165     }
166 
167     /**
168      * <p>
169      * Process server response:
170      * </p>
171      *
172      * <pre>
173      * HTTP/1.1 101 Switching Protocols
174      * Upgrade: websocket
175      * Connection: Upgrade
176      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
177      * Sec-WebSocket-Protocol: chat
178      * </pre>
179      *
180      * @param response
181      *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
182      * @throws WebSocketHandshakeException
183      */
184     @Override
185     protected void verify(FullHttpResponse response) {
186         final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
187         final HttpHeaders headers = response.headers();
188 
189         if (!response.status().equals(status)) {
190             throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
191         }
192 
193         CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
194         if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
195             throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
196         }
197 
198         if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
199             throw new WebSocketHandshakeException("Invalid handshake response connection: "
200                     + headers.get(HttpHeaderNames.CONNECTION));
201         }
202 
203         CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
204         if (accept == null || !accept.equals(expectedChallengeResponseString)) {
205             throw new WebSocketHandshakeException(String.format(
206                     "Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
207         }
208     }
209 
210     @Override
211     protected WebSocketFrameDecoder newWebsocketDecoder() {
212         return new WebSocket07FrameDecoder(false, allowExtensions, maxFramePayloadLength(), allowMaskMismatch);
213     }
214 
215     @Override
216     protected WebSocketFrameEncoder newWebSocketEncoder() {
217         return new WebSocket07FrameEncoder(performMasking);
218     }
219 }