View Javadoc
1   /*
2    * Copyright 2012 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.AsciiString;
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.HttpResponseStatus;
31  
32  import java.util.regex.Pattern;
33  
34  import static io.netty.handler.codec.http.HttpVersion.*;
35  
36  /**
37   * <p>
38   * Performs server side opening and closing handshakes for web socket specification version <a
39   * href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00" >draft-ietf-hybi-thewebsocketprotocol-
40   * 00</a>
41   * </p>
42   * <p>
43   * A very large portion of this code was taken from the Netty 3.2 HTTP example.
44   * </p>
45   */
46  public class WebSocketServerHandshaker00 extends WebSocketServerHandshaker {
47  
48      private static final AsciiString WEBSOCKET = new AsciiString("WebSocket");
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          super(WebSocketVersion.V00, webSocketURL, subprotocols, maxFramePayloadLength);
67      }
68  
69      /**
70       * <p>
71       * Handle the web socket handshake for the web socket specification <a href=
72       * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00">HyBi version 0</a> and lower. This standard
73       * is really a rehash of <a href="http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76" >hixie-76</a> and
74       * <a href="http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75" >hixie-75</a>.
75       * </p>
76       *
77       * <p>
78       * Browser request to the server:
79       * </p>
80       *
81       * <pre>
82       * GET /demo HTTP/1.1
83       * Upgrade: WebSocket
84       * Connection: Upgrade
85       * Host: example.com
86       * Origin: http://example.com
87       * Sec-WebSocket-Protocol: chat, sample
88       * Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5
89       * Sec-WebSocket-Key2: 12998 5 Y3 1  .P00
90       *
91       * ^n:ds[4U
92       * </pre>
93       *
94       * <p>
95       * Server response:
96       * </p>
97       *
98       * <pre>
99       * HTTP/1.1 101 WebSocket Protocol Handshake
100      * Upgrade: WebSocket
101      * Connection: Upgrade
102      * Sec-WebSocket-Origin: http://example.com
103      * Sec-WebSocket-Location: ws://example.com/demo
104      * Sec-WebSocket-Protocol: sample
105      *
106      * 8jKS'y:G*Co,Wxa-
107      * </pre>
108      */
109     @Override
110     protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
111 
112         // Serve the WebSocket handshake request.
113         if (!HttpHeaderValues.UPGRADE.equalsIgnoreCase(req.headers().get(HttpHeaderNames.CONNECTION))
114                 || !WEBSOCKET.equalsIgnoreCase(req.headers().get(HttpHeaderNames.UPGRADE))) {
115             throw new WebSocketHandshakeException("not a WebSocket handshake request: missing upgrade");
116         }
117 
118         // Hixie 75 does not contain these headers while Hixie 76 does
119         boolean isHixie76 = req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY1) &&
120                             req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY2);
121 
122         // Create the WebSocket handshake response.
123         FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, new HttpResponseStatus(101,
124                 isHixie76 ? "WebSocket Protocol Handshake" : "Web Socket Protocol Handshake"));
125         if (headers != null) {
126             res.headers().add(headers);
127         }
128 
129         res.headers().add(HttpHeaderNames.UPGRADE, WEBSOCKET);
130         res.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
131 
132         // Fill in the headers and contents depending on handshake getMethod.
133         if (isHixie76) {
134             // New handshake getMethod with a challenge:
135             res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, req.headers().get(HttpHeaderNames.ORIGIN));
136             res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_LOCATION, uri());
137             String subprotocols = req.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
138             if (subprotocols != null) {
139                 String selectedSubprotocol = selectSubprotocol(subprotocols);
140                 if (selectedSubprotocol == null) {
141                     if (logger.isDebugEnabled()) {
142                         logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
143                     }
144                 } else {
145                     res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
146                 }
147             }
148 
149             // Calculate the answer of the challenge.
150             String key1 = req.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_KEY1);
151             String key2 = req.headers().getAndConvert(HttpHeaderNames.SEC_WEBSOCKET_KEY2);
152             int a = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key1).replaceAll("")) /
153                            BEGINNING_SPACE.matcher(key1).replaceAll("").length());
154             int b = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key2).replaceAll("")) /
155                            BEGINNING_SPACE.matcher(key2).replaceAll("").length());
156             long c = req.content().readLong();
157             ByteBuf input = Unpooled.buffer(16);
158             input.writeInt(a);
159             input.writeInt(b);
160             input.writeLong(c);
161             res.content().writeBytes(WebSocketUtil.md5(input.array()));
162         } else {
163             // Old Hixie 75 handshake getMethod with no challenge:
164             res.headers().add(HttpHeaderNames.WEBSOCKET_ORIGIN, req.headers().get(HttpHeaderNames.ORIGIN));
165             res.headers().add(HttpHeaderNames.WEBSOCKET_LOCATION, uri());
166             String protocol = req.headers().getAndConvert(HttpHeaderNames.WEBSOCKET_PROTOCOL);
167             if (protocol != null) {
168                 res.headers().add(HttpHeaderNames.WEBSOCKET_PROTOCOL, selectSubprotocol(protocol));
169             }
170         }
171         return res;
172     }
173 
174     /**
175      * Echo back the closing frame
176      *
177      * @param channel
178      *            Channel
179      * @param frame
180      *            Web Socket frame that was received
181      */
182     @Override
183     public ChannelFuture close(Channel channel, CloseWebSocketFrame frame, ChannelPromise promise) {
184         return channel.writeAndFlush(frame, promise);
185     }
186 
187     @Override
188     protected WebSocketFrameDecoder newWebsocketDecoder() {
189         return new WebSocket00FrameDecoder(maxFramePayloadLength());
190     }
191 
192     @Override
193     protected WebSocketFrameEncoder newWebSocketEncoder() {
194         return new WebSocket00FrameEncoder();
195     }
196 }