Search in sources :

Example 6 with SslHandler

use of org.jboss.netty.handler.ssl.SslHandler in project smscgateway by RestComm.

the class TestSmppClient method createSession.

protected DefaultSmppSession createSession(Channel channel, SmppSessionConfiguration config, SmppSessionHandler sessionHandler) throws SmppTimeoutException, SmppChannelException, InterruptedException {
    TestSmppSession session = new TestSmppSession(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 {
            SslContextFactory factory = new SslContextFactory(sslConfig);
            SSLEngine sslEngine = factory.newSslEngine();
            sslEngine.setUseClientMode(true);
            channel.getPipeline().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.getPipeline().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.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_LOGGER_NAME, loggingHandler);
    // add a writeTimeout handler after the logger
    if (config.getWriteTimeout() > 0) {
        WriteTimeoutHandler writeTimeoutHandler = new WriteTimeoutHandler(new org.jboss.netty.util.HashedWheelTimer(), /* writeTimeoutTimer */
        config.getWriteTimeout(), TimeUnit.MILLISECONDS);
        channel.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_WRITE_TIMEOUT_NAME, writeTimeoutHandler);
    }
    // add a new instance of a decoder (that takes care of handling frames)
    channel.getPipeline().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.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_WRAPPER_NAME, new SmppSessionWrapper(session));
    return session;
}
Also used : SmppSessionThreadRenamer(com.cloudhopper.smpp.channel.SmppSessionThreadRenamer) SSLEngine(javax.net.ssl.SSLEngine) SmppSessionPduDecoder(com.cloudhopper.smpp.channel.SmppSessionPduDecoder) SmppSessionWrapper(com.cloudhopper.smpp.channel.SmppSessionWrapper) WriteTimeoutHandler(org.jboss.netty.handler.timeout.WriteTimeoutHandler) DefaultSmppSession(com.cloudhopper.smpp.impl.DefaultSmppSession) SslHandler(org.jboss.netty.handler.ssl.SslHandler) SmppChannelException(com.cloudhopper.smpp.type.SmppChannelException) SmppTimeoutException(com.cloudhopper.smpp.type.SmppTimeoutException) SmppChannelConnectException(com.cloudhopper.smpp.type.SmppChannelConnectException) UnrecoverablePduException(com.cloudhopper.smpp.type.UnrecoverablePduException) RecoverablePduException(com.cloudhopper.smpp.type.RecoverablePduException) SslContextFactory(com.cloudhopper.smpp.ssl.SslContextFactory) SmppSessionLogger(com.cloudhopper.smpp.channel.SmppSessionLogger) SslConfiguration(com.cloudhopper.smpp.ssl.SslConfiguration) SmppChannelConnectException(com.cloudhopper.smpp.type.SmppChannelConnectException)

Example 7 with SslHandler

use of org.jboss.netty.handler.ssl.SslHandler in project http-client by biasedbit.

the class DefaultHttpClient method init.

// HttpClient -----------------------------------------------------------------------------------------------------
@Override
public boolean init() {
    if (timeoutController == null) {
        // prefer lower resources consumption over precision
        timeoutController = new HashedWheelTimeoutController();
        timeoutController.init();
        internalTimeoutManager = true;
    }
    if (connectionFactory == null)
        connectionFactory = new DefaultConnectionFactory();
    if ((sslContextFactory == null) && isHttps())
        sslContextFactory = BogusSslContextFactory.getInstance();
    eventConsumerLatch = new CountDownLatch(1);
    eventQueue = new LinkedBlockingQueue<>();
    // TODO instead of fixed size thread pool, use a cached thread pool with size limit (limited growth cached pool)
    executor = Executors.newFixedThreadPool(maxHelperThreads, new NamedThreadFactory("httpHelpers"));
    Executor workerPool = Executors.newFixedThreadPool(maxIoWorkerThreads, new NamedThreadFactory("httpWorkers"));
    if (useNio) {
        // It's only going to create 1 thread, so no harm done here.
        Executor bossPool = Executors.newCachedThreadPool();
        channelFactory = new NioClientSocketChannelFactory(bossPool, workerPool);
    } else {
        channelFactory = new OioClientSocketChannelFactory(workerPool);
    }
    channelGroup = new CleanupChannelGroup(toString());
    // Create a pipeline without the last handler (it will be added right before connecting).
    pipelineFactory = new ChannelPipelineFactory() {

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = Channels.pipeline();
            if (useSsl) {
                SSLEngine engine = sslContextFactory.getClientContext().createSSLEngine();
                engine.setUseClientMode(true);
                pipeline.addLast("ssl", new SslHandler(engine));
            }
            pipeline.addLast("codec", new HttpClientCodec());
            if (autoDecompress)
                pipeline.addLast("decompressor", new HttpContentDecompressor());
            return pipeline;
        }
    };
    executor.execute(new Runnable() {

        @Override
        public void run() {
            eventHandlingLoop();
        }
    });
    return true;
}
Also used : NioClientSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory) SSLEngine(javax.net.ssl.SSLEngine) HashedWheelTimeoutController(com.biasedbit.http.client.timeout.HashedWheelTimeoutController) SslHandler(org.jboss.netty.handler.ssl.SslHandler) OioClientSocketChannelFactory(org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory)

Example 8 with SslHandler

use of org.jboss.netty.handler.ssl.SslHandler in project druid by druid-io.

the class ChannelResourceFactory method generate.

@Override
public ChannelFuture generate(final String hostname) {
    log.debug("Generating: %s", hostname);
    URL url;
    try {
        url = new URL(hostname);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    final String host = url.getHost();
    final int port = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
    final ChannelFuture retVal;
    final ChannelFuture connectFuture;
    if (proxyConfig != null) {
        final ChannelFuture proxyFuture = bootstrap.connect(new InetSocketAddress(proxyConfig.getHost(), proxyConfig.getPort()));
        connectFuture = Channels.future(proxyFuture.getChannel());
        final String proxyUri = StringUtils.format("%s:%d", host, port);
        DefaultHttpRequest connectRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, proxyUri);
        if (proxyConfig.getUser() != null) {
            connectRequest.headers().add("Proxy-Authorization", Request.makeBasicAuthenticationString(proxyConfig.getUser(), proxyConfig.getPassword()));
        }
        proxyFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture f1) {
                if (f1.isSuccess()) {
                    final Channel channel = f1.getChannel();
                    channel.getPipeline().addLast(DRUID_PROXY_HANDLER, new SimpleChannelUpstreamHandler() {

                        @Override
                        public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
                            Object msg = e.getMessage();
                            final ChannelPipeline pipeline = ctx.getPipeline();
                            pipeline.remove(DRUID_PROXY_HANDLER);
                            if (msg instanceof HttpResponse) {
                                HttpResponse httpResponse = (HttpResponse) msg;
                                if (HttpResponseStatus.OK.equals(httpResponse.getStatus())) {
                                    // When the HttpClientCodec sees the CONNECT response complete, it goes into a "done"
                                    // mode which makes it just do nothing.  Swap it with a new instance that will cover
                                    // subsequent requests
                                    pipeline.replace("codec", "codec", new HttpClientCodec());
                                    connectFuture.setSuccess();
                                } else {
                                    connectFuture.setFailure(new ChannelException(StringUtils.format("Got status[%s] from CONNECT request to proxy[%s]", httpResponse.getStatus(), proxyUri)));
                                }
                            } else {
                                connectFuture.setFailure(new ChannelException(StringUtils.format("Got message of type[%s], don't know what to do.", msg.getClass())));
                            }
                        }
                    });
                    channel.write(connectRequest).addListener(new ChannelFutureListener() {

                        @Override
                        public void operationComplete(ChannelFuture f2) {
                            if (!f2.isSuccess()) {
                                connectFuture.setFailure(new ChannelException(StringUtils.format("Problem with CONNECT request to proxy[%s]", proxyUri), f2.getCause()));
                            }
                        }
                    });
                } else {
                    connectFuture.setFailure(new ChannelException(StringUtils.format("Problem connecting to proxy[%s]", proxyUri), f1.getCause()));
                }
            }
        });
    } else {
        connectFuture = bootstrap.connect(new InetSocketAddress(host, port));
    }
    if ("https".equals(url.getProtocol())) {
        if (sslContext == null) {
            throw new IllegalStateException("No sslContext set, cannot do https");
        }
        final SSLEngine sslEngine = sslContext.createSSLEngine(host, port);
        final SSLParameters sslParameters = new SSLParameters();
        sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
        sslEngine.setSSLParameters(sslParameters);
        sslEngine.setUseClientMode(true);
        final SslHandler sslHandler = new SslHandler(sslEngine, SslHandler.getDefaultBufferPool(), false, timer, sslHandshakeTimeout);
        // https://github.com/netty/netty/issues/160
        sslHandler.setCloseOnSSLException(true);
        final ChannelFuture handshakeFuture = Channels.future(connectFuture.getChannel());
        connectFuture.getChannel().getPipeline().addLast("connectionErrorHandler", new SimpleChannelUpstreamHandler() {

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
                final Channel channel = ctx.getChannel();
                if (channel == null) {
                    // For the case where this pipeline is not attached yet.
                    handshakeFuture.setFailure(new ChannelException(StringUtils.format("Channel is null. The context name is [%s]", ctx.getName())));
                    return;
                }
                handshakeFuture.setFailure(e.getCause());
                if (channel.isOpen()) {
                    channel.close();
                }
            }
        });
        connectFuture.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture f) {
                if (f.isSuccess()) {
                    final ChannelPipeline pipeline = f.getChannel().getPipeline();
                    pipeline.addFirst("ssl", sslHandler);
                    sslHandler.handshake().addListener(new ChannelFutureListener() {

                        @Override
                        public void operationComplete(ChannelFuture f2) {
                            if (f2.isSuccess()) {
                                handshakeFuture.setSuccess();
                            } else {
                                handshakeFuture.setFailure(new ChannelException(StringUtils.format("Failed to handshake with host[%s]", hostname), f2.getCause()));
                            }
                        }
                    });
                } else {
                    handshakeFuture.setFailure(new ChannelException(StringUtils.format("Failed to connect to host[%s]", hostname), f.getCause()));
                }
            }
        });
        retVal = handshakeFuture;
    } else {
        retVal = connectFuture;
    }
    return retVal;
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) ExceptionEvent(org.jboss.netty.channel.ExceptionEvent) MalformedURLException(java.net.MalformedURLException) InetSocketAddress(java.net.InetSocketAddress) MessageEvent(org.jboss.netty.channel.MessageEvent) SSLEngine(javax.net.ssl.SSLEngine) Channel(org.jboss.netty.channel.Channel) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ChannelHandlerContext(org.jboss.netty.channel.ChannelHandlerContext) SimpleChannelUpstreamHandler(org.jboss.netty.channel.SimpleChannelUpstreamHandler) HttpClientCodec(org.jboss.netty.handler.codec.http.HttpClientCodec) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) URL(java.net.URL) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) SslHandler(org.jboss.netty.handler.ssl.SslHandler) SSLParameters(javax.net.ssl.SSLParameters) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) ChannelException(org.jboss.netty.channel.ChannelException)

Example 9 with SslHandler

use of org.jboss.netty.handler.ssl.SslHandler in project load-balancer by RestComm.

the class HttpClientPipelineFactory method getPipeline.

public ChannelPipeline getPipeline() throws Exception {
    // Create a default pipeline implementation.
    ChannelPipeline pipeline = pipeline();
    pipeline.addLast("decoder", new HttpResponseDecoder());
    // Remove the following line if you don't want automatic content decompression.
    // pipeline.addLast("inflater", new HttpContentDecompressor());
    pipeline.addLast("encoder", new HttpRequestEncoder());
    // http://code.google.com/p/commscale/issues/detail?id=5 support for HttpChunks,
    // https://telestax.atlassian.net/browse/LB-8 if commented accessing the RestComm Management console fails, so making the maxContentLength Configurable
    // pipeline.addLast("aggregator", new HttpChunkAggregator(maxContentLength));
    pipeline.addLast("handler", new HttpResponseHandler(balancerRunner));
    if (isUseSsl) {
        SslConfiguration sslConfig = new SslConfiguration();
        sslConfig.setTrustAll(true);
        sslConfig.setValidateCerts(true);
        sslConfig.setValidatePeerCerts(true);
        SslContextFactory factory = new SslContextFactory(sslConfig);
        SSLEngine sslEngine = factory.newSslEngine();
        sslEngine.setUseClientMode(true);
        pipeline.addFirst("ssl", new SslHandler(sslEngine));
    }
    return pipeline;
}
Also used : SslContextFactory(com.cloudhopper.smpp.ssl.SslContextFactory) SslConfiguration(com.cloudhopper.smpp.ssl.SslConfiguration) SSLEngine(javax.net.ssl.SSLEngine) HttpRequestEncoder(org.jboss.netty.handler.codec.http.HttpRequestEncoder) HttpResponseDecoder(org.jboss.netty.handler.codec.http.HttpResponseDecoder) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) SslHandler(org.jboss.netty.handler.ssl.SslHandler)

Example 10 with SslHandler

use of org.jboss.netty.handler.ssl.SslHandler in project load-balancer by RestComm.

the class HttpServerPipelineFactory method getPipeline.

public ChannelPipeline getPipeline() throws Exception {
    // Create a default pipeline implementation.
    ChannelPipeline pipeline = pipeline();
    if (isSecure) {
        SslConfiguration sslConfig = new SslConfiguration();
        sslConfig.setKeyStorePath(balancerRunner.balancerContext.lbConfig.getSslConfiguration().getKeyStore());
        sslConfig.setKeyStorePassword(balancerRunner.balancerContext.lbConfig.getSslConfiguration().getKeyStorePassword());
        sslConfig.setTrustStorePath(balancerRunner.balancerContext.lbConfig.getSslConfiguration().getTrustStore());
        sslConfig.setTrustStorePassword(balancerRunner.balancerContext.lbConfig.getSslConfiguration().getTrustStorePassword());
        String sProtocols = balancerRunner.balancerContext.lbConfig.getSslConfiguration().getTlsClientProtocols();
        String sCipherSuites = balancerRunner.balancerContext.lbConfig.getSslConfiguration().getEnabledCipherSuites();
        if (sProtocols != null) {
            String[] protocols = sProtocols.split(",");
            sslConfig.setIncludeProtocols(protocols);
        }
        if (sCipherSuites != null) {
            String[] cipherSuites = sCipherSuites.split(",");
            sslConfig.setIncludeCipherSuites(cipherSuites);
        }
        SslContextFactory factory = new SslContextFactory(sslConfig);
        SSLEngine sslEngine = factory.newSslEngine();
        sslEngine.setUseClientMode(false);
        pipeline.addLast("ssl", new SslHandler(sslEngine));
    }
    pipeline.addLast("decoder", new HttpRequestDecoder());
    // http://code.google.com/p/commscale/issues/detail?id=5 support for HttpChunks
    // https://telestax.atlassian.net/browse/LB-8 if commented accessing the RestComm Management console fails, so making the maxContentLength Configurable
    // pipeline.addLast("aggregator", new HttpChunkAggregator(maxContentLength));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    // pipeline.addLast("deflater", new HttpContentCompressor());
    if (balancerRunner.balancerContext.terminateTLSTraffic)
        pipeline.addLast("handler", new HttpRequestHandler(balancerRunner, false));
    else
        pipeline.addLast("handler", new HttpRequestHandler(balancerRunner, isSecure));
    return pipeline;
}
Also used : HttpResponseEncoder(org.jboss.netty.handler.codec.http.HttpResponseEncoder) SslContextFactory(com.cloudhopper.smpp.ssl.SslContextFactory) SslConfiguration(com.cloudhopper.smpp.ssl.SslConfiguration) SSLEngine(javax.net.ssl.SSLEngine) HttpRequestDecoder(org.jboss.netty.handler.codec.http.HttpRequestDecoder) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) SslHandler(org.jboss.netty.handler.ssl.SslHandler)

Aggregations

SslHandler (org.jboss.netty.handler.ssl.SslHandler)24 SSLEngine (javax.net.ssl.SSLEngine)16 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)10 SslConfiguration (com.cloudhopper.smpp.ssl.SslConfiguration)8 SslContextFactory (com.cloudhopper.smpp.ssl.SslContextFactory)8 InetSocketAddress (java.net.InetSocketAddress)7 ChannelHandler (org.jboss.netty.channel.ChannelHandler)5 Channel (org.jboss.netty.channel.Channel)4 ChannelFuture (org.jboss.netty.channel.ChannelFuture)4 HttpRequestDecoder (org.jboss.netty.handler.codec.http.HttpRequestDecoder)4 HttpResponseEncoder (org.jboss.netty.handler.codec.http.HttpResponseEncoder)4 SmppSessionPduDecoder (com.cloudhopper.smpp.channel.SmppSessionPduDecoder)3 RecoverablePduException (com.cloudhopper.smpp.type.RecoverablePduException)3 UnrecoverablePduException (com.cloudhopper.smpp.type.UnrecoverablePduException)3 SocketAddress (java.net.SocketAddress)3 SSLContext (javax.net.ssl.SSLContext)3 DefaultPduTranscoder (com.cloudhopper.smpp.transcoder.DefaultPduTranscoder)2 DefaultPduTranscoderContext (com.cloudhopper.smpp.transcoder.DefaultPduTranscoderContext)2 Executor (java.util.concurrent.Executor)2 ChannelHandlerFactory (org.apache.camel.component.netty.ChannelHandlerFactory)2