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:com.github.wangshuwei5.client.NettyClientInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    SSLEngine engine = null;/*from   w  w  w.ja  v  a  2s.  c om*/
    if (SSLMODE.CA.toString().equals(tlsMode)) {
        engine = NettySslContextFactory.getClientContext(tlsMode, null,
                System.getProperty("user.dir") + "/src/main/resources/cChat.jks").createSSLEngine();
    } else if (SSLMODE.CSA.toString().equals(tlsMode)) {
        engine = NettySslContextFactory
                .getClientContext(tlsMode, System.getProperty("user.dir") + "/src/main/resources/cChat.jks",
                        System.getProperty("user.dir") + "/src/main/resources/cChat.jks")
                .createSSLEngine();

    } else {
        System.err.println("ERROR : " + tlsMode);
        System.exit(-1);
    }
    engine.setUseClientMode(true);
    pipeline.addLast("ssl", new SslHandler(engine));

    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
    ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler());
    ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler());
}

From source file:com.github.wangshuwei5.server.NettyServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    ///*  w w w .j a va  2 s  . c  om*/
    // Read SecureChatSslContextFactory
    // if you need client certificate authentication.

    SSLEngine engine = null;
    if (SSLMODE.CA.toString().equals(tlsMode)) {
        engine = NettySslContextFactory.getServerContext(tlsMode,
                System.getProperty("user.dir") + "/src/main/resources/sChat.jks", null).createSSLEngine();
    } else if (SSLMODE.CSA.toString().equals(tlsMode)) {
        engine = NettySslContextFactory
                .getServerContext(tlsMode, System.getProperty("user.dir") + "/src/main/resources/sChat.jks",
                        System.getProperty("user.dir") + "/src/main/resources/sChat.jks")
                .createSSLEngine();

    } else {
        System.err.println("ERROR : " + tlsMode);
        System.exit(-1);
    }
    engine.setUseClientMode(false);

    // Client auth
    if (SSLMODE.CSA.toString().equals(tlsMode))
        engine.setNeedClientAuth(true);
    pipeline.addLast("ssl", new SslHandler(engine));

    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
    ch.pipeline().addLast(new LoginAuthRespHandler());
    ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());
}

From source file:com.github.zk1931.jzab.NettyTransport.java

License:Apache License

/**
 * Constructs a NettyTransport object./*from w  w  w  . j a  v  a 2  s.  com*/
 *
 * @param hostPort "hostname:port" string. The netty transport binds to the
 *                 port specified in the string.
 * @param receiver receiver callback.
 * @param sslParam Ssl parameters.
 * @param dir the directory used to store the received file.
 */
public NettyTransport(String hostPort, final Receiver receiver, ZabConfig.SslParameters sslParam,
        final File dir) throws InterruptedException, GeneralSecurityException, IOException {
    super(receiver);
    this.keyStore = sslParam.getKeyStore();
    this.trustStore = sslParam.getTrustStore();
    this.keyStorePassword = sslParam.getKeyStorePassword() != null
            ? sslParam.getKeyStorePassword().toCharArray()
            : null;
    this.trustStorePassword = sslParam.getTrustStorePassword() != null
            ? sslParam.getTrustStorePassword().toCharArray()
            : null;
    this.dir = dir;
    if (isSslEnabled()) {
        initSsl();
    }

    this.hostPort = hostPort;
    String[] address = hostPort.split(":", 2);
    int port = Integer.parseInt(address[1]);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    if (isSslEnabled()) {
                        SSLEngine engine = serverContext.createSSLEngine();
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(true);
                        ch.pipeline().addLast(new SslHandler(engine));
                    }
                    // Incoming handlers
                    ch.pipeline().addLast(new MainHandler());
                    ch.pipeline().addLast(new ServerHandshakeHandler());
                    ch.pipeline().addLast(new NotifyHandler());
                    ch.pipeline().addLast(new ServerErrorHandler());
                }
            });

    // Travis build fails once in a while because it fails to bind to a port.
    // This is most likely a transient failure. Retry binding for 5 times with
    // 1 second sleep in between before giving up.
    int bindRetryCount = 5;
    for (int i = 0;; i++) {
        try {
            channel = b.bind(port).sync().channel();
            LOG.info("Server started: {}", hostPort);
            return;
        } catch (Exception ex) {
            if (i >= bindRetryCount) {
                throw ex;
            }
            LOG.debug("Failed to bind to {}. Retrying after 1 second.", hostPort);
            Thread.sleep(1000);
        }
    }
}

From source file:com.github.zk1931.jzab.transport.NettyTransport.java

License:Apache License

/**
 * Constructs a NettyTransport object./*from  ww  w  . j a  v a  2s.  c  o m*/
 *
 * @param hostPort "hostname:port" string. The netty transport binds to the
 *                 port specified in the string.
 * @param receiver receiver callback.
 * @param sslParam Ssl parameters.
 * @param dir the directory used to store the received file.
 */
public NettyTransport(String hostPort, final Receiver receiver, SslParameters sslParam, final File dir)
        throws InterruptedException, GeneralSecurityException, IOException {
    super(receiver);
    this.keyStore = sslParam.getKeyStore();
    this.trustStore = sslParam.getTrustStore();
    this.keyStorePassword = sslParam.getKeyStorePassword() != null
            ? sslParam.getKeyStorePassword().toCharArray()
            : null;
    this.trustStorePassword = sslParam.getTrustStorePassword() != null
            ? sslParam.getTrustStorePassword().toCharArray()
            : null;
    this.dir = dir;
    if (isSslEnabled()) {
        initSsl();
    }

    this.hostPort = hostPort;
    String[] address = hostPort.split(":", 2);
    int port = Integer.parseInt(address[1]);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    if (isSslEnabled()) {
                        SSLEngine engine = serverContext.createSSLEngine();
                        engine.setUseClientMode(false);
                        engine.setNeedClientAuth(true);
                        ch.pipeline().addLast(new SslHandler(engine));
                    }
                    // Incoming handlers
                    ch.pipeline().addLast(new MainHandler());
                    ch.pipeline().addLast(new ServerHandshakeHandler());
                    ch.pipeline().addLast(new NotifyHandler());
                    ch.pipeline().addLast(new ErrorHandler());
                    // Outgoing handlers.
                    ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
                }
            });

    // Travis build fails once in a while because it fails to bind to a port.
    // This is most likely a transient failure. Retry binding for 5 times with
    // 1 second sleep in between before giving up.
    int bindRetryCount = 5;
    for (int i = 0;; i++) {
        try {
            channel = b.bind(port).sync().channel();
            LOG.info("Server started: {}", hostPort);
            return;
        } catch (Exception ex) {
            if (i >= bindRetryCount) {
                throw ex;
            }
            LOG.debug("Failed to bind to {}. Retrying after 1 second.", hostPort);
            Thread.sleep(1000);
        }
    }
}

From source file:com.google.cloud.pubsub.proxy.moquette.NettyAcceptor.java

License:Open Source License

private SslHandler initSslHandler(Properties props) {
    final String jksPath = props.getProperty(Constants.JKS_PATH_PROPERTY_NAME);
    LOG.info("Starting SSL using keystore at {}", jksPath);
    if (jksPath == null || jksPath.isEmpty()) {
        //key_store_password or key_manager_password are empty
        LOG.warn("You have configured the SSL port but not the jks_path, SSL not started");
        return null;
    }/*  ww w. j  a v  a 2 s.  c o m*/

    //if we have the port also the jks then keyStorePassword and keyManagerPassword
    //has to be defined
    final String keyStorePassword = props.getProperty(Constants.KEY_STORE_PASSWORD_PROPERTY_NAME);
    final String keyManagerPassword = props.getProperty(Constants.KEY_MANAGER_PASSWORD_PROPERTY_NAME);
    if (keyStorePassword == null || keyStorePassword.isEmpty()) {
        //key_store_password or key_manager_password are empty
        LOG.warn("You have configured the SSL port but not the key_store_password, SSL not started");
        return null;
    }
    if (keyManagerPassword == null || keyManagerPassword.isEmpty()) {
        //key_manager_password or key_manager_password are empty
        LOG.warn("You have configured the SSL port but not the" + " key_manager_password, SSL not started");
        return null;
    }

    try {
        InputStream jksInputStream = jksDatastore(jksPath);
        SSLContext serverContext = SSLContext.getInstance("TLS");
        final KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(jksInputStream, keyStorePassword.toCharArray());
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyManagerPassword.toCharArray());
        serverContext.init(kmf.getKeyManagers(), null, null);

        SSLEngine engine = serverContext.createSSLEngine();
        engine.setUseClientMode(false);
        return new SslHandler(engine);
    } catch (NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException | KeyStoreException
            | KeyManagementException | IOException ex) {
        LOG.error("Can't start SSL layer!", ex);
        return null;
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java

License:Open Source License

public HttpBlobStore(URI uri, int timeoutMillis, @Nullable final Credentials creds) throws Exception {
    boolean useTls = uri.getScheme().equals("https");
    if (uri.getPort() == -1) {
        int port = useTls ? 443 : 80;
        uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(),
                uri.getFragment());// w  w  w  .  j  a va  2  s.  c  om
    }
    this.uri = uri;
    final SslContext sslCtx;
    if (useTls) {
        // OpenSsl gives us a > 2x speed improvement on fast networks, but requires netty tcnative
        // to be there which is not available on all platforms and environments.
        SslProvider sslProvider = OpenSsl.isAvailable() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(sslProvider).build();
    } else {
        sslCtx = null;
    }
    Bootstrap clientBootstrap = new Bootstrap().channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeoutMillis).group(eventLoop)
            .remoteAddress(uri.getHost(), uri.getPort());
    downloadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() {
        @Override
        public void channelReleased(Channel ch) {
            ch.pipeline().remove("read-timeout-handler");
        }

        @Override
        public void channelAcquired(Channel ch) {
            ch.pipeline().addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis));
        }

        @Override
        public void channelCreated(Channel ch) {
            ChannelPipeline p = ch.pipeline();
            p.addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis));
            if (sslCtx != null) {
                SSLEngine engine = sslCtx.newEngine(ch.alloc());
                engine.setUseClientMode(true);
                p.addFirst(new SslHandler(engine));
            }
            p.addLast(new HttpClientCodec());
            p.addLast(new HttpDownloadHandler(creds));
        }
    });
    uploadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() {
        @Override
        public void channelReleased(Channel ch) {
        }

        @Override
        public void channelAcquired(Channel ch) {
        }

        @Override
        public void channelCreated(Channel ch) {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SSLEngine engine = sslCtx.newEngine(ch.alloc());
                engine.setUseClientMode(true);
                p.addFirst(new SslHandler(engine));
            }
            p.addLast(new HttpResponseDecoder());
            // The 10KiB limit was chosen at random. We only expect HTTP servers to respond with
            // an error message in the body and that should always be less than 10KiB.
            p.addLast(new HttpObjectAggregator(10 * 1024));
            p.addLast(new HttpRequestEncoder());
            p.addLast(new ChunkedWriteHandler());
            p.addLast(new HttpUploadHandler(creds));
        }
    });
    this.creds = creds;
}

From source file:com.googlecode.protobuf.pro.duplex.client.DuplexTcpClientPipelineFactory.java

License:Apache License

@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();//ww  w . j a  va 2  s  .  co  m

    RpcSSLContext ssl = getSslContext();
    if (ssl != null) {
        p.addLast(Handler.SSL, new SslHandler(ssl.createClientEngine()));
    }

    p.addLast(Handler.FRAME_DECODER, new ProtobufVarint32FrameDecoder());
    p.addLast(Handler.PROTOBUF_DECODER, new ProtobufDecoder(DuplexProtocol.WirePayload.getDefaultInstance(),
            getWirelinePayloadExtensionRegistry()));

    p.addLast(Handler.FRAME_ENCODER, new ProtobufVarint32LengthFieldPrepender());
    p.addLast(Handler.PROTOBUF_ENCODER, new ProtobufEncoder());

    // the connectResponseHandler is swapped after the client connection
    // handshake with the RpcClient for the Channel
    p.addLast(Handler.CLIENT_CONNECT, new ClientConnectResponseHandler());
}

From source file:com.googlecode.protobuf.pro.duplex.server.DuplexTcpServerPipelineFactory.java

License:Apache License

@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();//from www. j a v  a2  s.co  m

    if (getSslContext() != null) {
        p.addLast(Handler.SSL, new SslHandler(getSslContext().createServerEngine()));
    }

    p.addLast(Handler.FRAME_DECODER, new ProtobufVarint32FrameDecoder());
    p.addLast(Handler.PROTOBUF_DECODER, new ProtobufDecoder(DuplexProtocol.WirePayload.getDefaultInstance(),
            getWirelinePayloadExtensionRegistry()));

    p.addLast(Handler.FRAME_ENCODER, new ProtobufVarint32LengthFieldPrepender());
    p.addLast(Handler.PROTOBUF_ENCODER, new ProtobufEncoder());

    p.addLast(Handler.SERVER_CONNECT, connectRequestHandler); // one instance shared by all channels

    if (log.isDebugEnabled()) {
        log.debug("initChannel " + ch);
    }
}

From source file:com.guowl.websocket.client.WebSocketClientRunner.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from w  w  w. ja  va  2  s.co m*/
        // 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.
        final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));

        final String protocol = uri.getScheme();
        int defaultPort;
        ChannelInitializer<SocketChannel> initializer;

        // Normal WebSocket
        if ("ws".equals(protocol)) {
            initializer = new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("http-codec", new HttpClientCodec())
                            .addLast("aggregator", new HttpObjectAggregator(8192))
                            .addLast("ws-handler", handler);
                }
            };

            defaultPort = 80;
            // Secure WebSocket
        } else if ("wss".equals(protocol)) {
            initializer = new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    SSLEngine engine = WebSocketSslClientContextFactory.getContext().createSSLEngine();
                    engine.setUseClientMode(true);

                    ch.pipeline().addFirst("ssl", new SslHandler(engine))
                            .addLast("http-codec", new HttpClientCodec())
                            .addLast("aggregator", new HttpObjectAggregator(8192))
                            .addLast("ws-handler", handler);
                }
            };

            defaultPort = 443;
        } else {
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);
        }

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(initializer);

        int port = uri.getPort();
        // If no port was specified, we'll try the default port: https://tools.ietf.org/html/rfc6455#section-1.7
        if (uri.getPort() == -1) {
            port = defaultPort;
        }

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            if (msg == null) {
                break;
            } else if ("bye".equals(msg.toLowerCase())) {
                ch.writeAndFlush(new CloseWebSocketFrame());
                ch.closeFuture().sync();
                break;
            } else if ("ping".equals(msg.toLowerCase())) {
                WebSocketFrame frame = new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
            } else {
                WebSocketFrame frame = new TextWebSocketFrame(msg);
                ch.writeAndFlush(frame);
            }
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.gw.services.client.HttpsClientInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();//from   w  w  w.j  a  v a2s. c o m

    // Enable HTTPS if necessary.
    if (sslCtx != null) {
        SSLEngine sslEngine = sslCtx.createSSLEngine();
        sslEngine.setUseClientMode(true);
        SslHandler sslHandler = new SslHandler(sslEngine);
        p.addLast(sslHandler);
    }

    p.addLast(new HttpClientCodec());

    // Remove the following line if you don't want automatic content decompression.
    p.addLast(new HttpContentDecompressor());

    // Uncomment the following line if you don't want to handle HttpContents.
    //p.addLast(new HttpObjectAggregator(1048576));

    p.addLast(new HttpsClientHandler());
}