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