Search in sources :

Example 86 with LocalAddress

use of io.netty.channel.local.LocalAddress in project netty by netty.

the class HttpProxyHandlerTest method testExceptionDuringConnect.

@Test
public void testExceptionDuringConnect() throws Exception {
    EventLoopGroup group = null;
    Channel serverChannel = null;
    Channel clientChannel = null;
    try {
        group = new DefaultEventLoopGroup(1);
        final LocalAddress addr = new LocalAddress("a");
        final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
        ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class).group(group).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addFirst(new HttpResponseEncoder());
                DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_GATEWAY);
                response.headers().add("name", "value");
                response.headers().add(HttpHeaderNames.CONTENT_LENGTH, "0");
                ch.writeAndFlush(response);
            }
        }).bind(addr);
        serverChannel = sf.sync().channel();
        ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).group(group).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addFirst(new HttpProxyHandler(addr));
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        exception.set(cause);
                    }
                });
            }
        }).connect(new InetSocketAddress("localhost", 1234));
        clientChannel = cf.sync().channel();
        clientChannel.close().sync();
        assertTrue(exception.get() instanceof HttpProxyConnectException);
        HttpProxyConnectException actual = (HttpProxyConnectException) exception.get();
        assertNotNull(actual.headers());
        assertEquals("value", actual.headers().get("name"));
    } finally {
        if (clientChannel != null) {
            clientChannel.close();
        }
        if (serverChannel != null) {
            serverChannel.close();
        }
        if (group != null) {
            group.shutdownGracefully();
        }
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpProxyConnectException(io.netty.handler.proxy.HttpProxyHandler.HttpProxyConnectException) LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) InetSocketAddress(java.net.InetSocketAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 87 with LocalAddress

use of io.netty.channel.local.LocalAddress in project netty by netty.

the class OpenSslPrivateKeyMethodTest method testPrivateKeyMethod.

@ParameterizedTest(name = "{index}: delegate = {0}, async = {1}, newThread={2}")
@MethodSource("parameters")
public void testPrivateKeyMethod(final boolean delegate, boolean async, boolean newThread) throws Exception {
    final AtomicBoolean signCalled = new AtomicBoolean();
    OpenSslPrivateKeyMethod keyMethod = new OpenSslPrivateKeyMethod() {

        @Override
        public byte[] sign(SSLEngine engine, int signatureAlgorithm, byte[] input) throws Exception {
            signCalled.set(true);
            assertThread(delegate);
            assertEquals(CERT.cert().getPublicKey(), engine.getSession().getLocalCertificates()[0].getPublicKey());
            // Delegate signing to Java implementation.
            final Signature signature;
            // Depending on the Java version it will pick one or the other.
            if (signatureAlgorithm == OpenSslPrivateKeyMethod.SSL_SIGN_RSA_PKCS1_SHA256) {
                signature = Signature.getInstance("SHA256withRSA");
            } else if (signatureAlgorithm == OpenSslPrivateKeyMethod.SSL_SIGN_RSA_PSS_RSAE_SHA256) {
                signature = Signature.getInstance("RSASSA-PSS");
                signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1));
            } else {
                throw new AssertionError("Unexpected signature algorithm " + signatureAlgorithm);
            }
            signature.initSign(CERT.key());
            signature.update(input);
            return signature.sign();
        }

        @Override
        public byte[] decrypt(SSLEngine engine, byte[] input) {
            throw new UnsupportedOperationException();
        }
    };
    final SslContext sslServerContext = async ? buildServerContext(new OpenSslPrivateKeyMethodAdapter(keyMethod, newThread)) : buildServerContext(keyMethod);
    final SslContext sslClientContext = buildClientContext();
    try {
        try {
            final Promise<Object> serverPromise = GROUP.next().newPromise();
            final Promise<Object> clientPromise = GROUP.next().newPromise();
            ChannelHandler serverHandler = new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(newSslHandler(sslServerContext, ch.alloc(), delegateExecutor(delegate)));
                    pipeline.addLast(new SimpleChannelInboundHandler<Object>() {

                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) {
                            serverPromise.cancel(true);
                            ctx.fireChannelInactive();
                        }

                        @Override
                        public void channelRead0(ChannelHandlerContext ctx, Object msg) {
                            if (serverPromise.trySuccess(null)) {
                                ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 'P', 'O', 'N', 'G' }));
                            }
                            ctx.close();
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                            if (!serverPromise.tryFailure(cause)) {
                                ctx.fireExceptionCaught(cause);
                            }
                        }
                    });
                }
            };
            LocalAddress address = new LocalAddress("test-" + SslProvider.OPENSSL + '-' + SslProvider.JDK + '-' + RFC_CIPHER_NAME + '-' + delegate);
            Channel server = server(address, serverHandler);
            try {
                ChannelHandler clientHandler = new ChannelInitializer<Channel>() {

                    @Override
                    protected void initChannel(Channel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(newSslHandler(sslClientContext, ch.alloc(), delegateExecutor(delegate)));
                        pipeline.addLast(new SimpleChannelInboundHandler<Object>() {

                            @Override
                            public void channelInactive(ChannelHandlerContext ctx) {
                                clientPromise.cancel(true);
                                ctx.fireChannelInactive();
                            }

                            @Override
                            public void channelRead0(ChannelHandlerContext ctx, Object msg) {
                                clientPromise.trySuccess(null);
                                ctx.close();
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                if (!clientPromise.tryFailure(cause)) {
                                    ctx.fireExceptionCaught(cause);
                                }
                            }
                        });
                    }
                };
                Channel client = client(server, clientHandler);
                try {
                    client.writeAndFlush(Unpooled.wrappedBuffer(new byte[] { 'P', 'I', 'N', 'G' })).syncUninterruptibly();
                    assertTrue(clientPromise.await(5L, TimeUnit.SECONDS), "client timeout");
                    assertTrue(serverPromise.await(5L, TimeUnit.SECONDS), "server timeout");
                    clientPromise.sync();
                    serverPromise.sync();
                    assertTrue(signCalled.get());
                } finally {
                    client.close().sync();
                }
            } finally {
                server.close().sync();
            }
        } finally {
            ReferenceCountUtil.release(sslClientContext);
        }
    } finally {
        ReferenceCountUtil.release(sslServerContext);
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) SSLEngine(javax.net.ssl.SSLEngine) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PSSParameterSpec(java.security.spec.PSSParameterSpec) Signature(java.security.Signature) ChannelInitializer(io.netty.channel.ChannelInitializer) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 88 with LocalAddress

use of io.netty.channel.local.LocalAddress in project netty by netty.

the class SniClientTest method testSniClient.

@ParameterizedTest(name = PARAMETERIZED_NAME)
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
@MethodSource("parameters")
public void testSniClient(SslProvider sslServerProvider, SslProvider sslClientProvider) throws Exception {
    String sniHostName = "sni.netty.io";
    LocalAddress address = new LocalAddress("test");
    EventLoopGroup group = new DefaultEventLoopGroup(1);
    SelfSignedCertificate cert = new SelfSignedCertificate();
    SslContext sslServerContext = null;
    SslContext sslClientContext = null;
    Channel sc = null;
    Channel cc = null;
    try {
        if ((sslServerProvider == SslProvider.OPENSSL || sslServerProvider == SslProvider.OPENSSL_REFCNT) && !OpenSsl.useKeyManagerFactory()) {
            sslServerContext = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()).sslProvider(sslServerProvider).build();
        } else {
            // The used OpenSSL version does support a KeyManagerFactory, so use it.
            KeyManagerFactory kmf = PlatformDependent.javaVersion() >= 8 ? SniClientJava8TestUtil.newSniX509KeyManagerFactory(cert, sniHostName) : SslContext.buildKeyManagerFactory(new X509Certificate[] { cert.cert() }, null, cert.key(), null, null, null);
            sslServerContext = SslContextBuilder.forServer(kmf).sslProvider(sslServerProvider).build();
        }
        final SslContext finalContext = sslServerContext;
        final Promise<String> promise = group.next().newPromise();
        ServerBootstrap sb = new ServerBootstrap();
        sc = sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addFirst(new SniHandler(new Mapping<String, SslContext>() {

                    @Override
                    public SslContext map(String input) {
                        promise.setSuccess(input);
                        return finalContext;
                    }
                }));
            }
        }).bind(address).syncUninterruptibly().channel();
        TrustManagerFactory tmf = PlatformDependent.javaVersion() >= 8 ? SniClientJava8TestUtil.newSniX509TrustmanagerFactory(sniHostName) : InsecureTrustManagerFactory.INSTANCE;
        sslClientContext = SslContextBuilder.forClient().trustManager(tmf).sslProvider(sslClientProvider).build();
        Bootstrap cb = new Bootstrap();
        SslHandler handler = new SslHandler(sslClientContext.newEngine(ByteBufAllocator.DEFAULT, sniHostName, -1));
        cc = cb.group(group).channel(LocalChannel.class).handler(handler).connect(address).syncUninterruptibly().channel();
        assertEquals(sniHostName, promise.syncUninterruptibly().getNow());
        // After we are done with handshaking getHandshakeSession() should return null.
        handler.handshakeFuture().syncUninterruptibly();
        assertNull(handler.engine().getHandshakeSession());
        if (PlatformDependent.javaVersion() >= 8) {
            SniClientJava8TestUtil.assertSSLSession(handler.engine().getUseClientMode(), handler.engine().getSession(), sniHostName);
        }
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        ReferenceCountUtil.release(sslServerContext);
        ReferenceCountUtil.release(sslClientContext);
        cert.delete();
        group.shutdownGracefully();
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) X509Certificate(java.security.cert.X509Certificate) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SSLException(javax.net.ssl.SSLException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Timeout(org.junit.jupiter.api.Timeout) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 89 with LocalAddress

use of io.netty.channel.local.LocalAddress in project netty by netty.

the class OpenSslCertificateCompressionTest method runCertCompressionTest.

public void runCertCompressionTest(SslContext clientSslContext, SslContext serverSslContext) throws Throwable {
    EventLoopGroup group = new LocalEventLoopGroup();
    Promise<Object> clientPromise = group.next().newPromise();
    Promise<Object> serverPromise = group.next().newPromise();
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(LocalServerChannel.class).childHandler(new CertCompressionTestChannelInitializer(serverPromise, serverSslContext));
        Channel serverChannel = sb.bind(new LocalAddress("testCertificateCompression")).syncUninterruptibly().channel();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(LocalChannel.class).handler(new CertCompressionTestChannelInitializer(clientPromise, clientSslContext));
        Channel clientChannel = bootstrap.connect(serverChannel.localAddress()).syncUninterruptibly().channel();
        assertTrue(clientPromise.await(5L, TimeUnit.SECONDS), "client timeout");
        assertTrue(serverPromise.await(5L, TimeUnit.SECONDS), "server timeout");
        clientPromise.sync();
        serverPromise.sync();
        clientChannel.close().syncUninterruptibly();
        serverChannel.close().syncUninterruptibly();
    } finally {
        group.shutdownGracefully();
    }
}
Also used : EventLoopGroup(io.netty.channel.EventLoopGroup) LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalEventLoopGroup(io.netty.channel.local.LocalEventLoopGroup) LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 90 with LocalAddress

use of io.netty.channel.local.LocalAddress in project netty by netty.

the class OcspTest method handshake.

private static void handshake(SslProvider sslProvider, CountDownLatch latch, ChannelHandler serverHandler, byte[] response, ChannelHandler clientHandler, OcspClientCallback callback) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    try {
        SslContext serverSslContext = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(sslProvider).enableOcsp(true).build();
        try {
            SslContext clientSslContext = SslContextBuilder.forClient().sslProvider(sslProvider).enableOcsp(true).trustManager(InsecureTrustManagerFactory.INSTANCE).build();
            try {
                EventLoopGroup group = new DefaultEventLoopGroup();
                try {
                    LocalAddress address = new LocalAddress("handshake-" + Math.random());
                    Channel server = newServer(group, address, serverSslContext, response, serverHandler);
                    Channel client = newClient(group, address, clientSslContext, callback, clientHandler);
                    try {
                        assertTrue(latch.await(10L, TimeUnit.SECONDS));
                    } finally {
                        client.close().syncUninterruptibly();
                        server.close().syncUninterruptibly();
                    }
                } finally {
                    group.shutdownGracefully(1L, 1L, TimeUnit.SECONDS);
                }
            } finally {
                ReferenceCountUtil.release(clientSslContext);
            }
        } finally {
            ReferenceCountUtil.release(serverSslContext);
        }
    } finally {
        ssc.delete();
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) LocalAddress(io.netty.channel.local.LocalAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Aggregations

LocalAddress (io.netty.channel.local.LocalAddress)116 Bootstrap (io.netty.bootstrap.Bootstrap)66 LocalChannel (io.netty.channel.local.LocalChannel)66 LocalServerChannel (io.netty.channel.local.LocalServerChannel)66 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)63 Channel (io.netty.channel.Channel)61 Test (org.junit.Test)47 Test (org.junit.jupiter.api.Test)39 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)32 EventLoopGroup (io.netty.channel.EventLoopGroup)32 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)31 PooledByteBufAllocator (io.netty.buffer.PooledByteBufAllocator)28 ConnectException (java.net.ConnectException)27 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)27 Subscription (rx.Subscription)27 HttpInitiator (org.jocean.http.client.HttpClient.HttpInitiator)26 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)26 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)25 ChannelFuture (io.netty.channel.ChannelFuture)24 SSLException (javax.net.ssl.SSLException)22