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:HttpUploadServerInitializer.java

License:Apache License

@Override
public 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);/*  w ww  .  j av a2s  .  com*/
        pipeline.addLast("ssl", new SslHandler(engine));
    }

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

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

    pipeline.addLast("handler", new HttpUploadServerHandler());
}

From source file:books.netty.ssl.SecureChatClientInitializer.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.

    SSLEngine engine = null;/*from   w  ww .ja va2  s . co  m*/
    if (SSLMODE.CA.toString().equals(tlsMode)) {
        engine = SecureChatSslContextFactory
                .getClientContext(tlsMode, null,
                        System.getProperty("user.dir") + "/src/com/phei/netty/ssl/conf/client/cChat.jks")
                .createSSLEngine();
    } else if (SSLMODE.CSA.toString().equals(tlsMode)) {
        engine = SecureChatSslContextFactory
                .getClientContext(tlsMode,
                        System.getProperty("user.dir") + "/src/com/phei/netty/ssl/conf/twoway/cChat.jks",
                        System.getProperty("user.dir") + "/src/com/phei/netty/ssl/conf/twoway/cChat.jks")
                .createSSLEngine();

        // engine = SecureChatSslContextFactory
        // .getClientContext(
        // tlsMode,
        // System.getProperty("user.dir")
        // + "/src/com/phei/netty/ssl/conf/client/cChat.jks",
        // System.getProperty("user.dir")
        // + "/src/com/phei/netty/ssl/conf/client/cChat.jks")
        // .createSSLEngine();

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

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    // and then business logic.
    pipeline.addLast("handler", new SecureChatClientHandler());
}

From source file:books.netty.ssl.SecureChatServerInitializer.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.
    ///*from w  ww .j  a  v a 2  s.c om*/
    // Read SecureChatSslContextFactory
    // if you need client certificate authentication.

    SSLEngine engine = null;
    if (SSLMODE.CA.toString().equals(tlsMode)) {
        engine = SecureChatSslContextFactory
                .getServerContext(tlsMode,
                        System.getProperty("user.dir") + "/src/com/phei/netty/ssl/conf/client/sChat.jks", null)
                .createSSLEngine();
    } else if (SSLMODE.CSA.toString().equals(tlsMode)) {
        engine = SecureChatSslContextFactory
                .getServerContext(tlsMode,
                        System.getProperty("user.dir") + "/src/com/phei/netty/ssl/conf/twoway/sChat.jks",
                        System.getProperty("user.dir") + "/src/com/phei/netty/ssl/conf/twoway/sChat.jks")
                .createSSLEngine();

        // engine = SecureChatSslContextFactory
        // .getServerContext(
        // tlsMode,
        // System.getProperty("user.dir")
        // + "/src/com/phei/netty/ssl/conf/client/sChat.jks",
        // System.getProperty("user.dir")
        // + "/src/com/phei/netty/ssl/conf/client/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));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    // and then business logic.
    pipeline.addLast("handler", new SecureChatServerHandler());
}

From source file:cc.io.lessons.server.HttpUploadServerInitializer.java

License:Apache License

@Override
public 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);/*  w  ww.  j  a v  a2  s .co  m*/
        pipeline.addLast("ssl", new SslHandler(engine));
    }

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

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

    //pipeline.addLast("CustomTextFrameHandler",new CustomTextFrameHandler());
}

From source file:com.athena.dolly.websocket.server.test.WebSocketSslServerInitializer.java

License:Apache License

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

    SSLEngine engine = WebSocketSslServerSslContext.getInstance().serverContext().createSSLEngine();
    engine.setUseClientMode(false);/*from  ww  w .ja  v a 2s .  c om*/
    pipeline.addLast("ssl", new SslHandler(engine));

    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("handler", new WebSocketSslServerHandler());
}

From source file:com.barchart.netty.client.transport.WebSocketTransport.java

License:BSD License

@Override
public void initPipeline(final ChannelPipeline pipeline) throws Exception {

    final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, null, false, null);

    final WebSocketClientProtocolHandler wsHandler = new WebSocketClientProtocolHandler(handshaker);

    pipeline.addFirst(new HttpClientCodec(), //
            new HttpObjectAggregator(65536), //
            wsHandler,/*from  w w  w. j a  v a  2s .co  m*/
            // Fires channelActive() after handshake and removes self
            new WebSocketConnectedNotifier(),
            // BinaryWebSocketFrame <-> ByteBuf codec before user codecs
            new WebSocketBinaryCodec());

    if (uri.getScheme().equalsIgnoreCase("wss") && pipeline.get(SslHandler.class) == null) {

        final SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine();
        sslEngine.setUseClientMode(true);
        pipeline.addFirst("ssl", new SslHandler(sslEngine));

    }

}

From source file:com.basho.riak.client.core.netty.RiakSecurityDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext chc, ByteBuf in, List<Object> out) throws Exception {
    // Make sure we have 4 bytes
    if (in.readableBytes() >= 4) {
        in.markReaderIndex();//from   ww w . j a  va  2  s.c  o  m
        int length = in.readInt();

        // See if we have the full frame.
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
        } else {
            byte code = in.readByte();
            byte[] protobuf = new byte[length - 1];
            in.readBytes(protobuf);

            switch (state) {
            case TLS_WAIT:
                switch (code) {
                case RiakMessageCodes.MSG_StartTls:
                    logger.debug("Received MSG_RpbStartTls reply");
                    // change state
                    this.state = State.SSL_WAIT;
                    // insert SSLHandler
                    SslHandler sslHandler = new SslHandler(sslEngine);
                    // get promise
                    Future<Channel> hsFuture = sslHandler.handshakeFuture();
                    // register callback
                    hsFuture.addListener(new SslListener());
                    // Add handler
                    chc.channel().pipeline().addFirst(Constants.SSL_HANDLER, sslHandler);
                    break;
                case RiakMessageCodes.MSG_ErrorResp:
                    logger.debug("Received MSG_ErrorResp reply to startTls");
                    promise.tryFailure((riakErrorToException(protobuf)));
                    break;
                default:
                    promise.tryFailure(
                            new RiakResponseException(0, "Invalid return code during StartTLS; " + code));
                }
                break;
            case AUTH_WAIT:
                chc.channel().pipeline().remove(this);
                switch (code) {
                case RiakMessageCodes.MSG_AuthResp:
                    logger.debug("Received MSG_RpbAuthResp reply");
                    promise.trySuccess(null);
                    break;
                case RiakMessageCodes.MSG_ErrorResp:
                    logger.debug("Received MSG_ErrorResp reply to auth");
                    promise.tryFailure(riakErrorToException(protobuf));
                    break;
                default:
                    promise.tryFailure(
                            new RiakResponseException(0, "Invalid return code during Auth; " + code));
                }
                break;
            default:
                // WTF?
                logger.error("Received message while not in TLS_WAIT or AUTH_WAIT");
                promise.tryFailure(
                        new IllegalStateException("Received message while not in TLS_WAIT or AUTH_WAIT"));
            }
        }
    }
}

From source file:com.chiorichan.https.HttpsInitializer.java

License:Mozilla Public License

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

    try {
        SSLContext context = SslContextFactory.getServerContext();

        if (context == null) {
            NetworkManager.shutdownHttpsServer();
            Loader.getLogger()
                    .severe("The SSL engine failed to initalize, possibly due to a missing certificate file");
            return;
        }

        SSLEngine engine = context.createSSLEngine();
        engine.setUseClientMode(false);

        p.addLast("ssl", new SslHandler(engine));
    } catch (Exception e) {
        NetworkManager.shutdownHttpsServer();
        throw new IllegalStateException("The SSL engine failed to initalize", e);
    }

    p.addLast("decoder", new HttpRequestDecoder());
    p.addLast("aggregator", new HttpObjectAggregator(104857600));
    p.addLast("encoder", new HttpResponseEncoder());
    p.addLast("deflater", new HttpContentCompressor());
    p.addLast("handler", new HttpHandler(true));
}

From source file:com.cloudhopper.smpp.channel.SmppServerConnector.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // the channel we are going to handle
    Channel channel = ctx.channel();

    // always add it to our channel group
    channels.add(channel);/*from  w  ww .j ava2  s  .c  o m*/
    this.server.getCounters().incrementChannelConnectsAndGet();

    // create a default "unbound" thread name for the thread processing the channel
    // this will create a name of "RemoteIPAddress.RemotePort"
    String channelName = ChannelUtil.createChannelName(channel);
    String threadName = server.getConfiguration().getName() + ".UnboundSession." + channelName;

    // rename the current thread for logging, then rename it back
    String currentThreadName = Thread.currentThread().getName();
    Thread.currentThread().setName(server.getConfiguration().getName());
    logger.info("New channel from [{}]", channelName);
    Thread.currentThread().setName(currentThreadName);

    // add SSL handler
    if (server.getConfiguration().isUseSsl()) {
        SslConfiguration sslConfig = server.getConfiguration().getSslConfiguration();
        if (sslConfig == null)
            throw new IllegalStateException("sslConfiguration must be set");
        SslContextFactory factory = new SslContextFactory(sslConfig);
        SSLEngine sslEngine = factory.newSslEngine();
        sslEngine.setUseClientMode(false);
        channel.pipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_SSL_NAME, new SslHandler(sslEngine));
    }

    // add a new instance of a thread renamer
    channel.pipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_THREAD_RENAMER_NAME,
            new SmppSessionThreadRenamer(threadName));

    // add a new instance of a decoder (that takes care of handling frames)
    channel.pipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_PDU_DECODER_NAME,
            new SmppSessionPduDecoder(server.getTranscoder()));

    // create a new wrapper around an "unbound" session to pass the pdu up the chain
    UnboundSmppSession session = new UnboundSmppSession(channelName, channel, server);
    channel.pipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_WRAPPER_NAME,
            new SmppSessionWrapper(session));

    super.channelActive(ctx);
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppClient.java

License:Apache License

protected DefaultSmppSession createSession(Channel channel, SmppSessionConfiguration config,
        SmppSessionHandler sessionHandler)
        throws SmppTimeoutException, SmppChannelException, InterruptedException {
    DefaultSmppSession session = new DefaultSmppSession(SmppSession.Type.CLIENT, config, channel,
            sessionHandler, monitorExecutor);

    // add SSL handler
    if (config.isUseSsl()) {
        SslConfiguration sslConfig = config.getSslConfiguration();
        if (sslConfig == null)
            throw new IllegalStateException("sslConfiguration must be set");
        try {/*from ww w .  j av  a 2 s  .  c om*/
            SslContextFactory factory = new SslContextFactory(sslConfig);
            SSLEngine sslEngine = factory.newSslEngine();
            sslEngine.setUseClientMode(true);
            channel.pipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_SSL_NAME,
                    new SslHandler(sslEngine));
        } catch (Exception e) {
            throw new SmppChannelConnectException("Unable to create SSL session]: " + e.getMessage(), e);
        }
    }

    // add the thread renamer portion to the pipeline
    if (config.getName() != null) {
        channel.pipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_THREAD_RENAMER_NAME,
                new SmppSessionThreadRenamer(config.getName()));
    } else {
        logger.warn("Session configuration did not have a name set - skipping threadRenamer in pipeline");
    }

    // create the logging handler (for bytes sent/received on wire)
    SmppSessionLogger loggingHandler = new SmppSessionLogger(DefaultSmppSession.class.getCanonicalName(),
            config.getLoggingOptions());
    channel.pipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_LOGGER_NAME, loggingHandler);

    // add a new instance of a decoder (that takes care of handling frames)
    channel.pipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_PDU_DECODER_NAME,
            new SmppSessionPduDecoder(session.getTranscoder()));

    // create a new wrapper around a session to pass the pdu up the chain
    channel.pipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_WRAPPER_NAME,
            new SmppSessionWrapper(session));

    return session;
}