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:fileShare.ShareServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//  ww  w .j  a v a  2  s  .c  o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // Create a default pipeline implementation.
                        ChannelPipeline pipeline = ch.pipeline();

                        if (HttpUploadServer.isSSL) {
                            SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
                            engine.setUseClientMode(false);
                            pipeline.addLast("ssl", new SslHandler(engine));
                        }

                        pipeline.addLast("decoder", new HttpRequestDecoder());
                        pipeline.addLast("encoder", new HttpResponseEncoder());
                        pipeline.addLast("HttpObjectAggregator", new HttpObjectAggregator(10000000));
                        //pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

                        // Remove the following line if you don't want automatic content
                        // compression.
                        //pipeline.addLast("deflater", new HttpContentCompressor());

                        pipeline.addLast("handler", new MyHandler());
                        //                            pipeline.addLast("handler", new ShareHandler());
                    }
                });

        Channel ch = b.bind(port).sync().channel();
        System.out.println("HTTP Upload Server at port " + port + '.');
        System.out.println("Open your browser and navigate to http://localhost:" + port + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:io.advantageous.conekt.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.  ja v a2s.c o  m*/
    engine.setUseClientMode(client);
    Set<String> enabledProtocols = new HashSet<>(Arrays.asList(ENABLED_PROTOCOLS));
    enabledProtocols.retainAll(Arrays.asList(engine.getEnabledProtocols()));
    engine.setEnabledProtocols(enabledProtocols.toArray(new String[0]));
    if (!client) {
        switch (getClientAuth()) {
        case REQUEST: {
            engine.setWantClientAuth(true);
            break;
        }
        case REQUIRED: {
            engine.setNeedClientAuth(true);
            break;
        }
        case NONE: {
            engine.setNeedClientAuth(false);
            break;
        }
        }
    } else if (verifyHost) {
        SSLParameters sslParameters = engine.getSSLParameters();
        sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
        engine.setSSLParameters(sslParameters);
    }
    return new SslHandler(engine);
}

From source file:io.apigee.trireme.container.netty.NettyHttpServer.java

License:Open Source License

private ChannelInitializer<SocketChannel> makePipeline(final TLSParams tls) {
    return new ChannelInitializer<SocketChannel>() {
        @Override/*from   ww  w.  j  av  a2 s.  c  o m*/
        public void initChannel(SocketChannel c) throws Exception {

            c.pipeline().addLast(new IdleStateHandler(IDLE_CONNECTION_SECONDS, IDLE_CONNECTION_SECONDS,
                    IDLE_CONNECTION_SECONDS));
            if (tls != null) {
                isTls = true;
                SSLEngine engine = makeSSLEngine(tls);
                c.pipeline().addLast(new SslHandler(engine));
            }
            if (log.isTraceEnabled()) {
                c.pipeline().addLast("loggingReq", new LoggingHandler(LogLevel.DEBUG));
            }
            c.pipeline().addLast(new HttpRequestDecoder()).addLast(new HttpHandler())
                    .addLast(new HttpResponseEncoder());
            if (log.isTraceEnabled()) {
                c.pipeline().addLast("loggingResp", new LoggingHandler(LogLevel.DEBUG));
            }
        }
    };
}

From source file:io.atomix.catalyst.transport.netty.NettyClient.java

License:Apache License

@Override
public CompletableFuture<Connection> connect(Address address) {
    Assert.notNull(address, "address");
    ThreadContext context = ThreadContext.currentContextOrThrow();
    CompletableFuture<Connection> future = new ComposableFuture<>();

    LOGGER.info("Connecting to {}", address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(transport.eventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   w  w  w . java 2s.  c  o  m*/
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (transport.properties().sslEnabled()) {
                        pipeline.addFirst(
                                new SslHandler(new NettyTls(transport.properties()).initSslEngine(true)));
                    }
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0,
                            4, 0, 4));
                    pipeline.addLast(
                            new NettyHandler(connections, future::complete, context, transport.properties()));
                }
            });

    bootstrap.option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, transport.properties().connectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, ALLOCATOR);

    if (transport.properties().sendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize());
    }
    if (transport.properties().receiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize());
    }

    bootstrap.connect(address.socketAddress()).addListener(channelFuture -> {
        if (channelFuture.isSuccess()) {
            LOGGER.info("Connected to {}", address);
        } else {
            context.execute(() -> future.completeExceptionally(channelFuture.cause()));
        }
    });
    return future;
}

From source file:io.atomix.catalyst.transport.netty.NettyServer.java

License:Apache License

/**
 * Starts listening for the given member.
 *//*from w  w w  .  jav  a2  s  .co m*/
private void listen(Address address, Consumer<Connection> listener, ThreadContext context) {
    channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE);

    handler = new ServerHandler(connections, listener, context, transport.properties());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(transport.eventLoopGroup()).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (transport.properties().sslEnabled()) {
                        pipeline.addFirst(
                                new SslHandler(new NettyTls(transport.properties()).initSslEngine(false)));
                    }
                    pipeline.addLast(FIELD_PREPENDER);
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0,
                            4, 0, 4));
                    pipeline.addLast(handler);
                }
            }).option(ChannelOption.SO_BACKLOG, transport.properties().acceptBacklog())
            .option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay())
            .option(ChannelOption.SO_REUSEADDR, transport.properties().reuseAddress())
            .childOption(ChannelOption.ALLOCATOR, ALLOCATOR)
            .childOption(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive());

    if (transport.properties().sendBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize());
    }
    if (transport.properties().receiveBufferSize() != -1) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize());
    }

    LOGGER.info("Binding to {}", address);

    ChannelFuture bindFuture = bootstrap.bind(address.socketAddress());
    bindFuture.addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            listening = true;
            context.executor().execute(() -> {
                LOGGER.info("Listening at {}", bindFuture.channel().localAddress());
                listenFuture.complete(null);
            });
        } else {
            context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause()));
        }
    });
    channelGroup.add(bindFuture.channel());
}

From source file:io.dyn.net.tcp.TcpServer.java

License:Apache License

@SuppressWarnings({ "unchecked" })
@Override//from www .j  a  v  a 2 s.  c o m
public T start() {
    Tasks.execute(new Runnable() {
        @Override
        public void run() {
            if (!started.get()) {
                on(Lifecycle.STOP, new CompletionHandler() {
                    @Override
                    protected void complete() {
                        channel.close();
                        started.set(false);
                    }
                });
                bootstrap.setOption("backlog", backlog);
                bootstrap.setOption("child.keepAlive", keepAlive);
                bootstrap.setOption("child.reuseAddress", reuseAddress);
                bootstrap.setOption("child.receiveBufferSize", Buffer.SMALL_BUFFER_SIZE);
                bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
                    @Override
                    public ChannelPipeline getPipeline() throws Exception {
                        final ChannelPipeline pipeline = Channels.pipeline();
                        if (ssl) {
                            SSLEngine engine;
                            try {
                                engine = SSL.sslContext(sslConfig).createSSLEngine();
                                engine.setUseClientMode(false);
                                pipeline.addLast("ssl", new SslHandler(engine));
                            } catch (Exception e) {
                                event(Events.classToEventExpression(e.getClass()), e);
                            }
                        }
                        pipeline.addLast("channelHandler", new SimpleChannelUpstreamHandler() {
                            @Override
                            public void channelConnected(final ChannelHandlerContext ctx, ChannelStateEvent e)
                                    throws Exception {
                                log.debug("channel connected: " + ctx.getChannel());
                                Tasks.currentExecutor(new TaskExecutor() {
                                    @Override
                                    public void execute(Runnable task) {
                                        ctx.getPipeline().execute(task);
                                    }
                                });

                                Dyn<Channel> dyn = Dyn.wrap(ctx.getChannel());
                                ctx.getChannel().setAttachment(dyn);
                                event(NioEvents.CONNECTED, dyn);
                            }

                            @Override
                            public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e)
                                    throws Exception {
                                log.debug("channel disconnected: " + ctx.getChannel());
                                Tasks.currentExecutor(null);
                                event(NioEvents.DISCONNECTED, ctx.getChannel().getAttachment());
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
                                    throws Exception {
                                event(Events.classToEventExpression(e.getCause().getClass()), e.getCause());
                            }
                        });
                        if (null != protocolHandler) {
                            pipeline.addLast("protocol", new SimpleChannelUpstreamHandler() {
                                Protocol protocol = TcpServer.this.protocolHandler().newInstance();

                                @Override
                                public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
                                        throws Exception {
                                    if (e.getMessage() instanceof ChannelBuffer) {
                                        ChannelBuffer cb = (ChannelBuffer) e.getMessage();
                                        int available = cb.readableBytes();
                                        byte[] bs = new byte[available];
                                        cb.readBytes(bs);
                                        protocol.decode(Buffer.wrap(bs),
                                                (Evented) ctx.getChannel().getAttachment());
                                    }
                                }
                            });
                        }
                        configurePipeline(pipeline);
                        return pipeline;
                    }
                });

                try {
                    channel = bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port));
                    started.set(true);
                    //LOG.info("Listening on port %s...", port);
                    event(Lifecycle.START);
                } catch (UnknownHostException e) {
                    event(Events.classToEventExpression(e.getClass()), e);
                }
            }
        }
    }, executor);
    return (T) this;
}

From source file:io.gatling.http.client.impl.SslHandlers.java

License:Apache License

private static SslHandler createSslHandler(SslContext sslContext, String peerHost, int peerPort,
        ByteBufAllocator allocator, HttpClientConfig config) {

    SSLEngine sslEngine = config.isEnableSni() ? sslContext.newEngine(allocator, Tls.domain(peerHost), peerPort)
            : sslContext.newEngine(allocator);

    sslEngine.setUseClientMode(true);// w ww.  ja  va 2s.  c o  m
    if (config.isEnableHostnameVerification()) {
        SSLParameters params = sslEngine.getSSLParameters();
        params.setEndpointIdentificationAlgorithm("HTTPS");
        sslEngine.setSSLParameters(params);
    }

    SslHandler sslHandler = new SslHandler(sslEngine);
    if (config.getHandshakeTimeout() > 0)
        sslHandler.setHandshakeTimeoutMillis(config.getHandshakeTimeout());
    return sslHandler;
}

From source file:io.higgs.http.client.ClientIntializer.java

License:Apache License

/**
 * Adds an SSL engine to the given pipeline.
 *
 * @param pipeline     the pipeline to add SSL support to
 * @param forceToFront if true then the SSL handler is added to the front of the pipeline otherwise it is added
 *                     at the end/*from   ww  w.j  a v  a 2  s. com*/
 */
public static void addSSL(ChannelPipeline pipeline, boolean forceToFront, String[] sslProtocols) {
    SSLEngine engine = SSLContextFactory.getSSLSocket(SSLConfigFactory.sslConfiguration).createSSLEngine();
    engine.setUseClientMode(true);
    if (sslProtocols != null && sslProtocols.length > 0) {
        engine.setEnabledProtocols(sslProtocols);
    }
    if (forceToFront) {
        pipeline.addFirst("ssl", new SslHandler(engine));
    } else {
        pipeline.addLast("ssl", new SslHandler(engine));
    }
}

From source file:io.jsync.net.impl.TCPSSLHelper.java

License:Open Source License

private SslHandler createHandler(SSLEngine engine, boolean client) {
    engine.setEnabledProtocols(ENABLED_PROTOCOLS);
    engine.setUseClientMode(client);//from ww w  .  jav a 2  s . co  m
    if (!client) {
        switch (getClientAuth()) {
        case REQUEST: {
            engine.setWantClientAuth(true);
            break;
        }
        case REQUIRED: {
            engine.setNeedClientAuth(true);
            break;
        }
        case NONE: {
            engine.setNeedClientAuth(false);
            break;
        }
        }
    } else if (verifyHost) {
        SSLParameters sslParameters = engine.getSSLParameters();
        sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
        engine.setSSLParameters(sslParameters);
    }
    return new SslHandler(engine);
}

From source file:io.maelstorm.server.PipelineFactory.java

License:Open Source License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    final ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("idleStateHandler",
            new IdleStateHandler(idleTimeoutSeconds, idleTimeoutSeconds, idleTimeoutSeconds));
    pipeline.addLast("connmgr", connmgr);
    if (null != serverContext) {
        SSLEngine engine = serverContext.createSSLEngine();
        engine.setUseClientMode(false);//from  w  w w.j  av a  2s  .  co m
        pipeline.addLast("sslHandler", new SslHandler(engine));
    }
    pipeline.addLast("decoder",
            new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize, chunkedSupported));
    pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("handler", handler);
}