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.buffer.ByteBuf;
19  import io.netty.buffer.Unpooled;
20  import io.netty.channel.Channel;
21  import io.netty.channel.ChannelFuture;
22  import io.netty.channel.ChannelHandlerContext;
23  import io.netty.channel.ChannelPromise;
24  import io.netty.handler.codec.http.DefaultFullHttpResponse;
25  import io.netty.handler.codec.http.FullHttpRequest;
26  import io.netty.handler.codec.http.FullHttpResponse;
27  import io.netty.handler.codec.http.HttpHeaderNames;
28  import io.netty.handler.codec.http.HttpHeaderValues;
29  import io.netty.handler.codec.http.HttpHeaders;
30  import io.netty.handler.codec.http.HttpMethod;
31  import io.netty.handler.codec.http.HttpResponseStatus;
32  
33  import java.util.regex.Pattern;
34  
35  import static io.netty.handler.codec.http.HttpMethod.GET;
36  import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
37  
38  /**
39   * <p>
40   * Performs server side opening and closing handshakes for web socket specification version <a
41   * href="https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00" >draft-ietf-hybi-thewebsocketprotocol-
42   * 00</a>
43   * </p>
44   * <p>
45   * A very large portion of this code was taken from the Netty 3.2 HTTP example.
46   * </p>
47   */
48  public class WebSocketServerHandshaker00 extends WebSocketServerHandshaker {
49  
50      private static final Pattern BEGINNING_DIGIT = Pattern.compile("[^0-9]");
51      private static final Pattern BEGINNING_SPACE = Pattern.compile("[^ ]");
52  
53      /**
54       * Constructor specifying the destination web socket location
55       *
56       * @param webSocketURL
57       *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
58       *            sent to this URL.
59       * @param subprotocols
60       *            CSV of supported protocols
61       * @param maxFramePayloadLength
62       *            Maximum allowable frame payload length. Setting this value to your application's requirement may
63       *            reduce denial of service attacks using long data frames.
64       */
65      public WebSocketServerHandshaker00(String webSocketURL, String subprotocols, int maxFramePayloadLength) {
66          this(webSocketURL, subprotocols, WebSocketDecoderConfig.newBuilder()
67              .maxFramePayloadLength(maxFramePayloadLength)
68              .build());
69      }
70  
71      /**
72       * Constructor specifying the destination web socket location
73       *
74       * @param webSocketURL
75       *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
76       *            sent to this URL.
77       * @param subprotocols
78       *            CSV of supported protocols
79       * @param decoderConfig
80       *            Frames decoder configuration.
81       */
82      public WebSocketServerHandshaker00(String webSocketURL, String subprotocols, WebSocketDecoderConfig decoderConfig) {
83          super(WebSocketVersion.V00, webSocketURL, subprotocols, decoderConfig);
84      }
85  
86      /**
87       * <p>
88       * Handle the web socket handshake for the web socket specification <a href=
89       * "https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00">HyBi version 0</a> and lower. This standard
90       * is really a rehash of <a href="https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76" >hixie-76</a> and
91       * <a href="https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75" >hixie-75</a>.
92       * </p>
93       *
94       * <p>
95       * Browser request to the server:
96       * </p>
97       *
98       * <pre>
99       * GET /demo HTTP/1.1
100      * Upgrade: WebSocket
101      * Connection: Upgrade
102      * Host: example.com
103      * Origin: http://example.com
104      * Sec-WebSocket-Protocol: chat, sample
105      * Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5
106      * Sec-WebSocket-Key2: 12998 5 Y3 1  .P00
107      *
108      * ^n:ds[4U
109      * </pre>
110      *
111      * <p>
112      * Server response:
113      * </p>
114      *
115      * <pre>
116      * HTTP/1.1 101 WebSocket Protocol Handshake
117      * Upgrade: WebSocket
118      * Connection: Upgrade
119      * Sec-WebSocket-Origin: http://example.com
120      * Sec-WebSocket-Location: ws://example.com/demo
121      * Sec-WebSocket-Protocol: sample
122      *
123      * 8jKS'y:G*Co,Wxa-
124      * </pre>
125      */
126     @Override
127     protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
128         HttpMethod method = req.method();
129         if (!GET.equals(method)) {
130             throw new WebSocketServerHandshakeException("Invalid WebSocket handshake method: " + method, req);
131         }
132 
133         // Serve the WebSocket handshake request.
134         if (!req.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)
135                 || !HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(req.headers().get(HttpHeaderNames.UPGRADE))) {
136             throw new WebSocketServerHandshakeException("not a WebSocket handshake request: missing upgrade", req);
137         }
138 
139         // Hixie 75 does not contain these headers while Hixie 76 does
140         boolean isHixie76 = req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY1) &&
141                             req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY2);
142 
143         String origin = req.headers().get(HttpHeaderNames.ORIGIN);
144         //throw before allocating FullHttpResponse
145         if (origin == null && !isHixie76) {
146             throw new WebSocketServerHandshakeException("Missing origin header, got only " + req.headers().names(),
147                                                         req);
148         }
149 
150         // Create the WebSocket handshake response.
151         FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, new HttpResponseStatus(101,
152                 isHixie76 ? "WebSocket Protocol Handshake" : "Web Socket Protocol Handshake"),
153                 req.content().alloc().buffer(0));
154         if (headers != null) {
155             res.headers().add(headers);
156         }
157 
158         res.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
159                      .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
160 
161         // Fill in the headers and contents depending on handshake getMethod.
162         if (isHixie76) {
163             // New handshake getMethod with a challenge:
164             res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, origin);
165             res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_LOCATION, uri());
166 
167             String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
168             if (subprotocols != null) {
169                 String selectedSubprotocol = selectSubprotocol(subprotocols);
170                 if (selectedSubprotocol == null) {
171                     if (logger.isDebugEnabled()) {
172                         logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
173                     }
174                 } else {
175                     res.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
176                 }
177             }
178 
179             // Calculate the answer of the challenge.
180             String key1 = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY1);
181             String key2 = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY2);
182             int a = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key1).replaceAll("")) /
183                            BEGINNING_SPACE.matcher(key1).replaceAll("").length());
184             int b = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key2).replaceAll("")) /
185                            BEGINNING_SPACE.matcher(key2).replaceAll("").length());
186             long c = req.content().readLong();
187             ByteBuf input = Unpooled.wrappedBuffer(new byte[16]).setIndex(0, 0);
188             input.writeInt(a);
189             input.writeInt(b);
190             input.writeLong(c);
191             res.content().writeBytes(WebSocketUtil.md5(input.array()));
192         } else {
193             // Old Hixie 75 handshake getMethod with no challenge:
194             res.headers().add(HttpHeaderNames.WEBSOCKET_ORIGIN, origin);
195             res.headers().add(HttpHeaderNames.WEBSOCKET_LOCATION, uri());
196 
197             String protocol = req.headers().get(HttpHeaderNames.WEBSOCKET_PROTOCOL);
198             if (protocol != null) {
199                 res.headers().set(HttpHeaderNames.WEBSOCKET_PROTOCOL, selectSubprotocol(protocol));
200             }
201         }
202         return res;
203     }
204 
205     /**
206      * Echo back the closing frame
207      *
208      * @param channel
209      *            the {@link Channel} to use.
210      * @param frame
211      *            Web Socket frame that was received.
212      * @param promise
213      *            the {@link ChannelPromise} to be notified when the closing handshake is done.
214      */
215     @Override
216     public ChannelFuture close(Channel channel, CloseWebSocketFrame frame, ChannelPromise promise) {
217         return channel.writeAndFlush(frame, promise);
218     }
219 
220     /**
221      * Echo back the closing frame
222      *
223      * @param ctx
224      *            the {@link ChannelHandlerContext} to use.
225      * @param frame
226      *            Closing Frame that was received.
227      * @param promise
228      *            the {@link ChannelPromise} to be notified when the closing handshake is done.
229      */
230     @Override
231     public ChannelFuture close(ChannelHandlerContext ctx, CloseWebSocketFrame frame,
232                                ChannelPromise promise) {
233         return ctx.writeAndFlush(frame, promise);
234     }
235 
236     @Override
237     protected WebSocketFrameDecoder newWebsocketDecoder() {
238         return new WebSocket00FrameDecoder(decoderConfig());
239     }
240 
241     @Override
242     protected WebSocketFrameEncoder newWebSocketEncoder() {
243         return new WebSocket00FrameEncoder();
244     }
245 }