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.handler.codec.http.DefaultHttpResponse;
24  import org.jboss.netty.handler.codec.http.HttpHeaders.Names;
25  import org.jboss.netty.handler.codec.http.HttpRequest;
26  import org.jboss.netty.handler.codec.http.HttpResponse;
27  import org.jboss.netty.handler.codec.http.HttpResponseStatus;
28  import org.jboss.netty.logging.InternalLogger;
29  import org.jboss.netty.logging.InternalLoggerFactory;
30  import org.jboss.netty.util.CharsetUtil;
31  
32  import static org.jboss.netty.handler.codec.http.HttpHeaders.Values.*;
33  import static org.jboss.netty.handler.codec.http.HttpVersion.*;
34  
35  /**
36   * <p>
37   * Performs server side opening and closing handshakes for web socket specification version <a
38   * href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10" >draft-ietf-hybi-thewebsocketprotocol-
39   * 10</a>
40   * </p>
41   */
42  public class WebSocketServerHandshaker08 extends WebSocketServerHandshaker {
43  
44      private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketServerHandshaker08.class);
45  
46      public static final String WEBSOCKET_08_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
47  
48      private final boolean allowExtensions;
49  
50      /**
51       * Constructor using defaults
52       *
53       * @param webSocketURL
54       *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
55       *            sent to this URL.
56       * @param subprotocols
57       *            CSV of supported protocols
58       * @param allowExtensions
59       *            Allow extensions to be used in the reserved bits of the web socket frame
60       */
61      public WebSocketServerHandshaker08(String webSocketURL, String subprotocols, boolean allowExtensions) {
62          this(webSocketURL, subprotocols, allowExtensions, Long.MAX_VALUE);
63      }
64  
65      /**
66       * Constructor
67       *
68       * @param webSocketURL
69       *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
70       *            sent to this URL.
71       * @param subprotocols
72       *            CSV of supported protocols
73       * @param allowExtensions
74       *            Allow extensions to be used in the reserved bits of the web socket frame
75       * @param maxFramePayloadLength
76       *            Maximum allowable frame payload length. Setting this value to your application's requirement may
77       *            reduce denial of service attacks using long data frames.
78       */
79      public WebSocketServerHandshaker08(String webSocketURL, String subprotocols, boolean allowExtensions,
80              long maxFramePayloadLength) {
81          super(WebSocketVersion.V08, webSocketURL, subprotocols, maxFramePayloadLength);
82          this.allowExtensions = allowExtensions;
83      }
84  
85      /**
86       * <p>
87       * Handle the web socket handshake for the web socket specification <a href=
88       * "http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-08">HyBi version 8 to 10</a>. Version 8, 9 and
89       * 10 share the same wire protocol.
90       * </p>
91       *
92       * <p>
93       * Browser request to the server:
94       * </p>
95       *
96       * <pre>
97       * GET /chat HTTP/1.1
98       * Host: server.example.com
99       * Upgrade: websocket
100      * Connection: Upgrade
101      * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
102      * Sec-WebSocket-Origin: http://example.com
103      * Sec-WebSocket-Protocol: chat, superchat
104      * Sec-WebSocket-Version: 8
105      * </pre>
106      *
107      * <p>
108      * Server response:
109      * </p>
110      *
111      * <pre>
112      * HTTP/1.1 101 Switching Protocols
113      * Upgrade: websocket
114      * Connection: Upgrade
115      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
116      * Sec-WebSocket-Protocol: chat
117      * </pre>
118      *
119      * @param channel
120      *            Channel
121      * @param req
122      *            HTTP request
123      */
124     @Override
125     public ChannelFuture handshake(Channel channel, HttpRequest req) {
126 
127         if (logger.isDebugEnabled()) {
128             logger.debug(String.format("Channel %s WS Version 8 server handshake", channel.getId()));
129         }
130 
131         HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.SWITCHING_PROTOCOLS);
132 
133         String key = req.headers().get(Names.SEC_WEBSOCKET_KEY);
134         if (key == null) {
135             throw new WebSocketHandshakeException("not a WebSocket request: missing key");
136         }
137         String acceptSeed = key + WEBSOCKET_08_ACCEPT_GUID;
138         ChannelBuffer sha1 = WebSocketUtil.sha1(ChannelBuffers.copiedBuffer(acceptSeed, CharsetUtil.US_ASCII));
139 
140         String accept = WebSocketUtil.base64(sha1);
141 
142         if (logger.isDebugEnabled()) {
143             logger.debug(String.format("WS Version 8 Server Handshake key: %s. Response: %s.", key, accept));
144         }
145 
146         res.setStatus(HttpResponseStatus.SWITCHING_PROTOCOLS);
147         res.headers().add(Names.UPGRADE, WEBSOCKET.toLowerCase());
148         res.headers().add(Names.CONNECTION, Names.UPGRADE);
149         res.headers().add(Names.SEC_WEBSOCKET_ACCEPT, accept);
150         String subprotocols = req.headers().get(Names.SEC_WEBSOCKET_PROTOCOL);
151         if (subprotocols != null) {
152             String selectedSubprotocol = selectSubprotocol(subprotocols);
153             if (selectedSubprotocol == null) {
154                 throw new WebSocketHandshakeException("Requested subprotocol(s) not supported: " + subprotocols);
155             } else {
156                 res.headers().add(Names.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
157                 setSelectedSubprotocol(selectedSubprotocol);
158             }
159         }
160 
161         return writeHandshakeResponse(
162                 channel, res, new WebSocket08FrameEncoder(false),
163                               new WebSocket08FrameDecoder(true, allowExtensions, getMaxFramePayloadLength()));
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 f = channel.write(frame);
177         f.addListener(ChannelFutureListener.CLOSE);
178         return f;
179     }
180 
181 }