Search in sources :

Example 81 with DefaultFullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse in project netty by netty.

the class WebSocketServerHandshakerFactory method sendUnsupportedVersionResponse.

/**
 * Return that we need cannot not support the web socket version
 */
public static ChannelFuture sendUnsupportedVersionResponse(Channel channel, ChannelPromise promise) {
    HttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UPGRADE_REQUIRED, channel.alloc().buffer(0));
    res.headers().set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, WebSocketVersion.V13.toHttpHeaderValue());
    HttpUtil.setContentLength(res, 0);
    return channel.writeAndFlush(res, promise);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse)

Example 82 with DefaultFullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse in project netty by netty.

the class WebSocketServerProtocolHandler method exceptionCaught.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (cause instanceof WebSocketHandshakeException) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST, Unpooled.wrappedBuffer(cause.getMessage().getBytes()));
        ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        ctx.fireExceptionCaught(cause);
        ctx.close();
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Example 83 with DefaultFullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse in project netty by netty.

the class WebSocketServerHandshaker00 method newHandshakeResponse.

/**
 * <p>
 * Handle the web socket handshake for the web socket specification <a href=
 * "https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00">HyBi version 0</a> and lower. This standard
 * is really a rehash of <a href="https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76" >hixie-76</a> and
 * <a href="https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75" >hixie-75</a>.
 * </p>
 *
 * <p>
 * Browser request to the server:
 * </p>
 *
 * <pre>
 * GET /demo HTTP/1.1
 * Upgrade: WebSocket
 * Connection: Upgrade
 * Host: example.com
 * Origin: http://example.com
 * Sec-WebSocket-Protocol: chat, sample
 * Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5
 * Sec-WebSocket-Key2: 12998 5 Y3 1  .P00
 *
 * ^n:ds[4U
 * </pre>
 *
 * <p>
 * Server response:
 * </p>
 *
 * <pre>
 * HTTP/1.1 101 WebSocket Protocol Handshake
 * Upgrade: WebSocket
 * Connection: Upgrade
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Location: ws://example.com/demo
 * Sec-WebSocket-Protocol: sample
 *
 * 8jKS'y:G*Co,Wxa-
 * </pre>
 */
@Override
protected FullHttpResponse newHandshakeResponse(FullHttpRequest req, HttpHeaders headers) {
    // Serve the WebSocket handshake request.
    if (!req.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true) || !HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(req.headers().get(HttpHeaderNames.UPGRADE))) {
        throw new WebSocketServerHandshakeException("not a WebSocket handshake request: missing upgrade", req);
    }
    // Hixie 75 does not contain these headers while Hixie 76 does
    boolean isHixie76 = req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY1) && req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY2);
    String origin = req.headers().get(HttpHeaderNames.ORIGIN);
    // throw before allocating FullHttpResponse
    if (origin == null && !isHixie76) {
        throw new WebSocketServerHandshakeException("Missing origin header, got only " + req.headers().names(), req);
    }
    // Create the WebSocket handshake response.
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, new HttpResponseStatus(101, isHixie76 ? "WebSocket Protocol Handshake" : "Web Socket Protocol Handshake"), req.content().alloc().buffer(0));
    if (headers != null) {
        res.headers().add(headers);
    }
    res.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET).set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE);
    // Fill in the headers and contents depending on handshake getMethod.
    if (isHixie76) {
        // New handshake getMethod with a challenge:
        res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, origin);
        res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_LOCATION, uri());
        String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
        if (subprotocols != null) {
            String selectedSubprotocol = selectSubprotocol(subprotocols);
            if (selectedSubprotocol == null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Requested subprotocol(s) not supported: {}", subprotocols);
                }
            } else {
                res.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, selectedSubprotocol);
            }
        }
        // Calculate the answer of the challenge.
        String key1 = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY1);
        String key2 = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY2);
        int a = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key1).replaceAll("")) / BEGINNING_SPACE.matcher(key1).replaceAll("").length());
        int b = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key2).replaceAll("")) / BEGINNING_SPACE.matcher(key2).replaceAll("").length());
        long c = req.content().readLong();
        ByteBuf input = Unpooled.wrappedBuffer(new byte[16]).setIndex(0, 0);
        input.writeInt(a);
        input.writeInt(b);
        input.writeLong(c);
        res.content().writeBytes(WebSocketUtil.md5(input.array()));
    } else {
        // Old Hixie 75 handshake getMethod with no challenge:
        res.headers().add(HttpHeaderNames.WEBSOCKET_ORIGIN, origin);
        res.headers().add(HttpHeaderNames.WEBSOCKET_LOCATION, uri());
        String protocol = req.headers().get(HttpHeaderNames.WEBSOCKET_PROTOCOL);
        if (protocol != null) {
            res.headers().set(HttpHeaderNames.WEBSOCKET_PROTOCOL, selectSubprotocol(protocol));
        }
    }
    return res;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ByteBuf(io.netty.buffer.ByteBuf)

Example 84 with DefaultFullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse in project netty by netty.

the class SpdyHttpDecoder method createHttpResponse.

private static FullHttpResponse createHttpResponse(SpdyHeadersFrame responseFrame, ByteBufAllocator alloc, boolean validateHeaders) throws Exception {
    // Create the first line of the response from the name/value pairs
    SpdyHeaders headers = responseFrame.headers();
    HttpResponseStatus status = HttpResponseStatus.parseLine(headers.get(STATUS));
    HttpVersion version = HttpVersion.valueOf(headers.getAsString(VERSION));
    headers.remove(STATUS);
    headers.remove(VERSION);
    boolean release = true;
    ByteBuf buffer = alloc.buffer();
    try {
        FullHttpResponse res = new DefaultFullHttpResponse(version, status, buffer, validateHeaders);
        for (Map.Entry<CharSequence, CharSequence> e : responseFrame.headers()) {
            res.headers().add(e.getKey(), e.getValue());
        }
        // The Connection and Keep-Alive headers are no longer valid
        HttpUtil.setKeepAlive(res, true);
        // Transfer-Encoding header is not valid
        res.headers().remove(HttpHeaderNames.TRANSFER_ENCODING);
        res.headers().remove(HttpHeaderNames.TRAILER);
        release = false;
        return res;
    } finally {
        if (release) {
            buffer.release();
        }
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ByteBuf(io.netty.buffer.ByteBuf) HttpVersion(io.netty.handler.codec.http.HttpVersion) HashMap(java.util.HashMap) Map(java.util.Map)

Example 85 with DefaultFullHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse in project netty by netty.

the class WebSocketServerProtocolHandshakeHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    final HttpObject httpObject = (HttpObject) msg;
    if (httpObject instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) httpObject;
        isWebSocketPath = isWebSocketPath(req);
        if (!isWebSocketPath) {
            ctx.fireChannelRead(msg);
            return;
        }
        try {
            if (!GET.equals(req.method())) {
                sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN, ctx.alloc().buffer(0)));
                return;
            }
            final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(ctx.pipeline(), req, serverConfig.websocketPath()), serverConfig.subprotocols(), serverConfig.decoderConfig());
            final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
            final ChannelPromise localHandshakePromise = handshakePromise;
            if (handshaker == null) {
                WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
            } else {
                // Ensure we set the handshaker and replace this handler before we
                // trigger the actual handshake. Otherwise we may receive websocket bytes in this handler
                // before we had a chance to replace it.
                // 
                // See https://github.com/netty/netty/issues/9471.
                WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
                ctx.pipeline().remove(this);
                final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
                handshakeFuture.addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) {
                        if (!future.isSuccess()) {
                            localHandshakePromise.tryFailure(future.cause());
                            ctx.fireExceptionCaught(future.cause());
                        } else {
                            localHandshakePromise.trySuccess();
                            // Kept for compatibility
                            ctx.fireUserEventTriggered(WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
                            ctx.fireUserEventTriggered(new WebSocketServerProtocolHandler.HandshakeComplete(req.uri(), req.headers(), handshaker.selectedSubprotocol()));
                        }
                    }
                });
                applyHandshakeTimeout();
            }
        } finally {
            ReferenceCountUtil.release(req);
        }
    } else if (!isWebSocketPath) {
        ctx.fireChannelRead(msg);
    } else {
        ReferenceCountUtil.release(msg);
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelFuture(io.netty.channel.ChannelFuture) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpObject(io.netty.handler.codec.http.HttpObject) ChannelPromise(io.netty.channel.ChannelPromise) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Aggregations

DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)223 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)145 ByteBuf (io.netty.buffer.ByteBuf)68 HttpResponse (io.netty.handler.codec.http.HttpResponse)39 Test (org.junit.Test)25 HttpRequest (io.netty.handler.codec.http.HttpRequest)24 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)23 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)22 ChannelFuture (io.netty.channel.ChannelFuture)19 IOException (java.io.IOException)19 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)16 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)16 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)15 HttpObject (io.netty.handler.codec.http.HttpObject)15 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)12 HttpVersion (io.netty.handler.codec.http.HttpVersion)12 InetSocketAddress (java.net.InetSocketAddress)12 SSLException (javax.net.ssl.SSLException)12 Test (org.junit.jupiter.api.Test)12 Map (java.util.Map)11