View Javadoc
1   /*
2    * Copyright 2019 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 WebSocketServerHandshaker08 extends WebSocketServerHandshaker {
37  
38      public static final String WEBSOCKET_08_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
39  
40      /**
41       * Constructor specifying the destination web socket location
42       *
43       * @param webSocketURL
44       *            URL for web socket communications. e.g "ws://myhost.com/mypath".
45       *            Subsequent web socket frames will be sent to this URL.
46       * @param subprotocols
47       *            CSV of supported protocols
48       * @param allowExtensions
49       *            Allow extensions to be used in the reserved bits of the web socket frame
50       * @param maxFramePayloadLength
51       *            Maximum allowable frame payload length. Setting this value to your application's
52       *            requirement may reduce denial of service attacks using long data frames.
53       */
54      public WebSocketServerHandshaker08(
55              String webSocketURL, String subprotocols, boolean allowExtensions, int maxFramePayloadLength) {
56          this(webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, false);
57      }
58  
59      /**
60       * Constructor specifying the destination web socket location
61       *
62       * @param webSocketURL
63       *            URL for web socket communications. e.g "ws://myhost.com/mypath".
64       *            Subsequent web socket frames will be sent to this URL.
65       * @param subprotocols
66       *            CSV of supported protocols
67       * @param allowExtensions
68       *            Allow extensions to be used in the reserved bits of the web socket frame
69       * @param maxFramePayloadLength
70       *            Maximum allowable frame payload length. Setting this value to your application's
71       *            requirement may reduce denial of service attacks using long data frames.
72       * @param allowMaskMismatch
73       *            When set to true, frames which are not masked properly according to the standard will still be
74       *            accepted.
75       */
76      public WebSocketServerHandshaker08(
77              String webSocketURL, String subprotocols, boolean allowExtensions, int maxFramePayloadLength,
78              boolean allowMaskMismatch) {
79          this(webSocketURL, subprotocols, WebSocketDecoderConfig.newBuilder()
80              .allowExtensions(allowExtensions)
81              .maxFramePayloadLength(maxFramePayloadLength)
82              .allowMaskMismatch(allowMaskMismatch)
83              .build());
84      }
85  
86      /**
87       * Constructor specifying the destination web socket location
88       *
89       * @param webSocketURL
90       *            URL for web socket communications. e.g "ws://myhost.com/mypath".
91       *            Subsequent web socket frames will be sent to this URL.
92       * @param subprotocols
93       *            CSV of supported protocols
94       * @param decoderConfig
95       *            Frames decoder configuration.
96       */
97      public WebSocketServerHandshaker08(
98          String webSocketURL, String subprotocols, WebSocketDecoderConfig decoderConfig) {
99          super(WebSocketVersion.V08, webSocketURL, subprotocols, decoderConfig);
100     }
101 
102     /**
103      * <p>
104      * Handle the web socket handshake for the web socket specification <a href=
105      * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-08">HyBi version 8 to 10</a>. Version 8, 9 and
106      * 10 share the same wire protocol.
107      * </p>
108      *
109      * <p>
110      * Browser 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      * <p>
125      * Server response:
126      * </p>
127      *
128      * <pre>
129      * HTTP/1.1 101 Switching Protocols
130      * Upgrade: websocket
131      * Connection: Upgrade
132      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
133      * Sec-WebSocket-Protocol: chat
134      * </pre>
135      */
136     @Override
137     protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
138         CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
139         if (key == null) {
140             throw new WebSocketHandshakeException("not a WebSocket request: missing key");
141         }
142 
143         FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS,
144                 req.content().alloc().buffer(0));
145 
146         if (headers != null) {
147             res.headers().add(headers);
148         }
149 
150         String acceptSeed = key + WEBSOCKET_08_ACCEPT_GUID;
151         byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
152         String accept = WebSocketUtil.base64(sha1);
153 
154         if (logger.isDebugEnabled()) {
155             logger.debug("WebSocket version 08 server handshake key: {}, response: {}", key, accept);
156         }
157 
158         res.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
159                      .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
160                      .set(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);
161 
162         String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
163         if (subprotocols != null) {
164             String selectedSubprotocol = selectSubprotocol(subprotocols);
165             if (selectedSubprotocol == null) {
166                 if (logger.isDebugEnabled()) {
167                     logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
168                 }
169             } else {
170                 res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
171             }
172         }
173         return res;
174     }
175 
176     @Override
177     protected WebSocketFrameDecoder newWebsocketDecoder() {
178         return new WebSocket08FrameDecoder(decoderConfig());
179     }
180 
181     @Override
182     protected WebSocketFrameEncoder newWebSocketEncoder() {
183         return new WebSocket08FrameEncoder(false);
184     }
185 }