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.DefaultFullHttpResponse;
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.HttpResponseStatus;
25  import io.netty.util.CharsetUtil;
26  
27  import static io.netty.handler.codec.http.HttpVersion.*;
28  
29  /**
30   * <p>
31   * Performs server side opening and closing handshakes for <a href="http://netty.io/s/rfc6455">RFC 6455</a>
32   * (originally web socket specification <a href="http://netty.io/s/ws-17">draft-ietf-hybi-thewebsocketprotocol-17</a>).
33   * </p>
34   */
35  public class WebSocketServerHandshaker13 extends WebSocketServerHandshaker {
36  
37      public static final String WEBSOCKET_13_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
38  
39      private final boolean allowExtensions;
40      private final boolean allowMaskMismatch;
41  
42      /**
43       * Constructor specifying the destination web socket location
44       *
45       * @param webSocketURL
46       *        URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web
47       *        socket frames will be sent to this URL.
48       * @param subprotocols
49       *        CSV of supported protocols
50       * @param allowExtensions
51       *        Allow extensions to be used in the reserved bits of the web socket frame
52       * @param maxFramePayloadLength
53       *        Maximum allowable frame payload length. Setting this value to your application's
54       *        requirement may reduce denial of service attacks using long data frames.
55       */
56      public WebSocketServerHandshaker13(
57              String webSocketURL, String subprotocols, boolean allowExtensions, int maxFramePayloadLength) {
58          this(webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, false);
59      }
60  
61      /**
62       * Constructor specifying the destination web socket location
63       *
64       * @param webSocketURL
65       *        URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web
66       *        socket frames will be sent to this URL.
67       * @param subprotocols
68       *        CSV of supported protocols
69       * @param allowExtensions
70       *        Allow extensions to be used in the reserved bits of the web socket frame
71       * @param maxFramePayloadLength
72       *        Maximum allowable frame payload length. Setting this value to your application's
73       *        requirement may reduce denial of service attacks using long data frames.
74       * @param allowMaskMismatch
75       *            When set to true, frames which are not masked properly according to the standard will still be
76       *            accepted.
77       */
78      public WebSocketServerHandshaker13(
79              String webSocketURL, String subprotocols, boolean allowExtensions, int maxFramePayloadLength,
80              boolean allowMaskMismatch) {
81          super(WebSocketVersion.V13, webSocketURL, subprotocols, maxFramePayloadLength);
82          this.allowExtensions = allowExtensions;
83          this.allowMaskMismatch = allowMaskMismatch;
84      }
85  
86      /**
87       * <p>
88       * Handle the web socket handshake for the web socket specification <a href=
89       * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17">HyBi versions 13-17</a>. Versions 13-17
90       * share the same wire protocol.
91       * </p>
92       *
93       * <p>
94       * Browser request to the server:
95       * </p>
96       *
97       * <pre>
98       * GET /chat HTTP/1.1
99       * Host: server.example.com
100      * Upgrade: websocket
101      * Connection: Upgrade
102      * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
103      * Sec-WebSocket-Origin: http://example.com
104      * Sec-WebSocket-Protocol: chat, superchat
105      * Sec-WebSocket-Version: 13
106      * </pre>
107      *
108      * <p>
109      * Server response:
110      * </p>
111      *
112      * <pre>
113      * HTTP/1.1 101 Switching Protocols
114      * Upgrade: websocket
115      * Connection: Upgrade
116      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
117      * Sec-WebSocket-Protocol: chat
118      * </pre>
119      */
120     @Override
121     protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
122         FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);
123         if (headers != null) {
124             res.headers().add(headers);
125         }
126 
127         CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
128         if (key == null) {
129             throw new WebSocketHandshakeException("not a WebSocket request: missing key");
130         }
131         String acceptSeed = key + WEBSOCKET_13_ACCEPT_GUID;
132         byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
133         String accept = WebSocketUtil.base64(sha1);
134 
135         if (logger.isDebugEnabled()) {
136             logger.debug("WebSocket version 13 server handshake key: {}, response: {}", key, accept);
137         }
138 
139         res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
140         res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
141         res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);
142 
143         String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
144         if (subprotocols != null) {
145             String selectedSubprotocol = selectSubprotocol(subprotocols);
146             if (selectedSubprotocol == null) {
147                 if (logger.isDebugEnabled()) {
148                     logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
149                 }
150             } else {
151                 res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
152             }
153         }
154         return res;
155     }
156 
157     @Override
158     protected WebSocketFrameDecoder newWebsocketDecoder() {
159         return new WebSocket13FrameDecoder(true, allowExtensions, maxFramePayloadLength(), allowMaskMismatch);
160     }
161 
162     @Override
163     protected WebSocketFrameEncoder newWebSocketEncoder() {
164         return new WebSocket13FrameEncoder(false);
165     }
166 }