Java 类io.netty.handler.ssl.SslHandler 实例源码

项目:Camel    文件:HttpServerSharedInitializerFactory.java   
@Override
protected void initChannel(Channel ch) throws Exception {
    // create a new pipeline
    ChannelPipeline pipeline = ch.pipeline();

    SslHandler sslHandler = configureServerSSLOnDemand();
    if (sslHandler != null) {
        LOG.debug("Server SSL handler configured and added as an interceptor against the ChannelPipeline: {}", sslHandler);
        pipeline.addLast("ssl", sslHandler);
    }

    pipeline.addLast("decoder", new HttpRequestDecoder(409, configuration.getMaxHeaderSize(), 8192));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    if (configuration.isChunked()) {
        pipeline.addLast("aggregator", new HttpObjectAggregator(configuration.getChunkedMaxContentLength()));
    }
    if (configuration.isCompression()) {
        pipeline.addLast("deflater", new HttpContentCompressor());
    }

    pipeline.addLast("handler", channelFactory.getChannelHandler());
}
项目:onedatashare    文件:HTTPInitializer.java   
/**
 * Adds pipelines to channel.
 * 
 *  @param ch channel to be operated on
 */
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipe = ch.pipeline();

  if (ssl) {
    // HTTPs connection
    SSLEngine sslEng = getSsl(null);
    sslEng.setUseClientMode(true);
    pipe.addLast("SSL", new SslHandler(sslEng, false));
  }

  pipe.addFirst("Timer", new ReadTimeoutHandler(30));
  pipe.addLast("Codec", new HttpClientCodec());
  pipe.addLast("Inflater", new HttpContentDecompressor());
  pipe.addLast("Handler", new HTTPMessageHandler(builder));
}
项目:iothub    文件:MqttTransportServerInitializer.java   
@Override
  public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    SslHandler sslHandler = null;
    if (sslHandlerProvider != null) {
      sslHandler = sslHandlerProvider.getSslHandler();
      pipeline.addLast(sslHandler);
    }
    pipeline.addLast("decoder", new MqttDecoder(MAX_PAYLOAD_SIZE));
    pipeline.addLast("encoder", MqttEncoder.INSTANCE);

    MqttTransportHandler handler = new MqttTransportHandler(msgProducer, deviceService, authService, assetService,
        assetAuthService, relationService, sslHandler);
    pipeline.addLast(handler);

//    ch.closeFuture().addListener(handler);

  }
项目:util4j    文件:HttpServerInitHandler.java   
@Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        if(sslCtx!=null)
        {
            p.addLast(new SslHandler(sslCtx.newEngine(ch.alloc())));
        }
        p.addLast(new HttpResponseEncoder());//必须放在最前面,如果decoder途中需要回复消息,则decoder前面需要encoder
        p.addLast(new HttpRequestDecoder());
        p.addLast(new HttpObjectAggregator(65536));//限制contentLength
        //大文件传输处理
//      p.addLast(new ChunkedWriteHandler());
//      p.addLast(new HttpContentCompressor());
        //跨域配置
        CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
        p.addLast(new CorsHandler(corsConfig));
        p.addLast(new DefaultListenerHandler<HttpRequest>(listener));
    }
项目:Stork    文件:HTTPInitializer.java   
/**
 * Adds pipelines to channel.
 * 
 *  @param ch channel to be operated on
 */
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipe = ch.pipeline();

  if (ssl) {
    // HTTPs connection
    SSLEngine sslEng = getSsl(null);
    sslEng.setUseClientMode(true);
    pipe.addLast("SSL", new SslHandler(sslEng, false));
  }

  pipe.addFirst("Timer", new ReadTimeoutHandler(30));
  pipe.addLast("Codec", new HttpClientCodec());
  pipe.addLast("Inflater", new HttpContentDecompressor());
  pipe.addLast("Handler", new HTTPMessageHandler(builder));
}
项目:NioSmtpClient    文件:SmtpSession.java   
private CompletionStage<SmtpClientResponse> performTlsHandshake(SmtpClientResponse r) {
  CompletableFuture<SmtpClientResponse> ourFuture = new CompletableFuture<>();

  SslHandler sslHandler = new SslHandler(sslEngineSupplier.get());
  channel.pipeline().addFirst(sslHandler);

  sslHandler.handshakeFuture().addListener(nettyFuture -> {
    if (nettyFuture.isSuccess()) {
      ourFuture.complete(r);
    } else {
      ourFuture.completeExceptionally(nettyFuture.cause());
      close();
    }
  });

  return ourFuture;
}
项目:NioSmtpClient    文件:SmtpSessionTest.java   
@Test
public void itReturnsTheStartTlsResponseIfTheTlsHandshakeSucceeds() throws Exception {
  CompletableFuture<SmtpClientResponse> f = session.startTls();
  responseFuture.complete(Lists.newArrayList(OK_RESPONSE));

  // respond to the ehlo sent after starttls
  secondResponseFuture.complete(Lists.newArrayList(new DefaultSmtpResponse(250,
      "smtp.example.com Hello client.example.com",
      "AUTH PLAIN LOGIN",
      "PIPELINING")));

  // the handshake succeeds
  SslHandler sslHandler = getSslHandler();
  ((DefaultPromise<Channel>) sslHandler.handshakeFuture()).setSuccess(channel);

  assertThat(f.isDone()).isTrue();
  assertThat(f.get().getResponses().get(0).code()).isEqualTo(OK_RESPONSE.code());

  // check EHLO is parsed again
  assertThat(session.getEhloResponse().isSupported(Extension.PIPELINING)).isTrue();
  assertThat(session.getEhloResponse().isSupported(Extension.STARTTLS)).isFalse();
}
项目:NioSmtpClient    文件:SmtpSessionTest.java   
private SslHandler getSslHandler() throws Exception {
  // get SslHandler if it was added to the pipeline
  ArgumentCaptor<ChannelHandler> captor = ArgumentCaptor.forClass(ChannelHandler.class);
  verify(pipeline).addFirst(captor.capture());
  SslHandler sslHandler = (SslHandler) captor.getValue();

  // mock and store the context so we can get the handshake future
  ChannelHandlerContext context = mock(ChannelHandlerContext.class);
  when(context.executor()).thenReturn(ImmediateEventExecutor.INSTANCE);
  when(context.channel()).thenReturn(mock(Channel.class, Answers.RETURNS_MOCKS.get()));

  // add the handler but prevent the handshake from running automatically
  when(channel.isActive()).thenReturn(false);
  sslHandler.handlerAdded(context);

  return sslHandler;
}
项目:aws-sdk-java-v2    文件:ChannelPipelineInitializer.java   
@Override
public void channelCreated(Channel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();

    if (sslContext != null) {
        SslHandler handler = sslContext.newHandler(ch.alloc());
        p.addLast(handler);
        handler.handshakeFuture().addListener(future -> {
            if (!future.isSuccess()) {
                log.error(() -> "SSL handshake failed.", future.cause());
            }
        });
    }

    p.addLast(new HttpClientCodec());
    p.addLast(handlers);
    // Disabling auto-read is needed for backpressure to work
    ch.config().setOption(ChannelOption.AUTO_READ, false);
}
项目:iotplatform    文件:MqttTransportServerInitializer.java   
@Override
  public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    SslHandler sslHandler = null;
    if (sslHandlerProvider != null) {
      sslHandler = sslHandlerProvider.getSslHandler();
      pipeline.addLast(sslHandler);
    }
    pipeline.addLast("decoder", new MqttDecoder(MAX_PAYLOAD_SIZE));
    pipeline.addLast("encoder", MqttEncoder.INSTANCE);

    MqttTransportHandler handler = new MqttTransportHandler(msgProducer, deviceService, authService, assetService,
        assetAuthService, relationService, sslHandler);
    pipeline.addLast(handler);

//    ch.closeFuture().addListener(handler);

  }
项目:riposte    文件:HttpChannelInitializerTest.java   
@Test
public void initChannel_adds_sslCtx_handler_first_if_available_and_no_utility_handlers() throws SSLException {
    // given
    SslContext sslCtx = new JdkSslClientContext();
    HttpChannelInitializer hci = basicHttpChannelInitializer(sslCtx, 0, 100, false, mock(RequestValidator.class),
                                                             createRequestAndResponseFilterMock());

    // when
    hci.initChannel(socketChannelMock);

    // then
    ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture());
    List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues();
    assertThat(handlers.get(0), instanceOf(SslHandler.class));
}
项目:netty-tutorials    文件:SecureChatServerHandler.java   
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    // Once session is secured, send a greeting and register the channel to
    // the global channel
    // list so the channel received the messages from others.
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(Future<Channel> future)
                        throws Exception {
                    ctx.writeAndFlush("Welcome to "
                            + InetAddress.getLocalHost().getHostName()
                            + " secure chat service!\n");
                    ctx.writeAndFlush("Your session is protected by "
                            + ctx.pipeline().get(SslHandler.class).engine()
                            .getSession().getCipherSuite()
                            + " cipher suite.\n");

                    channels.add(ctx.channel());
                }
            });
}
项目:megaphone    文件:ChannelManager.java   
public SslHandler addSslHandler(ChannelPipeline pipeline, Uri uri, String virtualHost) {
    String peerHost;
    int peerPort;

    if (virtualHost != null) {
        int i = virtualHost.indexOf(':');
        if (i == -1) {
            peerHost = virtualHost;
            peerPort = uri.getSchemeDefaultPort();
        } else {
            peerHost = virtualHost.substring(0, i);
            peerPort = Integer.valueOf(virtualHost.substring(i + 1));
        }

    } else {
        peerHost = uri.getHost();
        peerPort = uri.getExplicitPort();
    }

    SslHandler sslHandler = createSslHandler(peerHost, peerPort);
    pipeline.addFirst(ChannelManager.SSL_HANDLER, sslHandler);
    return sslHandler;
}
项目:reactor-netty    文件:NettyOptions.java   
/**
 * Return a new eventual {@link SslHandler}, optionally with SNI activated
 *
 * @param allocator {@link ByteBufAllocator} to allocate for packet storage
 * @param sniInfo {@link Tuple2} with hostname and port for SNI (any null will skip SNI).
 * @return a new eventual {@link SslHandler} with SNI activated
 */
public final SslHandler getSslHandler(ByteBufAllocator allocator,
        Tuple2<String, Integer> sniInfo) {
    SslContext sslContext =
            this.sslContext == null ? defaultSslContext() : this.sslContext;

    if (sslContext == null) {
        return null;
    }

    Objects.requireNonNull(allocator, "allocator");
    SslHandler sslHandler;
    if (sniInfo != null && sniInfo.getT1() != null && sniInfo.getT2() != null) {
        sslHandler = sslContext.newHandler(allocator, sniInfo.getT1(), sniInfo.getT2());
    }
    else {
        sslHandler = sslContext.newHandler(allocator);
    }
    sslHandler.setHandshakeTimeoutMillis(sslHandshakeTimeoutMillis);
    sslHandler.setCloseNotifyFlushTimeoutMillis(sslCloseNotifyFlushTimeoutMillis);
    sslHandler.setCloseNotifyReadTimeoutMillis(sslCloseNotifyReadTimeoutMillis);
    return sslHandler;
}
项目:tealess    文件:HTTPSInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipeline = ch.pipeline();

  SSLEngine engine = context.createSSLEngine();
  engine.setUseClientMode(true);
  SslHandler sslHandler = new SslHandler(engine);
  //pipeline.addLast(sslHandler);
  pipeline.addLast(new SimpleChannelInboundHandler<Object>() {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
      System.out.println(msg);
    }
  });
  //pipeline.addLast(new HttpRequestDecoder());
  //pipeline.addLast(new HttpResponseEncoder());
  //pipeline.addLast(new HttpContentCompressor());
  //pipeline.addLast(new HTTPClientHandler());
}
项目:JavaAyo    文件:SecureChatServerHandler.java   
@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
            new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush(
                            "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n");
                    ctx.writeAndFlush(
                            "Your session is protected by " +
                                    ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() +
                                    " cipher suite.\n");

                    channels.add(ctx.channel());
                }
    });
}
项目:JavaAyo    文件:FileServerHandler.java   
@Override
public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    RandomAccessFile raf = null;
    long length = -1;
    try {
        raf = new RandomAccessFile(msg, "r");
        length = raf.length();
    } catch (Exception e) {
        ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n');
        return;
    } finally {
        if (length < 0 && raf != null) {
            raf.close();
        }
    }

    ctx.write("OK: " + raf.length() + '\n');
    if (ctx.pipeline().get(SslHandler.class) == null) {
        // SSL not enabled - can use zero-copy file transfer.
        ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length));
    } else {
        // SSL enabled - cannot use zero-copy file transfer.
        ctx.write(new ChunkedFile(raf));
    }
    ctx.writeAndFlush("\n");
}
项目:little_mitm    文件:ProxyConnection.java   
/**
 * Encrypts traffic on this connection with SSL/TLS.
 * 
 * @param pipeline
 *            the ChannelPipeline on which to enable encryption
 * @param sslEngine
 *            the {@link SSLEngine} for doing the encryption
 * @param authenticateClients
 *            determines whether to authenticate clients or not
 * @return a Future for when the SSL handshake has completed
 */
protected Future<Channel> encrypt(ChannelPipeline pipeline,
        SSLEngine sslEngine,
        boolean authenticateClients) {
    LOG.debug("Enabling encryption with SSLEngine: {}",
            sslEngine);
    this.sslEngine = sslEngine;
    sslEngine.setUseClientMode(runsAsSslClient);
    sslEngine.setNeedClientAuth(authenticateClients);
    if (null != channel) {
        channel.config().setAutoRead(true);
    }
    SslHandler handler = new SslHandler(sslEngine);
    if(pipeline.get("ssl") == null) {
        pipeline.addFirst("ssl", handler);
    } else {
        // The second SSL handler is added to handle the case
        // where the proxy (running as MITM) has to chain with
        // another SSL enabled proxy. The second SSL handler
        // is to perform SSL with the server.
        pipeline.addAfter("ssl", "sslWithServer", handler);
    }
    return handler.handshakeFuture();
}
项目:jlogstash-input-plugin    文件:Server.java   
/**
 * 加入打日志、ssl、idleState、BeatsHandler和BeatsParser这几个handler。
 */
public void initChannel(SocketChannel socket) throws SSLException {
    ChannelPipeline pipeline = socket.pipeline();

    pipeline.addLast(LOGGER_HANDLER, loggingHandler);

    if(server.isSslEnable()) {
        SslHandler sslHandler = sslBuilder.build(socket.alloc());
        pipeline.addLast(SSL_HANDLER, sslHandler);
    }

    // We have set a specific executor for the idle check, because the `beatsHandler` can be
    // blocked on the queue, this the idleStateHandler manage the `KeepAlive` signal.
    pipeline.addLast(idleExecutorGroup, KEEP_ALIVE_HANDLER, new IdleStateHandler(60*15, 5, 0));
    pipeline.addLast(BEATS_PARSER, new BeatsParser());
    pipeline.addLast(BEATS_HANDLER, this.beatsHandler);
}
项目:jlogstash-input-plugin    文件:SslSimpleBuilder.java   
public SslHandler build(ByteBufAllocator bufferAllocator) throws SSLException {
    SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase);

    builder.ciphers(Arrays.asList(ciphers));

    if(requireClientAuth()) {
        logger.debug("Certificate Authorities: " + certificateAuthorities);
        builder.trustManager(new File(certificateAuthorities));
    }

    SslContext context = builder.build();
    SslHandler sslHandler = context.newHandler(bufferAllocator);

    SSLEngine engine = sslHandler.engine();
    engine.setEnabledProtocols(protocols);


    if(requireClientAuth()) {
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(true);
    }

    return sslHandler;
}
项目:drill    文件:UserClient.java   
@Override protected void setupSSL(ChannelPipeline pipe,
    ConnectionMultiListener.SSLHandshakeListener sslHandshakeListener) {

  String peerHost = endpoint.getAddress();
  int peerPort = endpoint.getUserPort();
  SSLEngine sslEngine = sslConfig.createSSLEngine(allocator, peerHost, peerPort);

  // Add SSL handler into pipeline
  SslHandler sslHandler = new SslHandler(sslEngine);
  sslHandler.setHandshakeTimeoutMillis(sslConfig.getHandshakeTimeout());

  // Add a listener for SSL Handshake complete. The Drill client handshake will be enabled only
  // after this is done.
  sslHandler.handshakeFuture().addListener(sslHandshakeListener);
  pipe.addFirst(RpcConstants.SSL_HANDLER, sslHandler);
  logger.debug(sslConfig.toString());
}
项目:nomulus    文件:SslClientInitializer.java   
@Override
protected void initChannel(C channel) throws Exception {
  BackendProtocol protocol = (BackendProtocol) channel.attr(PROTOCOL_KEY).get();
  checkNotNull(protocol, "Protocol is not set for channel: %s", channel);
  SslHandler sslHandler =
      SslContextBuilder.forClient()
          .sslProvider(sslProvider)
          .trustManager(trustedCertificates)
          .build()
          .newHandler(channel.alloc(), protocol.host(), protocol.port());

  // Enable hostname verification.
  SSLEngine sslEngine = sslHandler.engine();
  SSLParameters sslParameters = sslEngine.getSSLParameters();
  sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
  sslEngine.setSSLParameters(sslParameters);

  channel.pipeline().addLast(sslHandler);
}
项目:Camel    文件:DefaultClientInitializerFactory.java   
private SslHandler configureClientSSLOnDemand() throws Exception {
    if (!producer.getConfiguration().isSsl()) {
        return null;
    }

    if (producer.getConfiguration().getSslHandler() != null) {
        return producer.getConfiguration().getSslHandler();
    } else if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(true);
        if (producer.getConfiguration().getSslContextParameters() == null) {
            // just set the enabledProtocols if the SslContextParameter doesn't set
            engine.setEnabledProtocols(producer.getConfiguration().getEnabledProtocols().split(","));
        }
        return new SslHandler(engine);
    }

    return null;
}
项目:Camel    文件:DefaultServerInitializerFactory.java   
private SslHandler configureServerSSLOnDemand() throws Exception {
    if (!consumer.getConfiguration().isSsl()) {
        return null;
    }

    if (consumer.getConfiguration().getSslHandler() != null) {
        return consumer.getConfiguration().getSslHandler();
    } else if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(consumer.getConfiguration().isNeedClientAuth());
        if (consumer.getConfiguration().getSslContextParameters() == null) {
            // just set the enabledProtocols if the SslContextParameter doesn't set
            engine.setEnabledProtocols(consumer.getConfiguration().getEnabledProtocols().split(","));
        }
        return new SslHandler(engine);
    }

    return null;
}
项目:Camel    文件:HttpClientInitializerFactory.java   
private SslHandler configureClientSSLOnDemand() throws Exception {
    if (!producer.getConfiguration().isSsl()) {
        return null;
    }

    if (producer.getConfiguration().getSslHandler() != null) {
        return producer.getConfiguration().getSslHandler();
    } else if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(true);
        if (producer.getConfiguration().getSslContextParameters() == null) {
            // just set the enabledProtocols if the SslContextParameter doesn't set
            engine.setEnabledProtocols(producer.getConfiguration().getEnabledProtocols().split(","));
        }
        return new SslHandler(engine);
    }

    return null;
}
项目:Camel    文件:HttpServerInitializerFactory.java   
private SslHandler configureServerSSLOnDemand() throws Exception {
    if (!consumer.getConfiguration().isSsl()) {
        return null;
    }

    if (consumer.getConfiguration().getSslHandler() != null) {
        return consumer.getConfiguration().getSslHandler();
    } else if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(consumer.getConfiguration().isNeedClientAuth());
        if (consumer.getConfiguration().getSslContextParameters() == null) {
            // just set the enabledProtocols if the SslContextParameter doesn't set
            engine.setEnabledProtocols(consumer.getConfiguration().getEnabledProtocols().split(","));
        }
        return new SslHandler(engine);
    }

    return null;
}
项目:Camel    文件:HttpServerSharedInitializerFactory.java   
private SslHandler configureServerSSLOnDemand() throws Exception {
    if (!configuration.isSsl()) {
        return null;
    }

    if (configuration.getSslHandler() != null) {
        return configuration.getSslHandler();
    } else if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(configuration.isNeedClientAuth());
        if (configuration.getSslContextParameters() == null) {
            // just set the enabledProtocols if the SslContextParameter doesn't set
            engine.setEnabledProtocols(configuration.getEnabledProtocols().split(","));
        }
        return new SslHandler(engine);
    }

    return null;
}
项目:spike.x    文件:TCPSSLHelper.java   
private SslHandler createHandler(SSLEngine engine, boolean client) {
    engine.setEnabledProtocols(ENABLED_PROTOCOLS);
    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;
            }
        }
    } else if (verifyHost) {
        SSLParameters sslParameters = engine.getSSLParameters();
        sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
        engine.setSSLParameters(sslParameters);
    }
    return new SslHandler(engine);
}
项目:netty-ssl-routing-proxy    文件:SslInboundHandler.java   
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);
    SslHandler sslHandler = Objects.requireNonNull(ctx.pipeline().get(SslHandler.class));
    sslHandler.handshakeFuture().addListener(future -> {
        if (future.isSuccess()) {
            RoutingContext context = new RoutingContext();
            context.setCertificateChain(sslHandler.engine().getSession().getPeerCertificateChain());

            Optional<RoutingTarget> target = config.getRoutingRule().route(context);
            if (target.isPresent()) {
                ctx.pipeline().get(RoutingProxyFrontendHandler.class).initProxyConnection(ctx, target.get());
            } else {
                logger.error("Unable to find target for routing context: " + context);
                ctx.close();
            }
        } else {
            logger.error("Handshake failure");
            ctx.close();
        }
    });
}
项目:cloud-pubsub-mqtt-proxy    文件:NettyAcceptor.java   
/**
 * Initialize the the various transport protocols for this server,
 * and setup their handlers/callbacks.
 */
@Override
public void initialize(IMessaging messaging, Properties props) throws IOException {
  bossGroup = new NioEventLoopGroup();
  workerGroup = new NioEventLoopGroup();

  initializePlainTcpTransport(messaging, props);
  initializeWebSocketTransport(messaging, props);
  String sslTcpPortProp = props.getProperty(Constants.SSL_PORT_PROPERTY_NAME);
  String wssPortProp = props.getProperty(Constants.WSS_PORT_PROPERTY_NAME);
  if (sslTcpPortProp != null || wssPortProp != null) {
    SslHandler sslHandler = initSslHandler(props);
    if (sslHandler == null) {
      LOG.error("Can't initialize SSLHandler layer! Exiting, check your configuration of jks");
      return;
    }
    initializeSslTcpTransport(messaging, props, sslHandler);
    initializeWssTransport(messaging, props, sslHandler);
  }
  // initialize ProxyContext and Pubsub impl
  context.open();
  pubsub.initialize(context);
}
项目:LittleProxy    文件:ProxyConnection.java   
/**
 * Encrypts traffic on this connection with SSL/TLS.
 * 
 * @param pipeline
 *            the ChannelPipeline on which to enable encryption
 * @param sslEngine
 *            the {@link SSLEngine} for doing the encryption
 * @param authenticateClients
 *            determines whether to authenticate clients or not
 * @return a Future for when the SSL handshake has completed
 */
protected Future<Channel> encrypt(ChannelPipeline pipeline,
        SSLEngine sslEngine,
        boolean authenticateClients) {
    LOG.debug("Enabling encryption with SSLEngine: {}",
            sslEngine);
    this.sslEngine = sslEngine;
    sslEngine.setUseClientMode(runsAsSslClient);
    sslEngine.setNeedClientAuth(authenticateClients);
    if (null != channel) {
        channel.config().setAutoRead(true);
    }
    SslHandler handler = new SslHandler(sslEngine);
    pipeline.addFirst("ssl", handler);
    return handler.handshakeFuture();
}
项目:GameServerFramework    文件:NHttpRequest.java   
@Override
public void configNewChannel(NioSocketChannel channel) {
    super.configNewChannel(channel);
    ChannelPipeline pipeline = channel.pipeline();
    // 添加 SSL 数据支持
    if (requestConfig.https()) {
        SslContext sslContent = NettyCenter.singleInstance().getSimpleClientSslContext();
        SSLEngine engine = sslContent.newEngine(channel.alloc());
        pipeline.addLast("ssl", new SslHandler(engine));
    }
    // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
    pipeline.addLast("decoder", new HttpResponseDecoder());
    // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
    pipeline.addLast("encoder", new HttpRequestEncoder());
    // 接收的请求累计器
    pipeline.addLast("aggegator", new HttpObjectAggregator(0x30000));
    // mime 类型写出
    pipeline.addLast("streamew", new ChunkedWriteHandler());
    // 添加解压器
    pipeline.addLast("decompressor", new HttpContentDecompressor());
    // add new handler
    pipeline.addLast("handler", new NettyHttpRequestChannelHandler());
}
项目:netty4.0.27Learn    文件:SecureChatServerHandler.java   
@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
            new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush(
                            "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n");
                    ctx.writeAndFlush(
                            "Your session is protected by " +
                                    ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() +
                                    " cipher suite.\n");

                    channels.add(ctx.channel());
                }
    });
}
项目:netty4.0.27Learn    文件:FileServerHandler.java   
@Override
public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    RandomAccessFile raf = null;
    long length = -1;
    try {
        raf = new RandomAccessFile(msg, "r");
        length = raf.length();
    } catch (Exception e) {
        ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n');
        return;
    } finally {
        if (length < 0 && raf != null) {
            raf.close();
        }
    }

    ctx.write("OK: " + raf.length() + '\n');
    if (ctx.pipeline().get(SslHandler.class) == null) {
        // SSL not enabled - can use zero-copy file transfer.
        ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length));
    } else {
        // SSL enabled - cannot use zero-copy file transfer.
        ctx.write(new ChunkedFile(raf));
    }
    ctx.writeAndFlush("\n");
}
项目:netty4.0.27Learn    文件:SpdyOrHttpChooser.java   
private boolean initPipeline(ChannelHandlerContext ctx) {
    // Get the SslHandler from the ChannelPipeline so we can obtain the
    // SslEngine from it.
    SslHandler handler = ctx.pipeline().get(SslHandler.class);
    if (handler == null) {
        // SslHandler is needed by SPDY by design.
        throw new IllegalStateException("SslHandler is needed for SPDY");
    }

    SelectedProtocol protocol = getProtocol(handler.engine());
    switch (protocol) {
    case UNKNOWN:
        // Not done with choosing the protocol, so just return here for now,
        return false;
    case SPDY_3_1:
        addSpdyHandlers(ctx, SpdyVersion.SPDY_3_1);
        break;
    case HTTP_1_0:
    case HTTP_1_1:
        addHttpHandlers(ctx);
        break;
    default:
        throw new IllegalStateException("Unknown SelectedProtocol");
    }
    return true;
}
项目:netty-storm    文件:NettySpoutServerHandler.java   
@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
            new GenericFutureListener<Future<Channel>>() {
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush(
                            "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure remote monitoring service!\n");
                    ctx.writeAndFlush(
                            "Your session is protected by " +
                                    ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() +
                                    " cipher suite.\n");

                    channels.add(ctx.channel());
                }
    });
}
项目:carbon-transports    文件:HTTPServerChannelInitializer.java   
@Override
public void initChannel(SocketChannel ch) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Initializing source channel pipeline");
    }

    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));
    }
}
项目:carbon-transports    文件:RedirectChannelInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    // Add the generic handlers to the pipeline
    // e.g. SSL handler
    if (sslEngine != null) {
        if (log.isDebugEnabled()) {
            log.debug("adding ssl handler");
        }
        ch.pipeline().addLast("ssl", new SslHandler(this.sslEngine));
    }
    ch.pipeline().addLast("compressor", new HttpContentCompressor());
    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
    if (httpTraceLogEnabled) {
        ch.pipeline().addLast(Constants.HTTP_TRACE_LOG_HANDLER,
                new HTTPTraceLoggingHandler("tracelog.http.upstream", LogLevel.DEBUG));
    }
    RedirectHandler redirectHandler = new RedirectHandler(sslEngine, httpTraceLogEnabled, maxRedirectCount
            , chunkDisabled, originalChannelContext, isIdleHandlerOfTargetChannelRemoved);
    ch.pipeline().addLast(Constants.REDIRECT_HANDLER, redirectHandler);
}
项目:activemq-artemis    文件:CoreClientOverTwoWaySSLTest.java   
@Override
public boolean intercept(final Packet packet, final RemotingConnection connection) throws ActiveMQException {
   if (packet.getType() == PacketImpl.SESS_SEND) {
      try {
         if (connection.getTransportConnection() instanceof NettyConnection) {
            System.out.println("Passed through....");
            NettyConnection nettyConnection = (NettyConnection) connection.getTransportConnection();
            SslHandler sslHandler = (SslHandler) nettyConnection.getChannel().pipeline().get("ssl");
            Assert.assertNotNull(sslHandler);
            Assert.assertNotNull(sslHandler.engine().getSession());
            Assert.assertNotNull(sslHandler.engine().getSession().getPeerCertificateChain());
         }
      } catch (SSLPeerUnverifiedException e) {
         Assert.fail(e.getMessage());
      }
   }
   return true;
}
项目:activemq-artemis    文件:NettyTcpTransport.java   
@Override
public void channelActive(ChannelHandlerContext context) throws Exception {
   // In the Secure case we need to let the handshake complete before we
   // trigger the connected event.
   if (!isSSL()) {
      handleConnected(context.channel());
   } else {
      SslHandler sslHandler = context.pipeline().get(SslHandler.class);
      sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
         @Override
         public void operationComplete(Future<Channel> future) throws Exception {
            if (future.isSuccess()) {
               LOG.trace("SSL Handshake has completed: {}", channel);
               handleConnected(channel);
            } else {
               LOG.trace("SSL Handshake has failed: {}", channel);
               handleException(channel, future.cause());
            }
         }
      });
   }
}