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 WebSocketServerHandshaker07 extends WebSocketServerHandshaker {
37  
38      public static final String WEBSOCKET_07_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 WebSocketServerHandshaker07(
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 WebSocketServerHandshaker07(
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 decoderConfig
90       *            Frames decoder configuration.
91       */
92      public WebSocketServerHandshaker07(String webSocketURL, String subprotocols, WebSocketDecoderConfig decoderConfig) {
93          super(WebSocketVersion.V07, webSocketURL, subprotocols, decoderConfig);
94      }
95  
96      /**
97       * <p>
98       * Handle the web socket handshake for the web socket specification <a href=
99       * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07">HyBi version 7</a>.
100      * </p>
101      *
102      * <p>
103      * Browser request to the server:
104      * </p>
105      *
106      * <pre>
107      * GET /chat HTTP/1.1
108      * Host: server.example.com
109      * Upgrade: websocket
110      * Connection: Upgrade
111      * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
112      * Sec-WebSocket-Origin: http://example.com
113      * Sec-WebSocket-Protocol: chat, superchat
114      * Sec-WebSocket-Version: 7
115      * </pre>
116      *
117      * <p>
118      * Server response:
119      * </p>
120      *
121      * <pre>
122      * HTTP/1.1 101 Switching Protocols
123      * Upgrade: websocket
124      * Connection: Upgrade
125      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
126      * Sec-WebSocket-Protocol: chat
127      * </pre>
128      */
129     @Override
130     protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
131         CharSequence key = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY);
132         if (key == null) {
133             throw new WebSocketHandshakeException("not a WebSocket request: missing key");
134         }
135 
136         FullHttpResponse res =
137                 new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS,
138                         req.content().alloc().buffer(0));
139 
140         if (headers != null) {
141             res.headers().add(headers);
142         }
143 
144         String acceptSeed = key + WEBSOCKET_07_ACCEPT_GUID;
145         byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
146         String accept = WebSocketUtil.base64(sha1);
147 
148         if (logger.isDebugEnabled()) {
149             logger.debug("WebSocket version 07 server handshake key: {}, response: {}.", key, accept);
150         }
151 
152         res.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
153                      .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
154                      .set(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT, accept);
155 
156         String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
157         if (subprotocols != null) {
158             String selectedSubprotocol = selectSubprotocol(subprotocols);
159             if (selectedSubprotocol == null) {
160                 if (logger.isDebugEnabled()) {
161                     logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
162                 }
163             } else {
164                 res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
165             }
166         }
167         return res;
168     }
169 
170     @Override
171     protected WebSocketFrameDecoder newWebsocketDecoder() {
172         return new WebSocket07FrameDecoder(decoderConfig());
173     }
174 
175     @Override
176     protected WebSocketFrameEncoder newWebSocketEncoder() {
177         return new WebSocket07FrameEncoder(false);
178     }
179 }