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