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 org.jboss.netty.handler.codec.http.websocketx;
17  
18  import static org.jboss.netty.handler.codec.http.HttpHeaders.Values.*;
19  import static org.jboss.netty.handler.codec.http.HttpVersion.*;
20  
21  import org.jboss.netty.buffer.ChannelBuffer;
22  import org.jboss.netty.buffer.ChannelBuffers;
23  import org.jboss.netty.channel.Channel;
24  import org.jboss.netty.channel.ChannelFuture;
25  import org.jboss.netty.channel.ChannelFutureListener;
26  import org.jboss.netty.channel.ChannelPipeline;
27  import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
28  import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
29  import org.jboss.netty.handler.codec.http.HttpHeaders.Names;
30  import org.jboss.netty.handler.codec.http.HttpRequest;
31  import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
32  import org.jboss.netty.handler.codec.http.HttpResponse;
33  import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
34  import org.jboss.netty.handler.codec.http.HttpResponseStatus;
35  import org.jboss.netty.logging.InternalLogger;
36  import org.jboss.netty.logging.InternalLoggerFactory;
37  import org.jboss.netty.util.CharsetUtil;
38  
39  /**
40   * <p>
41   * Performs server side opening and closing handshakes for <a
42   * href="http://tools.ietf.org/html/rfc6455 ">RFC 6455</a> (originally web
43   * socket specification version <a
44   * href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17"
45   * >draft-ietf-hybi-thewebsocketprotocol- 17</a>).
46   * </p>
47   */
48  public class WebSocketServerHandshaker13 extends WebSocketServerHandshaker {
49  
50      private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketServerHandshaker13.class);
51  
52      public static final String WEBSOCKET_13_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
53  
54      private final boolean allowExtensions;
55  
56      /**
57       * Constructor using defaults
58       *
59       * @param webSocketURL
60       *            URL for web socket communications. e.g
61       *            "ws://myhost.com/mypath". Subsequent web socket frames will be
62       *            sent to this URL.
63       * @param subprotocols
64       *            CSV of supported protocols
65       * @param allowExtensions
66       *            Allow extensions to be used in the reserved bits of the web
67       *            socket frame
68       */
69      public WebSocketServerHandshaker13(String webSocketURL, String subprotocols, boolean allowExtensions) {
70          this(webSocketURL, subprotocols, allowExtensions, Long.MAX_VALUE);
71      }
72  
73      /**
74       * Constructor specifying the destination web socket location
75       *
76       * @param webSocketURL
77       *            URL for web socket communications. e.g
78       *            "ws://myhost.com/mypath". Subsequent web socket frames will be
79       *            sent to this URL.
80       * @param subprotocols
81       *            CSV of supported protocols
82       * @param allowExtensions
83       *            Allow extensions to be used in the reserved bits of the web
84       *            socket frame
85       * @param maxFramePayloadLength
86       *            Maximum allowable frame payload length. Setting this value to
87       *            your application's requirement may reduce denial of service
88       *            attacks using long data frames.
89       */
90      public WebSocketServerHandshaker13(String webSocketURL, String subprotocols, boolean allowExtensions,
91              long maxFramePayloadLength) {
92          super(WebSocketVersion.V13, webSocketURL, subprotocols, maxFramePayloadLength);
93          this.allowExtensions = allowExtensions;
94      }
95  
96      /**
97       * <p>
98       * Handle the web socket handshake for the web socket specification <a href=
99       * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17">HyBi
100      * versions 13-17</a>. Versions 13-17 share the same wire protocol.
101      * </p>
102      *
103      * <p>
104      * Browser request to the server:
105      * </p>
106      *
107      * <pre>
108      * GET /chat HTTP/1.1
109      * Host: server.example.com
110      * Upgrade: websocket
111      * Connection: Upgrade
112      * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
113      * Sec-WebSocket-Origin: http://example.com
114      * Sec-WebSocket-Protocol: chat, superchat
115      * Sec-WebSocket-Version: 13
116      * </pre>
117      *
118      * <p>
119      * Server response:
120      * </p>
121      *
122      * <pre>
123      * HTTP/1.1 101 Switching Protocols
124      * Upgrade: websocket
125      * Connection: Upgrade
126      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
127      * Sec-WebSocket-Protocol: chat
128      * </pre>
129      *
130      * @param channel
131      *            Channel
132      * @param req
133      *            HTTP request
134      */
135     @Override
136     public ChannelFuture handshake(Channel channel, HttpRequest req) {
137 
138         if (logger.isDebugEnabled()) {
139             logger.debug(String.format("Channel %s WS Version 13 server handshake", channel.getId()));
140         }
141 
142         HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);
143 
144         String key = req.getHeader(Names.SEC_WEBSOCKET_KEY);
145         if (key == null) {
146             throw new WebSocketHandshakeException("not a WebSocket request: missing key");
147         }
148         String acceptSeed = key + WEBSOCKET_13_ACCEPT_GUID;
149         ChannelBuffer sha1 = WebSocketUtil.sha1(ChannelBuffers.copiedBuffer(acceptSeed, CharsetUtil.US_ASCII));
150         String accept = WebSocketUtil.base64(sha1);
151 
152         if (logger.isDebugEnabled()) {
153             logger.debug(String.format("WS Version 13 Server Handshake key: %s. Response: %s.", key, accept));
154         }
155 
156         res.setStatus(HttpResponseStatus.SWITCHING_PROTOCOLS);
157         res.addHeader(Names.UPGRADE, WEBSOCKET.toLowerCase());
158         res.addHeader(Names.CONNECTION, Names.UPGRADE);
159         res.addHeader(Names.SEC_WEBSOCKET_ACCEPT, accept);
160         String subprotocols = req.getHeader(Names.SEC_WEBSOCKET_PROTOCOL);
161         if (subprotocols != null) {
162             String selectedSubprotocol = selectSubprotocol(subprotocols);
163             if (selectedSubprotocol == null) {
164                 throw new WebSocketHandshakeException("Requested subprotocol(s) not supported: " + subprotocols);
165             } else {
166                 res.addHeader(Names.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
167                 setSelectedSubprotocol(selectedSubprotocol);
168             }
169         }
170 
171         ChannelFuture future = channel.write(res);
172 
173         // Upgrade the connection and send the handshake response.
174         future.addListener(new ChannelFutureListener() {
175             public void operationComplete(ChannelFuture future) {
176                 ChannelPipeline p = future.getChannel().getPipeline();
177                 if (p.get(HttpChunkAggregator.class) != null) {
178                     p.remove(HttpChunkAggregator.class);
179                 }
180 
181                 p.replace(HttpRequestDecoder.class, "wsdecoder",
182                         new WebSocket13FrameDecoder(true, allowExtensions, getMaxFramePayloadLength()));
183                 p.replace(HttpResponseEncoder.class, "wsencoder", new WebSocket13FrameEncoder(false));
184             }
185         });
186 
187         return future;
188     }
189 
190     /**
191      * Echo back the closing frame and close the connection
192      *
193      * @param channel
194      *            Channel
195      * @param frame
196      *            Web Socket frame that was received
197      */
198     @Override
199     public ChannelFuture close(Channel channel, CloseWebSocketFrame frame) {
200         ChannelFuture f = channel.write(frame);
201         f.addListener(ChannelFutureListener.CLOSE);
202         return f;
203     }
204 
205 }