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