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