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