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