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