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 web socket specification version <a
32   * href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10" >draft-ietf-hybi-thewebsocketprotocol-
33   * 10</a>
34   * </p>
35   */
36  public class WebSocketServerHandshaker07 extends WebSocketServerHandshaker {
37  
38      public static final String WEBSOCKET_07_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
39  
40      private final boolean allowExtensions;
41      private final boolean allowMaskMismatch;
42  
43      /**
44       * Constructor specifying the destination web socket location
45       *
46       * @param webSocketURL
47       *            URL for web socket communications. e.g "ws://myhost.com/mypath".
48       *            Subsequent web socket frames will be sent to this URL.
49       * @param subprotocols
50       *            CSV of supported protocols
51       * @param allowExtensions
52       *            Allow extensions to be used in the reserved bits of the web socket frame
53       * @param maxFramePayloadLength
54       *            Maximum allowable frame payload length. Setting this value to your application's
55       *            requirement may reduce denial of service attacks using long data frames.
56       */
57      public WebSocketServerHandshaker07(
58              String webSocketURL, String subprotocols, boolean allowExtensions, int maxFramePayloadLength) {
59          this(webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, false);
60      }
61  
62      /**
63       * Constructor specifying the destination web socket location
64       *
65       * @param webSocketURL
66       *            URL for web socket communications. e.g "ws://myhost.com/mypath".
67       *            Subsequent web socket frames will be sent to this URL.
68       * @param subprotocols
69       *            CSV of supported protocols
70       * @param allowExtensions
71       *            Allow extensions to be used in the reserved bits of the web socket frame
72       * @param maxFramePayloadLength
73       *            Maximum allowable frame payload length. Setting this value to your application's
74       *            requirement may reduce denial of service attacks using long data frames.
75       * @param allowMaskMismatch
76       *            When set to true, frames which are not masked properly according to the standard will still be
77       *            accepted.
78       */
79      public WebSocketServerHandshaker07(
80              String webSocketURL, String subprotocols, boolean allowExtensions, int maxFramePayloadLength,
81              boolean allowMaskMismatch) {
82          super(WebSocketVersion.V07, webSocketURL, subprotocols, maxFramePayloadLength);
83          this.allowExtensions = allowExtensions;
84          this.allowMaskMismatch = allowMaskMismatch;
85      }
86  
87      /**
88       * <p>
89       * Handle the web socket handshake for the web socket specification <a href=
90       * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07">HyBi version 7</a>.
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: 7
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 
123         FullHttpResponse res =
124                 new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);
125 
126         if (headers != null) {
127             res.headers().add(headers);
128         }
129 
130         CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
131         if (key == null) {
132             throw new WebSocketHandshakeException("not a WebSocket request: missing key");
133         }
134         String acceptSeed = key + WEBSOCKET_07_ACCEPT_GUID;
135         byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
136         String accept = WebSocketUtil.base64(sha1);
137 
138         if (logger.isDebugEnabled()) {
139             logger.debug("WebSocket version 07 server handshake key: {}, response: {}.", key, accept);
140         }
141 
142         res.headers().add(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
143         res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
144         res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);
145 
146         String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
147         if (subprotocols != null) {
148             String selectedSubprotocol = selectSubprotocol(subprotocols);
149             if (selectedSubprotocol == null) {
150                 if (logger.isDebugEnabled()) {
151                     logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
152                 }
153             } else {
154                 res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
155             }
156         }
157         return res;
158     }
159 
160     @Override
161     protected WebSocketFrameDecoder newWebsocketDecoder() {
162         return new WebSocket07FrameDecoder(true, allowExtensions, maxFramePayloadLength(), allowMaskMismatch);
163     }
164 
165     @Override
166     protected WebSocketFrameEncoder newWebSocketEncoder() {
167         return new WebSocket07FrameEncoder(false);
168     }
169 }