Search in sources :

Example 16 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project component-runtime by Talend.

the class ServingProxyHandler method channelRead0.

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;
    }
    api.getExecutor().execute(() -> {
        final Map<String, String> headers = StreamSupport.stream(Spliterators.spliteratorUnknownSize(request.headers().iteratorAsString(), Spliterator.IMMUTABLE), false).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
        final Attribute<String> baseAttr = ctx.channel().attr(Handlers.BASE);
        Optional<Response> matching = api.getResponseLocator().findMatching(new RequestImpl((baseAttr == null || baseAttr.get() == null ? "" : baseAttr.get()) + request.uri(), request.method().name(), headers), api.getHeaderFilter());
        if (!matching.isPresent()) {
            if (HttpMethod.CONNECT.name().equalsIgnoreCase(request.method().name())) {
                final Map<String, String> responseHeaders = new HashMap<>();
                responseHeaders.put(HttpHeaderNames.CONNECTION.toString(), HttpHeaderValues.KEEP_ALIVE.toString());
                responseHeaders.put(HttpHeaderNames.CONTENT_LENGTH.toString(), "0");
                matching = of(new ResponseImpl(responseHeaders, HttpResponseStatus.OK.code(), Unpooled.EMPTY_BUFFER.array()));
                if (api.getSslContext() != null) {
                    final SSLEngine sslEngine = api.getSslContext().createSSLEngine();
                    sslEngine.setUseClientMode(false);
                    ctx.channel().pipeline().addFirst("ssl", new SslHandler(sslEngine, true));
                    final String uri = request.uri();
                    final String[] parts = uri.split(":");
                    ctx.channel().attr(Handlers.BASE).set("https://" + parts[0] + (parts.length > 1 && !"443".equals(parts[1]) ? ":" + parts[1] : ""));
                }
            } else {
                sendError(ctx, new HttpResponseStatus(HttpURLConnection.HTTP_BAD_REQUEST, "You are in proxy mode. No response was found for the simulated request. Please ensure to capture it for next executions. " + request.method().name() + " " + request.uri()));
                return;
            }
        }
        final Response resp = matching.get();
        final ByteBuf bytes = ofNullable(resp.payload()).map(Unpooled::copiedBuffer).orElse(Unpooled.EMPTY_BUFFER);
        final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(resp.status()), bytes);
        HttpUtil.setContentLength(response, bytes.array().length);
        if (!api.isSkipProxyHeaders()) {
            response.headers().set("X-Talend-Proxy-JUnit", "true");
        }
        ofNullable(resp.headers()).ifPresent(h -> h.forEach((k, v) -> response.headers().set(k, v)));
        ctx.writeAndFlush(response);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) HttpVersion(io.netty.handler.codec.http.HttpVersion) Handlers.sendError(org.talend.sdk.component.junit.http.internal.impl.Handlers.sendError) Handlers.closeOnFlush(org.talend.sdk.component.junit.http.internal.impl.Handlers.closeOnFlush) Spliterators(java.util.Spliterators) Optional.of(java.util.Optional.of) Response(org.talend.sdk.component.junit.http.api.Response) HashMap(java.util.HashMap) SSLEngine(javax.net.ssl.SSLEngine) HttpApiHandler(org.talend.sdk.component.junit.http.api.HttpApiHandler) Unpooled(io.netty.buffer.Unpooled) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Collectors.toMap(java.util.stream.Collectors.toMap) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) StreamSupport(java.util.stream.StreamSupport) Attribute(io.netty.util.Attribute) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) Optional.ofNullable(java.util.Optional.ofNullable) HttpMethod(io.netty.handler.codec.http.HttpMethod) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Slf4j(lombok.extern.slf4j.Slf4j) SslHandler(io.netty.handler.ssl.SslHandler) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Optional(java.util.Optional) ChannelHandler(io.netty.channel.ChannelHandler) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AllArgsConstructor(lombok.AllArgsConstructor) Spliterator(java.util.Spliterator) HttpUtil(io.netty.handler.codec.http.HttpUtil) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HashMap(java.util.HashMap) SSLEngine(javax.net.ssl.SSLEngine) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ByteBuf(io.netty.buffer.ByteBuf) SslHandler(io.netty.handler.ssl.SslHandler) Response(org.talend.sdk.component.junit.http.api.Response) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HashMap(java.util.HashMap) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map)

Example 17 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project netty by netty.

the class WebSocketClientHandshaker07 method verify.

/**
 * <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
 */
@Override
protected void verify(FullHttpResponse response) {
    HttpResponseStatus status = response.status();
    if (!HttpResponseStatus.SWITCHING_PROTOCOLS.equals(status)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response getStatus: " + status, response);
    }
    HttpHeaders headers = response.headers();
    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response upgrade: " + upgrade, response);
    }
    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response connection: " + headers.get(HttpHeaderNames.CONNECTION), response);
    }
    CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketClientHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString), response);
    }
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus)

Example 18 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project netty by netty.

the class WebSocketClientHandshaker13 method verify.

/**
 * <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) {
    HttpResponseStatus status = response.status();
    if (!HttpResponseStatus.SWITCHING_PROTOCOLS.equals(status)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response getStatus: " + status, response);
    }
    HttpHeaders headers = response.headers();
    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response upgrade: " + upgrade, response);
    }
    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response connection: " + headers.get(HttpHeaderNames.CONNECTION), response);
    }
    CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketClientHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString), response);
    }
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus)

Example 19 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus in project netty by netty.

the class WebSocketClientHandshaker08 method verify.

/**
 * <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
 */
@Override
protected void verify(FullHttpResponse response) {
    HttpResponseStatus status = response.status();
    if (!HttpResponseStatus.SWITCHING_PROTOCOLS.equals(status)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response getStatus: " + status, response);
    }
    HttpHeaders headers = response.headers();
    CharSequence upgrade = headers.get(HttpHeaderNames.UPGRADE);
    if (!HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(upgrade)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response upgrade: " + upgrade, response);
    }
    if (!headers.containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {
        throw new WebSocketClientHandshakeException("Invalid handshake response connection: " + headers.get(HttpHeaderNames.CONNECTION), response);
    }
    CharSequence accept = headers.get(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT);
    if (accept == null || !accept.equals(expectedChallengeResponseString)) {
        throw new WebSocketClientHandshakeException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, expectedChallengeResponseString), response);
    }
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus)

Example 20 with HttpResponseStatus

use of io.netty.handler.codec.http.HttpResponseStatus 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)

Aggregations

HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)53 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)16 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)15 ByteBuf (io.netty.buffer.ByteBuf)14 HttpResponse (io.netty.handler.codec.http.HttpResponse)9 HttpVersion (io.netty.handler.codec.http.HttpVersion)8 IOException (java.io.IOException)8 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)7 HttpMethod (io.netty.handler.codec.http.HttpMethod)7 Test (org.junit.Test)7 Map (java.util.Map)5 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)4 HttpRequest (io.netty.handler.codec.http.HttpRequest)4 NoSuchElementException (java.util.NoSuchElementException)4 ChannelFuture (io.netty.channel.ChannelFuture)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)3 PrintWriter (java.io.PrintWriter)3 List (java.util.List)3 Unpooled (io.netty.buffer.Unpooled)2