Search in sources :

Example 11 with SslHandler

use of io.netty.handler.ssl.SslHandler in project vert.x by eclipse.

the class ConnectionBase method getPeerCertificateChain.

public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
    if (isSSL()) {
        ChannelHandlerContext sslHandlerContext = channel.pipeline().context("ssl");
        assert sslHandlerContext != null;
        SslHandler sslHandler = (SslHandler) sslHandlerContext.handler();
        return sslHandler.engine().getSession().getPeerCertificateChain();
    } else {
        return null;
    }
}
Also used : SslHandler(io.netty.handler.ssl.SslHandler)

Example 12 with SslHandler

use of io.netty.handler.ssl.SslHandler in project vert.x by eclipse.

the class NetClientImpl method connect.

private void connect(int port, String host, Handler<AsyncResult<NetSocket>> connectHandler, int remainingAttempts) {
    Objects.requireNonNull(host, "No null host accepted");
    Objects.requireNonNull(connectHandler, "No null connectHandler accepted");
    ContextImpl context = vertx.getOrCreateContext();
    sslHelper.validate(vertx);
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(context.nettyEventLoop());
    bootstrap.channel(NioSocketChannel.class);
    applyConnectionOptions(bootstrap);
    ChannelProvider channelProvider;
    if (options.getProxyOptions() == null) {
        channelProvider = ChannelProvider.INSTANCE;
    } else {
        channelProvider = ProxyChannelProvider.INSTANCE;
    }
    Handler<Channel> channelInitializer = ch -> {
        if (sslHelper.isSSL()) {
            SslHandler sslHandler = sslHelper.createSslHandler(vertx, host, port);
            ch.pipeline().addLast("ssl", sslHandler);
        }
        ChannelPipeline pipeline = ch.pipeline();
        if (logEnabled) {
            pipeline.addLast("logging", new LoggingHandler());
        }
        if (sslHelper.isSSL()) {
            pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
        }
        if (options.getIdleTimeout() > 0) {
            pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
        }
        pipeline.addLast("handler", new VertxNetHandler<NetSocketImpl>(ch, socketMap) {

            @Override
            protected void handleMsgReceived(Object msg) {
                ByteBuf buf = (ByteBuf) msg;
                conn.handleDataReceived(Buffer.buffer(buf));
            }
        });
    };
    Handler<AsyncResult<Channel>> channelHandler = res -> {
        if (res.succeeded()) {
            Channel ch = res.result();
            if (sslHelper.isSSL()) {
                SslHandler sslHandler = (SslHandler) ch.pipeline().get("ssl");
                io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture();
                fut.addListener(future2 -> {
                    if (future2.isSuccess()) {
                        connected(context, ch, connectHandler, host, port);
                    } else {
                        failed(context, ch, future2.cause(), connectHandler);
                    }
                });
            } else {
                connected(context, ch, connectHandler, host, port);
            }
        } else {
            if (remainingAttempts > 0 || remainingAttempts == -1) {
                context.executeFromIO(() -> {
                    log.debug("Failed to create connection. Will retry in " + options.getReconnectInterval() + " milliseconds");
                    vertx.setTimer(options.getReconnectInterval(), tid -> connect(port, host, connectHandler, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1));
                });
            } else {
                failed(context, null, res.cause(), connectHandler);
            }
        }
    };
    channelProvider.connect(vertx, bootstrap, options.getProxyOptions(), host, port, channelInitializer, channelHandler);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) ContextImpl(io.vertx.core.impl.ContextImpl) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) LoggerFactory(io.vertx.core.logging.LoggerFactory) ByteBuf(io.netty.buffer.ByteBuf) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) Logger(io.vertx.core.logging.Logger) NetClient(io.vertx.core.net.NetClient) Metrics(io.vertx.core.spi.metrics.Metrics) Closeable(io.vertx.core.Closeable) VertxInternal(io.vertx.core.impl.VertxInternal) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) Future(io.vertx.core.Future) NetClientOptions(io.vertx.core.net.NetClientOptions) Objects(java.util.Objects) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) LoggingHandler(io.netty.handler.logging.LoggingHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ContextImpl(io.vertx.core.impl.ContextImpl) ByteBuf(io.netty.buffer.ByteBuf) SslHandler(io.netty.handler.ssl.SslHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Bootstrap(io.netty.bootstrap.Bootstrap) Future(io.vertx.core.Future) AsyncResult(io.vertx.core.AsyncResult)

Example 13 with SslHandler

use of io.netty.handler.ssl.SslHandler in project flink by apache.

the class NettyServer method init.

void init(final NettyProtocol protocol, NettyBufferPool nettyBufferPool) throws IOException {
    checkState(bootstrap == null, "Netty server has already been initialized.");
    long start = System.currentTimeMillis();
    bootstrap = new ServerBootstrap();
    switch(config.getTransportType()) {
        case NIO:
            initNioBootstrap();
            break;
        case EPOLL:
            initEpollBootstrap();
            break;
        case AUTO:
            if (Epoll.isAvailable()) {
                initEpollBootstrap();
                LOG.info("Transport type 'auto': using EPOLL.");
            } else {
                initNioBootstrap();
                LOG.info("Transport type 'auto': using NIO.");
            }
    }
    // --------------------------------------------------------------------
    // Configuration
    // --------------------------------------------------------------------
    // Server bind address
    bootstrap.localAddress(config.getServerAddress(), config.getServerPort());
    // Pooled allocators for Netty's ByteBuf instances
    bootstrap.option(ChannelOption.ALLOCATOR, nettyBufferPool);
    bootstrap.childOption(ChannelOption.ALLOCATOR, nettyBufferPool);
    if (config.getServerConnectBacklog() > 0) {
        bootstrap.option(ChannelOption.SO_BACKLOG, config.getServerConnectBacklog());
    }
    // Receive and send buffer size
    int receiveAndSendBufferSize = config.getSendAndReceiveBufferSize();
    if (receiveAndSendBufferSize > 0) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, receiveAndSendBufferSize);
        bootstrap.childOption(ChannelOption.SO_RCVBUF, receiveAndSendBufferSize);
    }
    // Low and high water marks for flow control
    bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, config.getMemorySegmentSize() + 1);
    bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 2 * config.getMemorySegmentSize());
    // SSL related configuration
    try {
        serverSSLContext = config.createServerSSLContext();
    } catch (Exception e) {
        throw new IOException("Failed to initialize SSL Context for the Netty Server", e);
    }
    // --------------------------------------------------------------------
    // Child channel pipeline for accepted connections
    // --------------------------------------------------------------------
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel channel) throws Exception {
            if (serverSSLContext != null) {
                SSLEngine sslEngine = serverSSLContext.createSSLEngine();
                config.setSSLVerAndCipherSuites(sslEngine);
                sslEngine.setUseClientMode(false);
                channel.pipeline().addLast("ssl", new SslHandler(sslEngine));
            }
            channel.pipeline().addLast(protocol.getServerChannelHandlers());
        }
    });
    // --------------------------------------------------------------------
    // Start Server
    // --------------------------------------------------------------------
    bindFuture = bootstrap.bind().syncUninterruptibly();
    localAddress = (InetSocketAddress) bindFuture.channel().localAddress();
    long end = System.currentTimeMillis();
    LOG.info("Successful initialization (took {} ms). Listening on SocketAddress {}.", (end - start), bindFuture.channel().localAddress().toString());
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) IOException(java.io.IOException) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IOException(java.io.IOException) SslHandler(io.netty.handler.ssl.SslHandler)

Example 14 with SslHandler

use of io.netty.handler.ssl.SslHandler in project camel by apache.

the class LumberjackChannelInitializer method initChannel.

@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    // Add SSL support if configured
    if (sslContext != null) {
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        pipeline.addLast(new SslHandler(sslEngine));
    }
    LumberjackSessionHandler sessionHandler = new LumberjackSessionHandler();
    // Add the primary lumberjack frame decoder
    pipeline.addLast(new LumberjackFrameDecoder(sessionHandler));
    // Add the secondary lumberjack frame decoder, used when the first one is processing compressed frames
    pipeline.addLast(new LumberjackFrameDecoder(sessionHandler));
    // Add the bridge to Camel
    pipeline.addLast(messageExecutorService, new LumberjackMessageHandler(sessionHandler, messageProcessor));
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler)

Example 15 with SslHandler

use of io.netty.handler.ssl.SslHandler in project netty-socketio by mrniko.

the class SocketIOChannelInitializer method addSslHandler.

/**
     * Adds the ssl handler
     *
     * @return
     */
protected void addSslHandler(ChannelPipeline pipeline) {
    if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);
        pipeline.addLast(SSL_HANDLER, new SslHandler(engine));
    }
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) SslHandler(io.netty.handler.ssl.SslHandler)

Aggregations

SslHandler (io.netty.handler.ssl.SslHandler)46 SSLEngine (javax.net.ssl.SSLEngine)21 ChannelPipeline (io.netty.channel.ChannelPipeline)18 ChannelHandler (io.netty.channel.ChannelHandler)11 SocketChannel (io.netty.channel.socket.SocketChannel)9 Channel (io.netty.channel.Channel)7 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)6 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)6 ChunkedWriteHandler (io.netty.handler.stream.ChunkedWriteHandler)6 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)6 Bootstrap (io.netty.bootstrap.Bootstrap)5 ByteBuf (io.netty.buffer.ByteBuf)5 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)5 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)5 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)5 LoggingHandler (io.netty.handler.logging.LoggingHandler)5 File (java.io.File)5 ServerTlsHandler (io.grpc.netty.ProtocolNegotiators.ServerTlsHandler)4 ChannelFuture (io.netty.channel.ChannelFuture)4 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)4