Search in sources :

Example 1 with SslHandler

use of org.apache.flink.shaded.netty4.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 2 with SslHandler

use of org.apache.flink.shaded.netty4.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 3 with SslHandler

use of org.apache.flink.shaded.netty4.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 4 with SslHandler

use of org.apache.flink.shaded.netty4.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 5 with SslHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler in project pulsar by yahoo.

the class ServerCnx method handleConnect.

@Override
protected void handleConnect(CommandConnect connect) {
    checkArgument(state == State.Start);
    if (service.isAuthenticationEnabled()) {
        try {
            String authMethod = "none";
            if (connect.hasAuthMethodName()) {
                authMethod = connect.getAuthMethodName();
            } else if (connect.hasAuthMethod()) {
                // Legacy client is passing enum
                authMethod = connect.getAuthMethod().name().substring(10).toLowerCase();
            }
            String authData = connect.getAuthData().toStringUtf8();
            ChannelHandler sslHandler = ctx.channel().pipeline().get(PulsarChannelInitializer.TLS_HANDLER);
            SSLSession sslSession = null;
            if (sslHandler != null) {
                sslSession = ((SslHandler) sslHandler).engine().getSession();
            }
            authRole = getBrokerService().getAuthenticationService().authenticate(new AuthenticationDataCommand(authData, remoteAddress, sslSession), authMethod);
            log.info("[{}] Client successfully authenticated with {} role {}", remoteAddress, authMethod, authRole);
        } catch (AuthenticationException e) {
            String msg = "Unable to authenticate";
            log.warn("[{}] {}: {}", remoteAddress, msg, e.getMessage());
            ctx.writeAndFlush(Commands.newError(-1, ServerError.AuthenticationError, msg));
            close();
            return;
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Received CONNECT from {}", remoteAddress);
    }
    ctx.writeAndFlush(Commands.newConnected(connect));
    state = State.Connected;
    remoteEndpointProtocolVersion = connect.getProtocolVersion();
}
Also used : AuthenticationDataCommand(com.yahoo.pulsar.broker.authentication.AuthenticationDataCommand) AuthenticationException(javax.naming.AuthenticationException) SSLSession(javax.net.ssl.SSLSession) ChannelHandler(io.netty.channel.ChannelHandler) SslHandler(io.netty.handler.ssl.SslHandler)

Aggregations

SslHandler (io.netty.handler.ssl.SslHandler)141 SSLEngine (javax.net.ssl.SSLEngine)51 ChannelPipeline (io.netty.channel.ChannelPipeline)37 Channel (io.netty.channel.Channel)29 ChannelHandler (io.netty.channel.ChannelHandler)23 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)23 SslContext (io.netty.handler.ssl.SslContext)21 IOException (java.io.IOException)16 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)15 Test (org.junit.Test)15 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)14 ChannelInitializer (io.netty.channel.ChannelInitializer)13 SocketChannel (io.netty.channel.socket.SocketChannel)13 SSLSession (javax.net.ssl.SSLSession)12 ByteBuf (io.netty.buffer.ByteBuf)11 ChunkedWriteHandler (io.netty.handler.stream.ChunkedWriteHandler)11 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)11 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)10 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)10 File (java.io.File)10