Example usage for io.netty.handler.ssl SslHandler SslHandler

List of usage examples for io.netty.handler.ssl SslHandler SslHandler

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslHandler SslHandler.

Prototype

public SslHandler(SSLEngine engine) 

Source Link

Document

Creates a new instance which runs all delegated tasks directly on the EventExecutor .

Usage

From source file:io.moquette.server.netty.NettyAcceptor.java

License:Open Source License

private ChannelHandler createSslHandler(SSLContext sslContext, boolean needsClientAuth) {
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(false);/*from ww  w  .j av  a  2  s .  co m*/
    if (needsClientAuth) {
        sslEngine.setNeedClientAuth(true);
    }
    return new SslHandler(sslEngine);
}

From source file:io.reactivex.netty.pipeline.ssl.SslPipelineConfigurator.java

License:Apache License

@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
    pipeline.addFirst(new SslHandler(sslEngineFactory.createSSLEngine(pipeline.channel().alloc())));
}

From source file:io.scalecube.socketio.pipeline.SocketIOChannelInitializer.java

License:Apache License

@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    // Flash policy file
    if (isFlashSupported) {
        pipeline.addLast(FLASH_POLICY_HANDLER, flashPolicyHandler);
    }/*from  w ww  . ja  v a  2 s  .  c o  m*/
    // SSL
    if (sslContext != null) {
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        SslHandler sslHandler = new SslHandler(sslEngine);
        //sslHandler.setIssueHandshake(true);
        pipeline.addLast(SSL_HANDLER, sslHandler);
    }

    // HTTP
    pipeline.addLast(HTTP_REQUEST_DECODER, new HttpRequestDecoder());
    pipeline.addLast(HTTP_CHUNK_AGGREGATOR, new HttpObjectAggregator(MAX_HTTP_CONTENT_LENGTH));
    pipeline.addLast(HTTP_REPONSE_ENCODER, new HttpResponseEncoder());

    // Flash resources
    if (isFlashSupported) {
        pipeline.addLast(FLASH_RESOURCE_HANDLER, flashResourceHandler);
    }

    // Socket.IO
    pipeline.addLast(SOCKETIO_PACKET_ENCODER, packetEncoderHandler);
    pipeline.addLast(SOCKETIO_HANDSHAKE_HANDLER, handshakeHanler);
    pipeline.addLast(SOCKETIO_DISCONNECT_HANDLER, disconnectHanler);
    pipeline.addLast(SOCKETIO_WEBSOCKET_HANDLER, webSocketHandler);
    pipeline.addLast(SOCKETIO_FLASHSOCKET_HANDLER, flashSocketHandler);
    pipeline.addLast(SOCKETIO_XHR_POLLING_HANDLER, xhrPollingHanler);
    pipeline.addLast(SOCKETIO_JSONP_POLLING_HANDLER, jsonpPollingHanler);
    pipeline.addLast(SOCKETIO_HEARTBEAT_HANDLER, heartbeatHandler);
    pipeline.addLast(eventExecutorGroup, SOCKETIO_PACKET_DISPATCHER, packetDispatcherHandler);
}

From source file:io.soliton.protobuf.ChannelInitializers.java

License:Apache License

/**
 * Returns a server-side channel initializer capable of securely receiving
 * and sending HTTP requests and responses
 * <p/>/*from  w ww.j a  va  2s. com*/
 * <p>Communications will be encrypted as per the configured SSL context</p>
 *
 * @param handler the handler implementing the business logic.
 * @param sslContext the SSL context which drives the security of the
 * link to the client.
 */
public static final ChannelInitializer<Channel> secureHttpServer(
        final SimpleChannelInboundHandler<HttpRequest> handler, final SSLContext sslContext) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            SSLEngine sslEngine = sslContext.createSSLEngine();
            sslEngine.setUseClientMode(false);
            pipeline.addLast("ssl", new SslHandler(sslEngine));
            pipeline.addLast("httpCodec", new HttpServerCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(10 * 1024 * 1024));
            pipeline.addLast("httpServerHandler", handler);
        }
    };
}

From source file:io.soliton.protobuf.ChannelInitializers.java

License:Apache License

/**
 * Returns a client-side channel initializer capable of securely sending
 * and receiving HTTP requests and responses.
 * <p/>//from  www .j  a  va2s .c  o  m
 * <p>Communications will be encrypted as per the configured SSL context</p>
 *
 * @param handler the handler in charge of implementing the business logic
 * @param sslContext the SSL context which drives the security of the
 * link to the server.
 */
public static final ChannelInitializer<Channel> secureHttpClient(
        final SimpleChannelInboundHandler<HttpResponse> handler, final SSLContext sslContext) {
    return new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            SSLEngine sslEngine = sslContext.createSSLEngine();
            sslEngine.setUseClientMode(true);
            pipeline.addLast("ssl", new SslHandler(sslEngine));
            pipeline.addLast("httpCodec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(10 * 1024 * 1024));
            pipeline.addLast("httpClientHandler", handler);
        }
    };
}

From source file:io.vertx.core.http.Http2ClientTest.java

License:Open Source License

private ServerBootstrap createH2Server(
        BiFunction<Http2ConnectionDecoder, Http2ConnectionEncoder, Http2FrameListener> handler) {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.channel(NioServerSocketChannel.class);
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    eventLoopGroups.add(eventLoopGroup);
    bootstrap.group(eventLoopGroup);/*  w  w  w  .j a v a  2 s .c  o m*/
    bootstrap.childHandler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            SSLHelper sslHelper = new SSLHelper(serverOptions, Cert.SERVER_JKS.get(), null);
            SslHandler sslHandler = new SslHandler(
                    sslHelper.setApplicationProtocols(Arrays.asList(HttpVersion.HTTP_2, HttpVersion.HTTP_1_1))
                            .createEngine((VertxInternal) vertx, DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT));
            ch.pipeline().addLast(sslHandler);
            ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler("whatever") {
                @Override
                protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
                    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                        ChannelPipeline p = ctx.pipeline();
                        Http2ConnectionHandler clientHandler = createHttpConnectionHandler(handler);
                        p.addLast("handler", clientHandler);
                        return;
                    }
                    ctx.close();
                    throw new IllegalStateException("unknown protocol: " + protocol);
                }
            });
        }
    });
    return bootstrap;
}

From source file:io.vertx.core.http.impl.HttpChannelConnector.java

License:Open Source License

private void doConnect(ConnectionListener<HttpClientConnection> listener, ContextInternal context,
        Future<ConnectResult<HttpClientConnection>> future) {

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(context.nettyEventLoop());
    bootstrap.channelFactory(client.getVertx().transport().channelFactory(false));

    applyConnectionOptions(bootstrap);/*from   w ww. ja v  a 2 s  .  c o  m*/

    ChannelProvider channelProvider;
    // http proxy requests are handled in HttpClientImpl, everything else can use netty proxy handler
    if (options.getProxyOptions() == null || !ssl && options.getProxyOptions().getType() == ProxyType.HTTP) {
        channelProvider = ChannelProvider.INSTANCE;
    } else {
        channelProvider = ProxyChannelProvider.INSTANCE;
    }

    boolean useAlpn = options.isUseAlpn();
    Handler<Channel> channelInitializer = ch -> {

        // Configure pipeline
        ChannelPipeline pipeline = ch.pipeline();
        if (ssl) {
            SslHandler sslHandler = new SslHandler(sslHelper.createEngine(client.getVertx(), peerHost, port,
                    options.isForceSni() ? peerHost : null));
            ch.pipeline().addLast("ssl", sslHandler);
            // TCP connected, so now we must do the SSL handshake
            sslHandler.handshakeFuture().addListener(fut -> {
                if (fut.isSuccess()) {
                    String protocol = sslHandler.applicationProtocol();
                    if (useAlpn) {
                        if ("h2".equals(protocol)) {
                            applyHttp2ConnectionOptions(ch.pipeline());
                            http2Connected(listener, context, ch, future);
                        } else {
                            applyHttp1xConnectionOptions(ch.pipeline());
                            HttpVersion fallbackProtocol = "http/1.0".equals(protocol) ? HttpVersion.HTTP_1_0
                                    : HttpVersion.HTTP_1_1;
                            http1xConnected(listener, fallbackProtocol, host, port, true, context, ch,
                                    http1Weight, future);
                        }
                    } else {
                        applyHttp1xConnectionOptions(ch.pipeline());
                        http1xConnected(listener, version, host, port, true, context, ch, http1Weight, future);
                    }
                } else {
                    handshakeFailure(ch, fut.cause(), listener, future);
                }
            });
        } else {
            if (version == HttpVersion.HTTP_2) {
                if (options.isHttp2ClearTextUpgrade()) {
                    applyHttp1xConnectionOptions(pipeline);
                } else {
                    applyHttp2ConnectionOptions(pipeline);
                }
            } else {
                applyHttp1xConnectionOptions(pipeline);
            }
        }
    };

    Handler<AsyncResult<Channel>> channelHandler = res -> {

        if (res.succeeded()) {
            Channel ch = res.result();
            if (!ssl) {
                if (version == HttpVersion.HTTP_2) {
                    if (options.isHttp2ClearTextUpgrade()) {
                        http1xConnected(listener, version, host, port, false, context, ch, http2Weight, future);
                    } else {
                        http2Connected(listener, context, ch, future);
                    }
                } else {
                    http1xConnected(listener, version, host, port, false, context, ch, http1Weight, future);
                }
            }
        } else {
            connectFailed(null, listener, res.cause(), future);
        }
    };

    channelProvider.connect(client.getVertx(), bootstrap, options.getProxyOptions(),
            SocketAddress.inetSocketAddress(port, host), channelInitializer, channelHandler);
}

From source file:io.vertx.core.net.impl.NetClientBase.java

License:Open Source License

protected void doConnect(int port, String host, String serverName, Handler<AsyncResult<C>> connectHandler,
        int remainingAttempts) {
    checkClosed();//w  ww.  j  a v a  2 s.  c om
    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 -> {
        ChannelPipeline pipeline = ch.pipeline();
        if (sslHelper.isSSL()) {
            SslHandler sslHandler = new SslHandler(sslHelper.createEngine(vertx, host, port, serverName));
            ch.pipeline().addLast("ssl", sslHandler);
        }
        initChannel(pipeline);
        pipeline.addLast("handler", new VertxNetHandler<C>(ch, socketMap) {
            @Override
            protected Object safeObject(Object msg, ByteBufAllocator allocator) throws Exception {
                return NetClientBase.this.safeObject(msg, allocator);
            }

            @Override
            protected void handleMsgReceived(C conn, Object msg) {
                NetClientBase.this.handleMsgReceived(conn, msg);
            }
        });
    };

    Handler<AsyncResult<Channel>> channelHandler = res -> {
        if (res.succeeded()) {

            Channel ch = res.result();

            if (sslHelper.isSSL()) {
                // TCP connected, so now we must do the SSL handshake
                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");
                    //Set a timer to retry connection
                    vertx.setTimer(options.getReconnectInterval(),
                            tid -> doConnect(port, host, serverName, connectHandler,
                                    remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1));
                });
            } else {
                failed(context, null, res.cause(), connectHandler);
            }
        }
    };

    channelProvider.connect(vertx, bootstrap, options.getProxyOptions(), host, port, channelInitializer,
            channelHandler);
}

From source file:io.vertx.core.net.impl.SSLHelper.java

License:Open Source License

private SslHandler createHandler(SSLEngine engine, boolean client) {
    if (enabledCipherSuites != null && !enabledCipherSuites.isEmpty()) {
        String[] toUse = enabledCipherSuites.toArray(new String[enabledCipherSuites.size()]);
        engine.setEnabledCipherSuites(toUse);
    }//from   w w  w.  j a  va 2  s . com
    engine.setUseClientMode(client);
    Set<String> protocols = new LinkedHashSet<>(Arrays.asList(DEFAULT_ENABLED_PROTOCOLS));
    protocols.retainAll(Arrays.asList(engine.getEnabledProtocols()));
    if (enabledProtocols != null && !enabledProtocols.isEmpty() && !protocols.isEmpty()) {
        protocols.retainAll(enabledProtocols);
        if (protocols.isEmpty()) {
            log.warn("no SSL/TLS protocols are enabled due to configuration restrictions");
        }
    }
    engine.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
    if (!client) {
        switch (getClientAuth()) {
        case REQUEST: {
            engine.setWantClientAuth(true);
            break;
        }
        case REQUIRED: {
            engine.setNeedClientAuth(true);
            break;
        }
        case NONE: {
            engine.setNeedClientAuth(false);
            break;
        }
        }
    } else if (!endpointIdentificationAlgorithm.isEmpty()) {
        SSLParameters sslParameters = engine.getSSLParameters();
        sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm);
        engine.setSSLParameters(sslParameters);
    }
    return new SslHandler(engine);
}

From source file:io.vertx.core.net.impl.VertxSniHandler.java

License:Open Source License

@Override
protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext)
        throws Exception {
    SslHandler sslHandler = null;//from   ww w.  j a  v a  2s. c  om
    try {
        SSLEngine engine = helper.createEngine(sslContext);
        sslHandler = new SslHandler(engine);
        ctx.pipeline().replace(this, "ssl", sslHandler);
        Future<Channel> fut = sslHandler.handshakeFuture();
        fut.addListener(future -> {
            if (future.isSuccess()) {
                Attribute<String> val = ctx.channel().attr(SERVER_NAME_ATTR);
                val.set(hostname);
                handshakeFuture.setSuccess(ctx.channel());
            } else {
                handshakeFuture.setFailure(future.cause());
            }
        });
        sslHandler = null;
    } finally {
        // Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not
        // transferred to the SslHandler.
        // See https://github.com/netty/netty/issues/5678
        if (sslHandler != null) {
            ReferenceCountUtil.safeRelease(sslHandler.engine());
        }
    }
}