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