netty5/codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketClientHandshaker13.java

301 lines
13 KiB
Java
Raw Normal View History

/*
2012-06-04 22:31:44 +02:00
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
2012-06-04 22:31:44 +02:00
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http.websocketx;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
Fix backward compatibility from the previous backport Motivation: The commit 50e06442c3f2753c9b2a506f68ea70273b829e21 changed the type of the constants in HttpHeaders.Names and HttpHeaders.Values, making 4.1 backward-incompatible with 4.0. It also introduces newer utility classes such as HttpHeaderUtil, which deprecates most static methods in HttpHeaders. To ease the migration between 4.1 and 5.0, we should deprecate all static methods that are non-existent in 5.0, and provide proper counterpart. Modification: - Revert the changes in HttpHeaders.Names and Values - Deprecate all static methods in HttpHeaders in favor of: - HttpHeaderUtil - the member methods of HttpHeaders - AsciiString - Add integer and date access methods to HttpHeaders for easier future migration to 5.0 - Add HttpHeaderNames and HttpHeaderValues which provide standard HTTP constants in AsciiString - Deprecate HttpHeaders.Names and Values - Make HttpHeaderValues.WEBSOCKET lowercased because it's actually lowercased in all WebSocket versions but the oldest one - Add RtspHeaderNames and RtspHeaderValues which provide standard RTSP constants in AsciiString - Deprecate RtspHeaders.* - Do not use AsciiString.equalsIgnoreCase(CharSeq, CharSeq) if one of the parameters are AsciiString - Avoid using AsciiString.toString() repetitively - Change the parameter type of some methods from String to CharSequence Result: Backward compatibility is recovered. New classes and methods will make the migration to 5.0 easier, once (Http|Rtsp)Header(Names|Values) are ported to master.
2014-10-31 08:48:28 +01:00
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.net.URI;
/**
* <p>
* Performs client side opening and closing handshakes for web socket specification version <a
* href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17" >draft-ietf-hybi-thewebsocketprotocol-
* 17</a>
* </p>
*/
public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketClientHandshaker13.class);
public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private String expectedChallengeResponseString;
2012-01-19 05:12:45 +01:00
private final boolean allowExtensions;
private final boolean performMasking;
private final boolean allowMaskMismatch;
/**
* Creates a new instance.
*
* @param webSocketURL
* URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
* sent to this URL.
* @param version
* Version of web socket specification to use to connect to the server
2012-01-19 05:12:45 +01:00
* @param subprotocol
* Sub protocol request sent to the server.
* @param allowExtensions
* Allow extensions to be used in the reserved bits of the web socket frame
* @param customHeaders
* Map of custom headers to add to the client request
* @param maxFramePayloadLength
* Maximum length of a frame's payload
*/
2012-01-19 05:12:45 +01:00
public WebSocketClientHandshaker13(URI webSocketURL, WebSocketVersion version, String subprotocol,
boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength) {
this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength,
true, false);
}
/**
* Creates a new instance.
*
* @param webSocketURL
* URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
* sent to this URL.
* @param version
* Version of web socket specification to use to connect to the server
* @param subprotocol
* Sub protocol request sent to the server.
* @param allowExtensions
* Allow extensions to be used in the reserved bits of the web socket frame
* @param customHeaders
* Map of custom headers to add to the client request
* @param maxFramePayloadLength
* Maximum length of a frame's payload
* @param performMasking
* Whether to mask all written websocket frames. This must be set to true in order to be fully compatible
* with the websocket specifications. Client applications that communicate with a non-standard server
* which doesn't require masking might set this to false to achieve a higher performance.
* @param allowMaskMismatch
* When set to true, frames which are not masked properly according to the standard will still be
* accepted.
*/
public WebSocketClientHandshaker13(URI webSocketURL, WebSocketVersion version, String subprotocol,
boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength,
boolean performMasking, boolean allowMaskMismatch) {
this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength,
performMasking, allowMaskMismatch, DEFAULT_FORCE_CLOSE_TIMEOUT_MILLIS);
}
/**
* Creates a new instance.
*
* @param webSocketURL
* URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
* sent to this URL.
* @param version
* Version of web socket specification to use to connect to the server
* @param subprotocol
* Sub protocol request sent to the server.
* @param allowExtensions
* Allow extensions to be used in the reserved bits of the web socket frame
* @param customHeaders
* Map of custom headers to add to the client request
* @param maxFramePayloadLength
* Maximum length of a frame's payload
* @param performMasking
* Whether to mask all written websocket frames. This must be set to true in order to be fully compatible
* with the websocket specifications. Client applications that communicate with a non-standard server
* which doesn't require masking might set this to false to achieve a higher performance.
* @param allowMaskMismatch
* When set to true, frames which are not masked properly according to the standard will still be
* accepted
* @param forceCloseTimeoutMillis
* Close the connection if it was not closed by the server after timeout specified.
*/
public WebSocketClientHandshaker13(URI webSocketURL, WebSocketVersion version, String subprotocol,
boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength,
boolean performMasking, boolean allowMaskMismatch,
long forceCloseTimeoutMillis) {
this(webSocketURL, version, subprotocol, allowExtensions, customHeaders, maxFramePayloadLength, performMasking,
allowMaskMismatch, forceCloseTimeoutMillis, false);
}
/**
* Creates a new instance.
*
* @param webSocketURL
* URL for web socket communications. e.g "ws://myhost.com/mypath". Subsequent web socket frames will be
* sent to this URL.
* @param version
* Version of web socket specification to use to connect to the server
* @param subprotocol
* Sub protocol request sent to the server.
* @param allowExtensions
* Allow extensions to be used in the reserved bits of the web socket frame
* @param customHeaders
* Map of custom headers to add to the client request
* @param maxFramePayloadLength
* Maximum length of a frame's payload
* @param performMasking
* Whether to mask all written websocket frames. This must be set to true in order to be fully compatible
* with the websocket specifications. Client applications that communicate with a non-standard server
* which doesn't require masking might set this to false to achieve a higher performance.
* @param allowMaskMismatch
* When set to true, frames which are not masked properly according to the standard will still be
* accepted
* @param forceCloseTimeoutMillis
* Close the connection if it was not closed by the server after timeout specified.
* @param absoluteUpgradeUrl
* Use an absolute url for the Upgrade request, typically when connecting through an HTTP proxy over
* clear HTTP
*/
WebSocketClientHandshaker13(URI webSocketURL, WebSocketVersion version, String subprotocol,
boolean allowExtensions, HttpHeaders customHeaders, int maxFramePayloadLength,
boolean performMasking, boolean allowMaskMismatch,
long forceCloseTimeoutMillis, boolean absoluteUpgradeUrl) {
super(webSocketURL, version, subprotocol, customHeaders, maxFramePayloadLength, forceCloseTimeoutMillis,
absoluteUpgradeUrl);
this.allowExtensions = allowExtensions;
this.performMasking = performMasking;
this.allowMaskMismatch = allowMaskMismatch;
}
/**
* /**
* <p>
* Sends the opening request to the server:
* </p>
*
* <pre>
* GET /chat HTTP/1.1
* Host: server.example.com
* Upgrade: websocket
* Connection: Upgrade
* Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
* Origin: http://example.com
* Sec-WebSocket-Protocol: chat, superchat
* Sec-WebSocket-Version: 13
* </pre>
*
*/
@Override
protected FullHttpRequest newHandshakeRequest() {
2013-01-17 07:06:46 +01:00
URI wsURL = uri();
// Get 16 bit nonce and base 64 encode it
2012-01-19 05:12:45 +01:00
byte[] nonce = WebSocketUtil.randomBytes(16);
String key = WebSocketUtil.base64(nonce);
String acceptSeed = key + MAGIC_GUID;
2012-01-19 05:12:45 +01:00
byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
expectedChallengeResponseString = WebSocketUtil.base64(sha1);
if (logger.isDebugEnabled()) {
logger.debug(
"WebSocket version 13 client handshake key: {}, expected response: {}",
key, expectedChallengeResponseString);
}
// Format request
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, upgradeUrl(wsURL),
Unpooled.EMPTY_BUFFER);
HttpHeaders headers = request.headers();
if (customHeaders != null) {
headers.add(customHeaders);
}
headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET)
.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE)
.set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key)
.set(HttpHeaderNames.HOST, websocketHostValue(wsURL))
.set(HttpHeaderNames.ORIGIN, websocketOriginValue(wsURL));
2013-01-17 07:06:46 +01:00
String expectedSubprotocol = expectedSubprotocol();
if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
}
headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "13");
return request;
}
/**
* <p>
* Process server response:
* </p>
*
* <pre>
* HTTP/1.1 101 Switching Protocols
* Upgrade: websocket
* Connection: Upgrade
* Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
* Sec-WebSocket-Protocol: chat
* </pre>
*
* @param response
* HTTP response returned from the server for the request sent by beginOpeningHandshake00().
* @throws WebSocketHandshakeException if handshake response is invalid.
*/
@Override
protected void verify(FullHttpResponse response) {
2012-01-19 05:12:45 +01:00
final HttpResponseStatus status = HttpResponseStatus.SWITCHING_PROTOCOLS;
final HttpHeaders headers = response.headers();
if (!response.status().equals(status)) {
throw new WebSocketHandshakeException("Invalid handshake response getStatus: " + response.status());
}
Fix backward compatibility from the previous backport Motivation: The commit 50e06442c3f2753c9b2a506f68ea70273b829e21 changed the type of the constants in HttpHeaders.Names and HttpHeaders.Values, making 4.1 backward-incompatible with 4.0. It also introduces newer utility classes such as HttpHeaderUtil, which deprecates most static methods in HttpHeaders. To ease the migration between 4.1 and 5.0, we should deprecate all static methods that are non-existent in 5.0, and provide proper counterpart. Modification: - Revert the changes in HttpHeaders.Names and Values - Deprecate all static methods in HttpHeaders in favor of: - HttpHeaderUtil - the member methods of HttpHeaders - AsciiString - Add integer and date access methods to HttpHeaders for easier future migration to 5.0 - Add HttpHeaderNames and HttpHeaderValues which provide standard HTTP constants in AsciiString - Deprecate HttpHeaders.Names and Values - Make HttpHeaderValues.WEBSOCKET lowercased because it's actually lowercased in all WebSocket versions but the oldest one - Add RtspHeaderNames and RtspHeaderValues which provide standard RTSP constants in AsciiString - Deprecate RtspHeaders.* - Do not use AsciiString.equalsIgnoreCase(CharSeq, CharSeq) if one of the parameters are AsciiString - Avoid using AsciiString.toString() repetitively - Change the parameter type of some methods from String to CharSequence Result: Backward compatibility is recovered. New classes and methods will make the migration to 5.0 easier, once (Http|Rtsp)Header(Names|Values) are ported to master.
2014-10-31 08:48:28 +01:00
CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
throw new WebSocketHandshakeException("Invalid handshake response upgrade: " + upgrade);
}
if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
throw new WebSocketHandshakeException("Invalid handshake response connection: "
+ headers.get(HttpHeaderNames.CONNECTION));
}
Fix backward compatibility from the previous backport Motivation: The commit 50e06442c3f2753c9b2a506f68ea70273b829e21 changed the type of the constants in HttpHeaders.Names and HttpHeaders.Values, making 4.1 backward-incompatible with 4.0. It also introduces newer utility classes such as HttpHeaderUtil, which deprecates most static methods in HttpHeaders. To ease the migration between 4.1 and 5.0, we should deprecate all static methods that are non-existent in 5.0, and provide proper counterpart. Modification: - Revert the changes in HttpHeaders.Names and Values - Deprecate all static methods in HttpHeaders in favor of: - HttpHeaderUtil - the member methods of HttpHeaders - AsciiString - Add integer and date access methods to HttpHeaders for easier future migration to 5.0 - Add HttpHeaderNames and HttpHeaderValues which provide standard HTTP constants in AsciiString - Deprecate HttpHeaders.Names and Values - Make HttpHeaderValues.WEBSOCKET lowercased because it's actually lowercased in all WebSocket versions but the oldest one - Add RtspHeaderNames and RtspHeaderValues which provide standard RTSP constants in AsciiString - Deprecate RtspHeaders.* - Do not use AsciiString.equalsIgnoreCase(CharSeq, CharSeq) if one of the parameters are AsciiString - Avoid using AsciiString.toString() repetitively - Change the parameter type of some methods from String to CharSequence Result: Backward compatibility is recovered. New classes and methods will make the migration to 5.0 easier, once (Http|Rtsp)Header(Names|Values) are ported to master.
2014-10-31 08:48:28 +01:00
CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
2012-01-19 05:12:45 +01:00
if (accept == null || !accept.equals(expectedChallengeResponseString)) {
throw new WebSocketHandshakeException(String.format(
"Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString));
}
}
@Override
protected WebSocketFrameDecoder newWebsocketDecoder() {
return new WebSocket13FrameDecoder(false, allowExtensions, maxFramePayloadLength(), allowMaskMismatch);
}
@Override
protected WebSocketFrameEncoder newWebSocketEncoder() {
return new WebSocket13FrameEncoder(performMasking);
}
@Override
public WebSocketClientHandshaker13 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) {
super.setForceCloseTimeoutMillis(forceCloseTimeoutMillis);
return this;
}
}