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