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