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 java.net.URI;
    19  import java.util.Map;
    20
    21  import org.jboss.netty.channel.Channel;
    22  import org.jboss.netty.channel.ChannelFuture;
    23  import org.jboss.netty.handler.codec.http.DefaultHttpRequest;
    24  import org.jboss.netty.handler.codec.http.HttpHeaders.Names;
    25  import org.jboss.netty.handler.codec.http.HttpHeaders.Values;
    26  import org.jboss.netty.handler.codec.http.HttpMethod;
    27  import org.jboss.netty.handler.codec.http.HttpRequest;
    28  import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
    29  import org.jboss.netty.handler.codec.http.HttpResponse;
    30  import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
    31  import org.jboss.netty.handler.codec.http.HttpResponseStatus;
    32  import org.jboss.netty.handler.codec.http.HttpVersion;
    33  import org.jboss.netty.logging.InternalLogger;
    34  import org.jboss.netty.logging.InternalLoggerFactory;
    35  import org.jboss.netty.util.CharsetUtil;
    36
    37  /**
    38   * <p>
    39   * Performs client side opening and closing handshakes for web socket specification version <a
    40   * href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10" >draft-ietf-hybi-thewebsocketprotocol-
    41   * 10</a>
    42   * </p>
    43   */
    44  public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
    45
    46      private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker08.class);
    47
    48      public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    49
    50      private String expectedChallengeResponseString;
    51
    52      private final boolean allowExtensions;
    53
    54      /**
    55       * Constructor with default values
    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 version
    61       *            Version of web socket specification to use to connect to the server
    62       * @param subprotocol
    63       *            Sub protocol request sent to the server.
    64       * @param allowExtensions
    65       *            Allow extensions to be used in the reserved bits of the web socket frame
    66       * @param customHeaders
    67       *            Map of custom headers to add to the client request
    68       */
    69      public WebSocketClientHandshaker08(URI webSocketURL, WebSocketVersion version, String subprotocol,
    70              boolean allowExtensions, Map<String, String> customHeaders) {
    71          this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, Long.MAX_VALUE);
    72      }
    73
    74      /**
    75       * Constructor
    76       *
    77       * @param webSocketURL
    78       *            URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
    79       *            sent to this URL.
    80       * @param version
    81       *            Version of web socket specification to use to connect to the server
    82       * @param subprotocol
    83       *            Sub protocol request sent to the server.
    84       * @param allowExtensions
    85       *            Allow extensions to be used in the reserved bits of the web socket frame
    86       * @param customHeaders
    87       *            Map of custom headers to add to the client request
    88       * @param maxFramePayloadLength
    89       *            Maximum length of a frame's payload
    90       */
    91      public WebSocketClientHandshaker08(URI webSocketURL, WebSocketVersion version, String subprotocol,
    92              boolean allowExtensions, Map<String, String> customHeaders, long maxFramePayloadLength) {
    93          super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength);
    94          this.allowExtensions = allowExtensions;
    95      }
    96
    97
    98      /**
    99       * /**
    100      * <p>
    101      * Sends the opening request to the server:
    102      * </p>
    103      *
    104      * <pre>
    105      * GET /chat HTTP/1.1
    106      * Host: server.example.com
    107      * Upgrade: websocket
    108      * Connection: Upgrade
    109      * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
    110      * Sec-WebSocket-Origin: http://example.com
    111      * Sec-WebSocket-Protocol: chat, superchat
    112      * Sec-WebSocket-Version: 8
    113      * </pre>
    114      *
    115      * @param channel
    116      *            Channel into which we can write our request
    117      */
    118     @Override
    119     public ChannelFuture handshake(Channel channel) throws Exception {
    120         // Get path
    121         URI wsURL = getWebSocketUrl();
    122         String path = wsURL.getPath();
    123         if (wsURL.getQuery() != null && wsURL.getQuery().length() > 0) {
    124             path = wsURL.getPath() + "?" + wsURL.getQuery();
    125         }
    126
    127         // Get 16 bit nonce and base 64 encode it
    128         byte[] nonce = WebSocketUtil.randomBytes(16);
    129         String key = WebSocketUtil.base64(nonce);
    130
    131         String acceptSeed = key + MAGIC_GUID;
    132         byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII.name()));
    133         expectedChallengeResponseString = WebSocketUtil.base64(sha1);
    134
    135         if (logger.isDebugEnabled()) {
    136             logger.debug(String.format("WS Version 08 Client Handshake key: %s. Expected response: %s.", key,
    137                     expectedChallengeResponseString));
    138         }
    139
    140         // Format request
    141         HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
    142         request.addHeader(Names.UPGRADE, Values.WEBSOCKET.toLowerCase());
    143         request.addHeader(Names.CONNECTION, Values.UPGRADE);
    144         request.addHeader(Names.SEC_WEBSOCKET_KEY, key);
    145         request.addHeader(Names.HOST, wsURL.getHost());
    146
    147         int wsPort = wsURL.getPort();
    148         String originValue = "http://" + wsURL.getHost();
    149         if (wsPort != 80 && wsPort != 443) {
    150             // if the port is not standard (80/443) its needed to add the port to the header.
    151             // See http://tools.ietf.org/html/rfc6454#section-6.2
    152             originValue = originValue + ":" + wsPort;
    153         }
    154
    155         // Use Sec-WebSocket-Origin
    156         // See https://github.com/netty/netty/issues/264
    157         request.addHeader(Names.SEC_WEBSOCKET_ORIGIN, originValue);
    158
    159         String expectedSubprotocol = getExpectedSubprotocol();
    160         if (expectedSubprotocol != null && !expectedSubprotocol.equals("")) {
    161             request.addHeader(Names.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
    162         }
    163
    164         request.addHeader(Names.SEC_WEBSOCKET_VERSION, "8");
    165
    166         if (customHeaders != null) {
    167             for (String header : customHeaders.keySet()) {
    168                 request.addHeader(header, customHeaders.get(header));
    169             }
    170         }
    171
    172         ChannelFuture future = channel.write(request);
    173
    174         channel.getPipeline().replace(HttpRequestEncoder.class, "ws-encoder", new WebSocket08FrameEncoder(true));
    175
    176         return future;
    177     }
    178
    179     /**
    180      * <p>
    181      * Process server response:
    182      * </p>
    183      *
    184      * <pre>
    185      * HTTP/1.1 101 Switching Protocols
    186      * Upgrade: websocket
    187      * Connection: Upgrade
    188      * Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
    189      * Sec-WebSocket-Protocol: chat
    190      * </pre>
    191      *
    192      * @param channel
    193      *            Channel
    194      * @param response
    195      *            HTTP response returned from the server for the request sent by beginOpeningHandshake00().
    196      * @throws WebSocketHandshakeException
    197      */
    198     @Override
    199     public void finishHandshake(Channel channel, HttpResponse response) {
    200         final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
    201
    202         if (!response.getStatus().equals(status)) {
    203             throw new WebSocketHandshakeException("Invalid handshake response status: " + response.getStatus());
    204         }
    205
    206         String upgrade = response.getHeader(Names.UPGRADE);
    207         // Upgrade header should be matched case-insensitive.
    208         // See https://github.com/netty/netty/issues/278
    209         if (upgrade == null || !upgrade.toLowerCase().equals(Values.WEBSOCKET.toLowerCase())) {
    210             throw new WebSocketHandshakeException("Invalid handshake response upgrade: "
    211                     + response.getHeader(Names.UPGRADE));
    212         }
    213
    214         // Connection header should be matched case-insensitive.
    215         // See https://github.com/netty/netty/issues/278
    216         String connection = response.getHeader(Names.CONNECTION);
    217         if (connection == null || !connection.toLowerCase().equals(Values.UPGRADE.toLowerCase())) {
    218             throw new WebSocketHandshakeException("Invalid handshake response connection: "
    219                     + response.getHeader(Names.CONNECTION));
    220         }
    221
    222         String accept = response.getHeader(Names.SEC_WEBSOCKET_ACCEPT);
    223         if (accept == null || !accept.equals(expectedChallengeResponseString)) {
    224             throw new WebSocketHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept,
    225                     expectedChallengeResponseString));
    226         }
    227
    228         String subprotocol = response.getHeader(Names.SEC_WEBSOCKET_PROTOCOL);
    229         setActualSubprotocol(subprotocol);
    230
    231
    232         setHandshakeComplete();
    233
    234         channel.getPipeline().get(HttpResponseDecoder.class).replace("ws-decoder",
    235                 new WebSocket08FrameDecoder(false, allowExtensions, getMaxFramePayloadLength()));
    236
    237
    238     }
    239 }