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