Search in sources :

Example 11 with SslContext

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContext in project ballerina by ballerina-lang.

the class WebSocketClient method handhshake.

/**
 * @return true if the handshake is done properly.
 * @throws URISyntaxException throws if there is an error in the URI syntax.
 * @throws InterruptedException throws if the connecting the server is interrupted.
 */
public boolean handhshake() throws InterruptedException, URISyntaxException, SSLException {
    boolean isDone = false;
    URI uri = new URI(url);
    String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }
    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        logger.error("Only WS(S) is supported.");
        return false;
    }
    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }
    group = new NioEventLoopGroup();
    DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders();
    headers.entrySet().forEach(header -> {
        httpHeaders.add(header.getKey(), header.getValue());
    });
    try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, httpHeaders));
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.INSTANCE, handler);
            }
        });
        channel = b.connect(uri.getHost(), port).sync().channel();
        isDone = handler.handshakeFuture().sync().isSuccess();
    } catch (Exception e) {
        logger.error("Handshake unsuccessful : " + e.getMessage(), e);
        return false;
    }
    logger.info("WebSocket Handshake successful : " + isDone);
    return isDone;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) ChannelPipeline(io.netty.channel.ChannelPipeline) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 12 with SslContext

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContext in project ballerina by ballerina-lang.

the class WebSocketClient method handshake.

/**
 * @param callback callback which should be called when a response is received.
 * @return true if the handshake is done properly.
 * @throws URISyntaxException   throws if there is an error in the URI syntax.
 * @throws InterruptedException throws if the connecting the server is interrupted.
 */
public boolean handshake(Callback callback) throws InterruptedException, URISyntaxException, SSLException {
    boolean isDone;
    URI uri = new URI(url);
    String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }
    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        LOGGER.debug("Only WS(S) is supported.");
        return false;
    }
    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }
    DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders();
    headers.forEach(httpHeaders::add);
    try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, httpHeaders), callback);
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.INSTANCE, handler);
            }
        });
        channel = b.connect(uri.getHost(), port).sync().channel();
        isDone = handler.handshakeFuture().sync().isSuccess();
    } catch (Exception e) {
        LOGGER.debug("Handshake unsuccessful : " + e.getMessage(), e);
        group.shutdownGracefully();
        return false;
    }
    LOGGER.debug("WebSocket Handshake successful: {}", isDone);
    return isDone;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) ChannelPipeline(io.netty.channel.ChannelPipeline) URISyntaxException(java.net.URISyntaxException) SSLException(javax.net.ssl.SSLException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) Bootstrap(io.netty.bootstrap.Bootstrap) SslContext(io.netty.handler.ssl.SslContext)

Example 13 with SslContext

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContext in project jocean-http by isdom.

the class InsertHandlerTestCase method testInsertHandlers2.

@Test
public void testInsertHandlers2() throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    final Channel channel = new LocalChannel();
    // Inbound.ENABLE_SSL.applyTo(channel, sslCtx);
    // Inbound.CLOSE_ON_IDLE.applyTo(channel, 180);
    // Inbound.CONTENT_COMPRESSOR.applyTo(channel);
    // Inbound.LOGGING.applyTo(channel);
    final List<String> names = channel.pipeline().names();
// assertEquals(Inbound.LOGGING.name(), names.get(0));
// assertEquals(Inbound.CLOSE_ON_IDLE.name(), names.get(1));
// assertEquals(Inbound.ENABLE_SSL.name(), names.get(2));
// assertEquals(Inbound.CONTENT_COMPRESSOR.name(), names.get(3));
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) SslContext(io.netty.handler.ssl.SslContext) Test(org.junit.Test)

Example 14 with SslContext

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContext in project jocean-http by isdom.

the class SslDemo method main.

public static void main(String[] args) throws Exception {
    final SslContext sslCtx = SslContextBuilder.forClient().build();
    final Feature sslfeature = new Feature.ENABLE_SSL(sslCtx);
    try (final HttpClient client = new DefaultHttpClient()) {
        {
            final String host = "www.sina.com.cn";
            final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
            // HttpUtil.setKeepAlive(request, true);
            request.headers().set(HttpHeaderNames.HOST, host);
            LOG.debug("send request:{}", request);
            final String content = sendRequestAndRecv(client, host, 443, request, sslfeature, Feature.ENABLE_LOGGING, Feature.ENABLE_COMPRESSOR);
        // LOG.info("recv:{}", content);
        }
    /*
            {
                final String host = "www.alipay.com";

                final DefaultFullHttpRequest request = new DefaultFullHttpRequest(
                        HttpVersion.HTTP_1_0, HttpMethod.GET, "/");
                HttpUtil.setKeepAlive(request, true);
                request.headers().set(HttpHeaderNames.HOST, host);

                LOG.debug("send request:{}", request);
              
                LOG.info("recv:{}", sendRequestAndRecv(client, request, host, sslfeature));
            }
            */
    /*
            {
                final String host = "github.com";

                final DefaultFullHttpRequest request = new DefaultFullHttpRequest(
                        HttpVersion.HTTP_1_0, HttpMethod.GET, "/isdom");
                HttpUtil.setKeepAlive(request, true);
                request.headers().set(HttpHeaderNames.HOST, host);

                LOG.debug("send request:{}", request);
              
                LOG.info("recv:{}", sendRequestAndRecv(client, request, host, sslfeature));
            }
            */
    }
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpClient(org.jocean.http.client.HttpClient) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) SslContext(io.netty.handler.ssl.SslContext)

Example 15 with SslContext

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslContext in project ratpack by ratpack.

the class DefaultRatpackServer method buildChannel.

protected Channel buildChannel(final ServerConfig serverConfig, final ChannelHandler handlerAdapter) throws InterruptedException {
    SslContext sslContext = serverConfig.getNettySslContext();
    this.useSsl = sslContext != null;
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverConfig.getConnectTimeoutMillis().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
        serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, i);
    });
    serverConfig.getMaxMessagesPerRead().ifPresent(i -> {
        FixedRecvByteBufAllocator allocator = new FixedRecvByteBufAllocator(i);
        serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, allocator);
        serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, allocator);
    });
    serverConfig.getReceiveBufferSize().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.SO_RCVBUF, i);
        serverBootstrap.childOption(ChannelOption.SO_RCVBUF, i);
    });
    serverConfig.getWriteSpinCount().ifPresent(i -> {
        serverBootstrap.option(ChannelOption.WRITE_SPIN_COUNT, i);
        serverBootstrap.childOption(ChannelOption.WRITE_SPIN_COUNT, i);
    });
    serverConfig.getConnectQueueSize().ifPresent(i -> serverBootstrap.option(ChannelOption.SO_BACKLOG, i));
    return serverBootstrap.group(execController.getEventLoopGroup()).channel(ChannelImplDetector.getServerSocketChannelImpl()).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            new ConnectionIdleTimeout(pipeline, serverConfig.getIdleTimeout());
            if (sslContext != null) {
                SSLEngine sslEngine = sslContext.newEngine(PooledByteBufAllocator.DEFAULT);
                pipeline.addLast("ssl", new SslHandler(sslEngine));
            }
            pipeline.addLast("decoder", new HttpRequestDecoder(serverConfig.getMaxInitialLineLength(), serverConfig.getMaxHeaderSize(), serverConfig.getMaxChunkSize(), false));
            pipeline.addLast("encoder", new HttpResponseEncoder());
            pipeline.addLast("deflater", new IgnorableHttpContentCompressor());
            pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
            pipeline.addLast("adapter", handlerAdapter);
            ch.config().setAutoRead(false);
        }
    }).bind(buildSocketAddress(serverConfig)).sync().channel();
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SslHandler(io.netty.handler.ssl.SslHandler) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) ConnectionIdleTimeout(ratpack.http.internal.ConnectionIdleTimeout) SslContext(io.netty.handler.ssl.SslContext)

Aggregations

SslContext (io.netty.handler.ssl.SslContext)220 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)67 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)59 EventLoopGroup (io.netty.channel.EventLoopGroup)52 Channel (io.netty.channel.Channel)48 Test (org.junit.Test)48 SSLException (javax.net.ssl.SSLException)46 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)41 SslContextBuilder (io.netty.handler.ssl.SslContextBuilder)37 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)36 Bootstrap (io.netty.bootstrap.Bootstrap)35 LoggingHandler (io.netty.handler.logging.LoggingHandler)35 SocketChannel (io.netty.channel.socket.SocketChannel)34 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)33 InetSocketAddress (java.net.InetSocketAddress)31 SslHandler (io.netty.handler.ssl.SslHandler)30 CertificateException (java.security.cert.CertificateException)29 IOException (java.io.IOException)26 ChannelPipeline (io.netty.channel.ChannelPipeline)23 File (java.io.File)23