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:org.teiid.transport.SocketListener.java

License:Apache License

protected void configureChannelPipeline(ChannelPipeline pipeline, SSLConfiguration config,
        StorageManager storageManager) throws Exception {
    if (config != null) {
        SSLEngine engine = config.getServerSSLEngine();
        if (engine != null) {
            pipeline.addLast("ssl", new SslHandler(engine)); //$NON-NLS-1$
        }/*from   ww w .  j  a v a2s.  com*/
    }
    pipeline.addLast("decoder", new ObjectDecoder(maxMessageSize, //$NON-NLS-1$
            maxLobSize, Thread.currentThread().getContextClassLoader(), storageManager));
    pipeline.addLast("chunker", new ChunkedWriteHandler()); //$NON-NLS-1$
    pipeline.addLast("encoder", new ObjectEncoder()); //$NON-NLS-1$
    pipeline.addLast("handler", this.channelHandler); //$NON-NLS-1$
}

From source file:org.thingsboard.server.transport.mqtt.MqttSslHandlerProvider.java

License:Apache License

public SslHandler getSslHandler() {
    try {//w ww  .j  a v  a 2  s  .  c o m
        URL ksUrl = Resources.getResource(keyStoreFile);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(keyStoreFile);
        File tsFile = new File(tsUrl.toURI());

        TrustManagerFactory tmFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        try (InputStream tsFileInputStream = new FileInputStream(tsFile)) {
            trustStore.load(tsFileInputStream, keyStorePassword.toCharArray());
        }
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        try (InputStream ksFileInputStream = new FileInputStream(ksFile)) {
            ks.load(ksFileInputStream, keyStorePassword.toCharArray());
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = { x509wrapped };
        if (StringUtils.isEmpty(sslProtocol)) {
            sslProtocol = "TLS";
        }
        SSLContext sslContext = SSLContext.getInstance(sslProtocol);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        return new SslHandler(sslEngine);
    } catch (Exception e) {
        log.error("Unable to set up SSL context. Reason: " + e.getMessage(), e);
        throw new RuntimeException("Failed to get SSL handler", e);
    }
}

From source file:org.vertx.java.core.http.impl.DefaultHttpClient.java

License:Open Source License

void internalConnect(final Handler<ClientConnection> connectHandler,
        final Handler<Throwable> connectErrorHandler) {
    if (bootstrap == null) {
        // Share the event loop thread to also serve the HttpClient's network traffic.
        VertxEventLoopGroup pool = new VertxEventLoopGroup();
        pool.addWorker(actualCtx.getEventLoop());
        bootstrap = new Bootstrap();
        bootstrap.group(pool);//  w  w w .  j  a  v a  2s .c  om
        bootstrap.channel(NioSocketChannel.class);
        tcpHelper.checkSSL(vertx);

        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (tcpHelper.isSSL()) {
                    SSLEngine engine = tcpHelper.getSSLContext().createSSLEngine(host, port);
                    if (tcpHelper.isVerifyHost()) {
                        SSLParameters sslParameters = engine.getSSLParameters();
                        sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
                        engine.setSSLParameters(sslParameters);
                    }
                    engine.setUseClientMode(true); //We are on the client side of the connection
                    pipeline.addLast("ssl", new SslHandler(engine));
                }

                pipeline.addLast("codec", new HttpClientCodec(4096, 8192, 8192, false, false));
                if (tryUseCompression) {
                    pipeline.addLast("inflater", new HttpContentDecompressor(true));
                }
                pipeline.addLast("handler", new ClientHandler());
            }
        });
    }
    tcpHelper.applyConnectionOptions(bootstrap);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            final Channel ch = channelFuture.channel();
            if (channelFuture.isSuccess()) {
                if (tcpHelper.isSSL()) {
                    // TCP connected, so now we must do the SSL handshake

                    SslHandler sslHandler = ch.pipeline().get(SslHandler.class);

                    Future<Channel> fut = sslHandler.handshakeFuture();
                    fut.addListener(new GenericFutureListener<Future<Channel>>() {
                        @Override
                        public void operationComplete(Future<Channel> future) throws Exception {
                            if (future.isSuccess()) {
                                connected(ch, connectHandler);
                            } else {
                                connectionFailed(ch, connectErrorHandler,
                                        new SSLHandshakeException("Failed to create SSL connection"));
                            }
                        }
                    });
                } else {
                    connected(ch, connectHandler);
                }
            } else {
                connectionFailed(ch, connectErrorHandler, channelFuture.cause());
            }
        }
    });
}

From source file:org.vertx.java.core.http.impl.DefaultHttpServer.java

License:Open Source License

public HttpServer listen(int port, String host, final Handler<AsyncResult<HttpServer>> listenHandler) {
    if (requestHandler == null && wsHandler == null) {
        throw new IllegalStateException("Set request or websocket handler first");
    }/*from  w  ww.ja v a  2  s .  c  o  m*/
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;

    synchronized (vertx.sharedHttpServers()) {
        id = new ServerID(port, host);

        serverOrigin = (isSSL() ? "https" : "http") + "://" + host + ":" + port;

        DefaultHttpServer shared = vertx.sharedHttpServers().get(id);
        if (shared == null) {
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels",
                    GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            tcpHelper.applyConnectionOptions(bootstrap);
            tcpHelper.checkSSL(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (tcpHelper.isSSL()) {
                        SSLEngine engine = tcpHelper.getSSLContext().createSSLEngine();
                        engine.setUseClientMode(false);
                        switch (tcpHelper.getClientAuth()) {
                        case REQUEST: {
                            engine.setWantClientAuth(true);
                            break;
                        }
                        case REQUIRED: {
                            engine.setNeedClientAuth(true);
                            break;
                        }
                        case NONE: {
                            engine.setNeedClientAuth(false);
                            break;
                        }
                        }
                        pipeline.addLast("ssl", new SslHandler(engine));
                    }
                    pipeline.addLast("flashpolicy", new FlashPolicyHandler());
                    pipeline.addLast("httpDecoder", new HttpRequestDecoder(4096, 8192, 8192, false));
                    pipeline.addLast("httpEncoder", new VertxHttpResponseEncoder());
                    if (compressionSupported) {
                        pipeline.addLast("deflater", new HttpChunkContentCompressor());
                    }
                    if (tcpHelper.isSSL() || compressionSupported) {
                        // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used.
                        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support
                    }
                    pipeline.addLast("handler", new ServerHandler());
                }
            });

            addHandlers(this);
            try {
                bindFuture = bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port));
                Channel serverChannel = bindFuture.channel();
                serverChannelGroup.add(serverChannel);
                bindFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        if (!channelFuture.isSuccess()) {
                            vertx.sharedHttpServers().remove(id);
                        }
                    }
                });
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(new VoidHandler() {
                        @Override
                        protected void handle() {
                            listenHandler.handle(new DefaultFutureResult<HttpServer>(t));
                        }
                    });
                } else {
                    // No handler - log so user can see failure
                    actualCtx.reportException(t);
                }
                listening = false;
                return this;
            }
            vertx.sharedHttpServers().put(id, this);
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            addHandlers(actualServer);
        }
        actualServer.bindFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                if (listenHandler != null) {
                    final AsyncResult<HttpServer> res;
                    if (future.isSuccess()) {
                        res = new DefaultFutureResult<HttpServer>(DefaultHttpServer.this);
                    } else {
                        res = new DefaultFutureResult<>(future.cause());
                        listening = false;
                    }
                    actualCtx.execute(future.channel().eventLoop(), new Runnable() {
                        @Override
                        public void run() {
                            listenHandler.handle(res);
                        }
                    });
                } else if (!future.isSuccess()) {
                    listening = false;
                    // No handler - log so user can see failure
                    actualCtx.reportException(future.cause());
                }
            }
        });
    }
    return this;
}

From source file:org.vertx.java.core.net.impl.TCPSSLHelper.java

License:Open Source License

public SslHandler createSslHandler(VertxInternal vertx, boolean client) {
    if (sslContext == null) {
        sslContext = createContext(vertx, keyStorePath, keyStorePassword, trustStorePath, trustStorePassword,
                trustAll);/*from w  ww. j a  va 2 s . c  om*/
    }
    SSLEngine engine = getSSLContext().createSSLEngine();
    engine.setUseClientMode(client);
    if (!client) {
        switch (getClientAuth()) {
        case REQUEST: {
            engine.setWantClientAuth(true);
            break;
        }
        case REQUIRED: {
            engine.setNeedClientAuth(true);
            break;
        }
        case NONE: {
            engine.setNeedClientAuth(false);
            break;
        }
        }
    }
    return new SslHandler(engine);
}

From source file:org.wildfly.camel.test.lumberjack.LumberjackComponentTest.java

License:Apache License

private List<Integer> sendMessages(int port, SSLContextParameters sslContextParameters)
        throws InterruptedException {
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {/*ww  w .  ja va2  s  .c o m*/
        // This list will hold the acknowledgment response sequence numbers
        List<Integer> responses = new ArrayList<>();

        // This initializer configures the SSL and an acknowledgment recorder
        ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (sslContextParameters != null) {
                    SSLEngine sslEngine = sslContextParameters.createSSLContext(null).createSSLEngine();
                    sslEngine.setUseClientMode(true);
                    pipeline.addLast(new SslHandler(sslEngine));
                }

                // Add the response recorder
                pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                        Assert.assertEquals(msg.readUnsignedByte(), (short) '2');
                        Assert.assertEquals(msg.readUnsignedByte(), (short) 'A');
                        synchronized (responses) {
                            responses.add(msg.readInt());
                        }
                    }
                });
            }
        };

        // Connect to the server
        Channel channel = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class)
                .handler(initializer).connect("127.0.0.1", port).sync().channel();

        // Send the 2 window frames
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("lumberjack/window10"));
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("lumberjack/window15"));
        TimeUnit.MILLISECONDS.sleep(100);

        channel.close();

        synchronized (responses) {
            return responses;
        }
    } finally {
        eventLoopGroup.shutdownGracefully();
    }
}

From source file:org.wisdom.engine.server.WisdomServerInitializer.java

License:Apache License

@Override
public void initChannel(final SocketChannel ch) throws Exception {
    // Create a default pipeline implementation.
    final ChannelPipeline pipeline = ch.pipeline();
    if (secure) {
        final SSLEngine engine = SSLServerContext.getInstance(accessor).serverContext().createSSLEngine();
        engine.setUseClientMode(false);/* w w w.j a va  2s  . c  om*/
        setClientAuthenticationMode(engine);
        pipeline.addLast("ssl", new SslHandler(engine));
    }

    pipeline.addLast("decoder", new HttpRequestDecoder());

    // Uncomment the following line if you don't want to handle HttpChunks.
    //p.addLast("aggregator", new HttpObjectAggregator(65536));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

    // The wisdom handler.
    pipeline.addLast("handler", new WisdomHandler(accessor));

}

From source file:org.wso2.carbon.inbound.endpoint.protocol.websocket.ssl.SSLHandlerFactory.java

License:Open Source License

public SslHandler create() {
    SSLEngine engine = serverContext.createSSLEngine();
    engine.setNeedClientAuth(needClientAuth);
    engine.setUseClientMode(false);//from  w  w w .  j  a va2s. c  o  m
    return new SslHandler(engine);
}

From source file:org.wso2.carbon.mss.internal.router.SSLHandlerFactory.java

License:Open Source License

/**
 * @return instance of {@code SslHandler}
 *//*from w w  w .j av a  2  s . c o  m*/
public SslHandler create() {
    SSLEngine engine = serverContext.createSSLEngine();
    engine.setNeedClientAuth(needClientAuth);
    engine.setUseClientMode(false);
    return new SslHandler(engine);
}

From source file:org.wso2.carbon.transport.http.netty.listener.HTTPServerChannelInitializer.java

License:Open Source License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Initializing source channel pipeline");
    }/*from   w ww  . j a v a  2s. co m*/

    ChannelPipeline pipeline = ch.pipeline();

    if (sslConfig != null) {
        pipeline.addLast(Constants.SSL_HANDLER, new SslHandler(new SSLHandlerFactory(sslConfig).build()));
    }

    pipeline.addLast("encoder", new HttpResponseEncoder());
    configureHTTPPipeline(pipeline);

    if (socketIdleTimeout > 0) {
        pipeline.addBefore(Constants.HTTP_SOURCE_HANDLER, Constants.IDLE_STATE_HANDLER, new IdleStateHandler(
                socketIdleTimeout, socketIdleTimeout, socketIdleTimeout, TimeUnit.MILLISECONDS));
    }
}