
io.netty5.handler.codec.http.websocketx.WebSocketServerProtocolHandler Maven / Gradle / Ivy
/*
* Copyright 2019 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:
*
* https://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.netty5.handler.codec.http.websocketx;
import io.netty5.channel.Channel;
import io.netty5.channel.ChannelFutureListeners;
import io.netty5.channel.ChannelHandler;
import io.netty5.channel.ChannelHandlerContext;
import io.netty5.channel.ChannelPipeline;
import io.netty5.handler.codec.http.DefaultFullHttpResponse;
import io.netty5.handler.codec.http.FullHttpResponse;
import io.netty5.handler.codec.http.HttpResponseStatus;
import io.netty5.util.AttributeKey;
import io.netty5.util.concurrent.Promise;
import java.util.Objects;
import static io.netty5.handler.codec.http.HttpVersion.HTTP_1_1;
import static io.netty5.handler.codec.http.websocketx.WebSocketServerProtocolConfig.DEFAULT_HANDSHAKE_TIMEOUT_MILLIS;
/**
* This handler does all the heavy lifting for you to run a websocket server.
*
* It takes care of websocket handshaking as well as processing of control frames (Close, Ping, Pong). Text and Binary
* data frames are passed to the next handler in the pipeline (implemented by you) for processing.
*
* See io.netty5.example.http.websocketx.html5.WebSocketServer for usage.
*
* The implementation of this handler assumes that you just want to run a websocket server and not process other types
* HTTP requests (like GET and POST). If you wish to support both HTTP requests and websockets in the one server, refer
* to the io.netty5.example.http.websocketx.server.WebSocketServer example.
*
* To know once a handshake was done you can intercept the
* {@link ChannelHandler#channelInboundEvent(ChannelHandlerContext, Object)} and check if the event was instance
* of {@link WebSocketServerHandshakeCompletionEvent}, the event will contain extra information about the handshake
* such as the request and selected subprotocol.
*/
public class WebSocketServerProtocolHandler extends WebSocketProtocolHandler {
private static final AttributeKey HANDSHAKER_ATTR_KEY =
AttributeKey.valueOf(WebSocketServerHandshaker.class, "HANDSHAKER");
private final WebSocketServerProtocolConfig serverConfig;
/**
* Base constructor
*
* @param serverConfig
* Server protocol configuration.
*/
public WebSocketServerProtocolHandler(WebSocketServerProtocolConfig serverConfig) {
super(Objects.requireNonNull(serverConfig, "serverConfig").dropPongFrames(),
serverConfig.sendCloseFrame(),
serverConfig.forceCloseTimeoutMillis()
);
this.serverConfig = serverConfig;
}
public WebSocketServerProtocolHandler(String websocketPath) {
this(websocketPath, DEFAULT_HANDSHAKE_TIMEOUT_MILLIS);
}
public WebSocketServerProtocolHandler(String websocketPath, long handshakeTimeoutMillis) {
this(websocketPath, false, handshakeTimeoutMillis);
}
public WebSocketServerProtocolHandler(String websocketPath, boolean checkStartsWith) {
this(websocketPath, checkStartsWith, DEFAULT_HANDSHAKE_TIMEOUT_MILLIS);
}
public WebSocketServerProtocolHandler(String websocketPath, boolean checkStartsWith, long handshakeTimeoutMillis) {
this(websocketPath, null, false, 65536, false, checkStartsWith, handshakeTimeoutMillis);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols) {
this(websocketPath, subprotocols, DEFAULT_HANDSHAKE_TIMEOUT_MILLIS);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, long handshakeTimeoutMillis) {
this(websocketPath, subprotocols, false, handshakeTimeoutMillis);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, boolean allowExtensions) {
this(websocketPath, subprotocols, allowExtensions, DEFAULT_HANDSHAKE_TIMEOUT_MILLIS);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, boolean allowExtensions,
long handshakeTimeoutMillis) {
this(websocketPath, subprotocols, allowExtensions, 65536, handshakeTimeoutMillis);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols,
boolean allowExtensions, int maxFrameSize) {
this(websocketPath, subprotocols, allowExtensions, maxFrameSize, DEFAULT_HANDSHAKE_TIMEOUT_MILLIS);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols,
boolean allowExtensions, int maxFrameSize, long handshakeTimeoutMillis) {
this(websocketPath, subprotocols, allowExtensions, maxFrameSize, false, handshakeTimeoutMillis);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols,
boolean allowExtensions, int maxFrameSize, boolean allowMaskMismatch) {
this(websocketPath, subprotocols, allowExtensions, maxFrameSize, allowMaskMismatch,
DEFAULT_HANDSHAKE_TIMEOUT_MILLIS);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, boolean allowExtensions,
int maxFrameSize, boolean allowMaskMismatch, long handshakeTimeoutMillis) {
this(websocketPath, subprotocols, allowExtensions, maxFrameSize, allowMaskMismatch, false,
handshakeTimeoutMillis);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols,
boolean allowExtensions, int maxFrameSize, boolean allowMaskMismatch, boolean checkStartsWith) {
this(websocketPath, subprotocols, allowExtensions, maxFrameSize, allowMaskMismatch, checkStartsWith,
DEFAULT_HANDSHAKE_TIMEOUT_MILLIS);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols,
boolean allowExtensions, int maxFrameSize, boolean allowMaskMismatch,
boolean checkStartsWith, long handshakeTimeoutMillis) {
this(websocketPath, subprotocols, allowExtensions, maxFrameSize, allowMaskMismatch, checkStartsWith, true,
handshakeTimeoutMillis);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols,
boolean allowExtensions, int maxFrameSize, boolean allowMaskMismatch,
boolean checkStartsWith, boolean dropPongFrames) {
this(websocketPath, subprotocols, allowExtensions, maxFrameSize, allowMaskMismatch, checkStartsWith,
dropPongFrames, DEFAULT_HANDSHAKE_TIMEOUT_MILLIS);
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, boolean allowExtensions,
int maxFrameSize, boolean allowMaskMismatch, boolean checkStartsWith,
boolean dropPongFrames, long handshakeTimeoutMillis) {
this(websocketPath, subprotocols, checkStartsWith, dropPongFrames, handshakeTimeoutMillis,
WebSocketDecoderConfig.newBuilder()
.maxFramePayloadLength(maxFrameSize)
.allowMaskMismatch(allowMaskMismatch)
.allowExtensions(allowExtensions)
.build());
}
public WebSocketServerProtocolHandler(String websocketPath, String subprotocols, boolean checkStartsWith,
boolean dropPongFrames, long handshakeTimeoutMillis,
WebSocketDecoderConfig decoderConfig) {
this(WebSocketServerProtocolConfig.newBuilder()
.websocketPath(websocketPath)
.subprotocols(subprotocols)
.checkStartsWith(checkStartsWith)
.handshakeTimeoutMillis(handshakeTimeoutMillis)
.dropPongFrames(dropPongFrames)
.decoderConfig(decoderConfig)
.build());
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
ChannelPipeline cp = ctx.pipeline();
if (cp.get(WebSocketServerProtocolHandshakeHandler.class) == null) {
// Add the WebSocketHandshakeHandler before this one.
cp.addBefore(ctx.name(), WebSocketServerProtocolHandshakeHandler.class.getName(),
new WebSocketServerProtocolHandshakeHandler(serverConfig));
}
if (serverConfig.decoderConfig().withUTF8Validator() && cp.get(Utf8FrameValidator.class) == null) {
// Add the UFT8 checking before this one.
cp.addBefore(ctx.name(), Utf8FrameValidator.class.getName(),
new Utf8FrameValidator(serverConfig.decoderConfig().closeOnProtocolViolation()));
}
}
@Override
protected void decodeAndClose(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
if (serverConfig.handleCloseFrames() && frame instanceof CloseWebSocketFrame) {
WebSocketServerHandshaker handshaker = getHandshaker(ctx.channel());
if (handshaker != null) {
Promise promise = ctx.newPromise();
closeSent(promise);
handshaker.close(ctx, (CloseWebSocketFrame) frame).cascadeTo(promise);
} else {
frame.close();
ctx.writeAndFlush(ctx.bufferAllocator().allocate(0)).addListener(ctx, ChannelFutureListeners.CLOSE);
}
return;
}
super.decodeAndClose(ctx, frame);
}
@Override
protected WebSocketServerHandshakeException buildHandshakeException(String message) {
return new WebSocketServerHandshakeException(message);
}
@Override
public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (cause instanceof WebSocketHandshakeException) {
final byte[] bytes = cause.getMessage().getBytes();
FullHttpResponse response = new DefaultFullHttpResponse(
HTTP_1_1, HttpResponseStatus.BAD_REQUEST,
ctx.bufferAllocator().allocate(bytes.length).writeBytes(bytes));
ctx.channel().writeAndFlush(response).addListener(ctx, ChannelFutureListeners.CLOSE);
} else {
ctx.fireChannelExceptionCaught(cause);
ctx.close();
}
}
static WebSocketServerHandshaker getHandshaker(Channel channel) {
return channel.attr(HANDSHAKER_ATTR_KEY).get();
}
static void setHandshaker(Channel channel, WebSocketServerHandshaker handshaker) {
channel.attr(HANDSHAKER_ATTR_KEY).set(handshaker);
}
}