Search in sources :

Example 1 with JdkSslContext

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.JdkSslContext in project jersey by jersey.

the class NettyConnector method apply.

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {
    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();
    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80;
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true, ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }
                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);
                    final String userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class);
                    p.addLast(new HttpProxyHandler(new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()), userName, password));
                }
                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback, settableFuture));
            }
        });
        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }
        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();
        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };
        ch.closeFuture().addListener(closeListener);
        HttpRequest nettyRequest;
        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }
        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }
        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());
        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }
        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {

                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });
            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }
            executorService.execute(new Runnable() {

                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);
                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });
            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }
    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }
    return settableFuture;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Configuration(javax.ws.rs.core.Configuration) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) CompletableFuture(java.util.concurrent.CompletableFuture) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap) List(java.util.List) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) JerseyChunkedInput(org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) JdkSslContext(io.netty.handler.ssl.JdkSslContext) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler) Map(java.util.Map)

Example 2 with JdkSslContext

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.JdkSslContext in project rest.li by linkedin.

the class Http2InitializerHandler method configureHttpsPipeline.

/**
   * Sets up HTTP/2 over TLS through ALPN (h2) pipeline
   */
private void configureHttpsPipeline(ChannelHandlerContext ctx) throws Exception {
    JdkSslContext context = new JdkSslContext(_sslContext, IS_CLIENT, Arrays.asList(_sslParameters.getCipherSuites()), IdentityCipherSuiteFilter.INSTANCE, new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1), _sslParameters.getNeedClientAuth() ? ClientAuth.REQUIRE : ClientAuth.OPTIONAL);
    SslHandler sslHandler = context.newHandler(ctx.alloc());
    Http2StreamCodec http2Codec = new Http2StreamCodecBuilder().connection(_connection).maxContentLength(_maxResponseSize).maxHeaderSize(_maxHeaderSize).gracefulShutdownTimeoutMillis(_gracefulShutdownTimeout).streamingTimeout(_streamingTimeout).scheduler(_scheduler).build();
    Http2AlpnHandler alpnHandler = new Http2AlpnHandler(sslHandler, http2Codec);
    Http2SchemeHandler schemeHandler = new Http2SchemeHandler(HttpScheme.HTTPS.toString());
    Http2StreamResponseHandler responseHandler = new Http2StreamResponseHandler();
    Http2ChannelPoolHandler channelPoolHandler = new Http2ChannelPoolHandler();
    ctx.pipeline().addBefore(ctx.name(), "alpnHandler", alpnHandler);
    ctx.pipeline().addBefore(ctx.name(), "schemeHandler", schemeHandler);
    ctx.pipeline().addBefore(ctx.name(), "responseHandler", responseHandler);
    ctx.pipeline().addBefore(ctx.name(), "channelHandler", channelPoolHandler);
    _setupComplete = true;
}
Also used : JdkSslContext(io.netty.handler.ssl.JdkSslContext) SslHandler(io.netty.handler.ssl.SslHandler) ApplicationProtocolConfig(io.netty.handler.ssl.ApplicationProtocolConfig)

Example 3 with JdkSslContext

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.JdkSslContext in project camel by apache.

the class WebsocketSSLContextInUriRouteExampleTest method createAsyncHttpSSLClient.

protected AsyncHttpClient createAsyncHttpSSLClient() throws IOException, GeneralSecurityException {
    AsyncHttpClient c;
    AsyncHttpClientConfig config;
    DefaultAsyncHttpClientConfig.Builder builder = new DefaultAsyncHttpClientConfig.Builder();
    SSLContext sslContext = new SSLContextParameters().createSSLContext(context());
    JdkSslContext ssl = new JdkSslContext(sslContext, true, ClientAuth.REQUIRE);
    builder.setSslContext(ssl);
    builder.setAcceptAnyCertificate(true);
    config = builder.build();
    c = new DefaultAsyncHttpClient(config);
    return c;
}
Also used : JdkSslContext(io.netty.handler.ssl.JdkSslContext) RouteBuilder(org.apache.camel.builder.RouteBuilder) AsyncHttpClientConfig(org.asynchttpclient.AsyncHttpClientConfig) DefaultAsyncHttpClientConfig(org.asynchttpclient.DefaultAsyncHttpClientConfig) DefaultAsyncHttpClientConfig(org.asynchttpclient.DefaultAsyncHttpClientConfig) DefaultAsyncHttpClient(org.asynchttpclient.DefaultAsyncHttpClient) SSLContext(javax.net.ssl.SSLContext) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) DefaultAsyncHttpClient(org.asynchttpclient.DefaultAsyncHttpClient) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters)

Example 4 with JdkSslContext

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.JdkSslContext in project camel by apache.

the class WebsocketSSLRouteExampleTest method createAsyncHttpSSLClient.

protected AsyncHttpClient createAsyncHttpSSLClient() throws IOException, GeneralSecurityException {
    AsyncHttpClient c;
    AsyncHttpClientConfig config;
    DefaultAsyncHttpClientConfig.Builder builder = new DefaultAsyncHttpClientConfig.Builder();
    SSLContext sslContext = new SSLContextParameters().createSSLContext(context());
    JdkSslContext ssl = new JdkSslContext(sslContext, true, ClientAuth.REQUIRE);
    builder.setSslContext(ssl);
    builder.setAcceptAnyCertificate(true);
    config = builder.build();
    c = new DefaultAsyncHttpClient(config);
    return c;
}
Also used : JdkSslContext(io.netty.handler.ssl.JdkSslContext) RouteBuilder(org.apache.camel.builder.RouteBuilder) AsyncHttpClientConfig(org.asynchttpclient.AsyncHttpClientConfig) DefaultAsyncHttpClientConfig(org.asynchttpclient.DefaultAsyncHttpClientConfig) DefaultAsyncHttpClientConfig(org.asynchttpclient.DefaultAsyncHttpClientConfig) DefaultAsyncHttpClient(org.asynchttpclient.DefaultAsyncHttpClient) SSLContext(javax.net.ssl.SSLContext) AsyncHttpClient(org.asynchttpclient.AsyncHttpClient) DefaultAsyncHttpClient(org.asynchttpclient.DefaultAsyncHttpClient) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters)

Example 5 with JdkSslContext

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.JdkSslContext in project vert.x by eclipse.

the class SSLEngineTest method doTest.

private void doTest(SSLEngineOptions engine, boolean useAlpn, HttpVersion version, String error, String expectedSslContext, boolean expectCause) {
    server.close();
    HttpServerOptions options = new HttpServerOptions().setSslEngineOptions(engine).setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST).setKeyCertOptions(Cert.SERVER_PEM.get()).setSsl(true).setUseAlpn(useAlpn);
    server = vertx.createHttpServer(options);
    server.requestHandler(req -> {
        assertEquals(req.version(), version);
        assertTrue(req.isSSL());
        req.response().end();
    });
    try {
        startServer();
        if (error != null) {
            fail("Was expecting failure: " + error);
        }
    } catch (Exception e) {
        if (error == null) {
            fail(e);
        } else {
            assertEquals(error, e.getMessage());
            if (expectCause) {
                assertNotSame(e, e.getCause());
            }
            return;
        }
    }
    SSLHelper sslHelper = ((HttpServerImpl) server).sslHelper();
    SslContext ctx = sslHelper.getContext((VertxInternal) vertx);
    switch(expectedSslContext != null ? expectedSslContext : "jdk") {
        case "jdk":
            assertTrue(ctx instanceof JdkSslContext);
            break;
        case "openssl":
            assertTrue(ctx instanceof OpenSslContext);
            break;
    }
    client = vertx.createHttpClient(new HttpClientOptions().setSslEngineOptions(engine).setSsl(true).setUseAlpn(useAlpn).setTrustAll(true).setProtocolVersion(version));
    client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", onSuccess(req -> {
        req.send(onSuccess(resp -> {
            assertEquals(200, resp.statusCode());
            testComplete();
        }));
    }));
    await();
}
Also used : SSLHelper(io.vertx.core.net.impl.SSLHelper) VertxException(io.vertx.core.VertxException) HttpServerImpl(io.vertx.core.http.impl.HttpServerImpl) SSLEngineOptions(io.vertx.core.net.SSLEngineOptions) VertxInternal(io.vertx.core.impl.VertxInternal) JdkSslContext(io.netty.handler.ssl.JdkSslContext) SslContext(io.netty.handler.ssl.SslContext) OpenSslContext(io.netty.handler.ssl.OpenSslContext) Test(org.junit.Test) SSLHelper(io.vertx.core.net.impl.SSLHelper) OpenSSLEngineOptions(io.vertx.core.net.OpenSSLEngineOptions) HttpTestBase(io.vertx.core.http.HttpTestBase) HttpVersion(io.vertx.core.http.HttpVersion) HttpMethod(io.vertx.core.http.HttpMethod) Cert(io.vertx.test.tls.Cert) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpClientOptions(io.vertx.core.http.HttpClientOptions) JdkSSLEngineOptions(io.vertx.core.net.JdkSSLEngineOptions) JdkSslContext(io.netty.handler.ssl.JdkSslContext) OpenSslContext(io.netty.handler.ssl.OpenSslContext) HttpServerOptions(io.vertx.core.http.HttpServerOptions) VertxException(io.vertx.core.VertxException) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpServerImpl(io.vertx.core.http.impl.HttpServerImpl) JdkSslContext(io.netty.handler.ssl.JdkSslContext) SslContext(io.netty.handler.ssl.SslContext) OpenSslContext(io.netty.handler.ssl.OpenSslContext)

Aggregations

JdkSslContext (io.netty.handler.ssl.JdkSslContext)14 SslContext (io.netty.handler.ssl.SslContext)4 SSLContext (javax.net.ssl.SSLContext)4 OpenSslContext (io.netty.handler.ssl.OpenSslContext)3 Channel (io.netty.channel.Channel)2 EventLoopGroup (io.netty.channel.EventLoopGroup)2 SocketChannel (io.netty.channel.socket.SocketChannel)2 ApplicationProtocolConfig (io.netty.handler.ssl.ApplicationProtocolConfig)2 SslHandler (io.netty.handler.ssl.SslHandler)2 VertxException (io.vertx.core.VertxException)2 HttpClientOptions (io.vertx.core.http.HttpClientOptions)2 HttpServerOptions (io.vertx.core.http.HttpServerOptions)2 HttpVersion (io.vertx.core.http.HttpVersion)2 HttpServerImpl (io.vertx.core.http.impl.HttpServerImpl)2 VertxInternal (io.vertx.core.impl.VertxInternal)2 JdkSSLEngineOptions (io.vertx.core.net.JdkSSLEngineOptions)2 OpenSSLEngineOptions (io.vertx.core.net.OpenSSLEngineOptions)2 SSLEngineOptions (io.vertx.core.net.SSLEngineOptions)2 SSLHelper (io.vertx.core.net.impl.SSLHelper)2 List (java.util.List)2