org.mockito.Answers#io.netty.handler.ssl.SslHandler源码实例Demo

下面列出了org.mockito.Answers#io.netty.handler.ssl.SslHandler 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: grpc-nebula-java   文件: ProtocolNegotiators.java
@Override
public Handler newHandler(GrpcHttp2ConnectionHandler handler) {
  final HostPort hostPort = parseAuthority(handler.getAuthority());

  ChannelHandler sslBootstrap = new ChannelHandlerAdapter() {
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
      SSLEngine sslEngine = sslContext.newEngine(ctx.alloc(), hostPort.host, hostPort.port);
      SSLParameters sslParams = sslEngine.getSSLParameters();
      sslParams.setEndpointIdentificationAlgorithm("HTTPS");
      sslEngine.setSSLParameters(sslParams);
      ctx.pipeline().replace(this, null, new SslHandler(sslEngine, false));
    }
  };
  return new BufferUntilTlsNegotiatedHandler(sslBootstrap, handler);
}
 
源代码2 项目: zuul   文件: Http1MutualSslChannelInitializer.java
@Override
protected void initChannel(Channel ch) throws Exception
{
    SslHandler sslHandler = sslContext.newHandler(ch.alloc());
    sslHandler.engine().setEnabledProtocols(sslContextFactory.getProtocols());

    // Configure our pipeline of ChannelHandlerS.
    ChannelPipeline pipeline = ch.pipeline();

    storeChannel(ch);
    addTimeoutHandlers(pipeline);
    addPassportHandler(pipeline);
    addTcpRelatedHandlers(pipeline);
    pipeline.addLast("ssl", sslHandler);
    addSslInfoHandlers(pipeline, isSSlFromIntermediary);
    addSslClientCertChecks(pipeline);
    addHttp1Handlers(pipeline);
    addHttpRelatedHandlers(pipeline);
    addZuulHandlers(pipeline);
}
 
@Test
public void tlsHandler_userEventTriggeredSslEvent_supportedProtocolGrpcExp() throws Exception {
  SslHandler goodSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "grpc-exp";
    }
  };

  ChannelHandler handler = new ServerTlsHandler(sslContext, grpcHandler);
  pipeline.addLast(handler);

  pipeline.replace(SslHandler.class, null, goodSslHandler);
  channelHandlerCtx = pipeline.context(handler);
  Object sslEvent = SslHandshakeCompletionEvent.SUCCESS;

  pipeline.fireUserEventTriggered(sslEvent);

  assertTrue(channel.isOpen());
  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNotNull(grpcHandlerCtx);
}
 
源代码4 项目: Bats   文件: 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());
}
 
@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());
                }
    });
}
 
源代码6 项目: arcusipcd   文件: Ipcd10ChannelInitializer.java
@Override
protected void initChannel(SocketChannel ch) throws Exception {
	
	ChannelPipeline pipeline = ch.pipeline();
	
	if (serverTlsContext != null && serverTlsContext.useTls()) {
		SSLEngine engine = serverTlsContext.getContext().createSSLEngine();
		engine.setUseClientMode(false);
		pipeline.addLast("tls", new SslHandler(engine));
	}
	
	pipeline.addLast("encoder", new HttpResponseEncoder());
       pipeline.addLast("decoder", new HttpRequestDecoder());
       pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
       pipeline.addLast("handler", new Ipcd10WebSocketServerHandler(false));
}
 
源代码7 项目: qpid-jms   文件: NettyServer.java
@Override
public void channelActive(final ChannelHandlerContext ctx) {
    LOG.info("NettyServerHandler -> New active channel: {}", ctx.channel());
    SslHandler handler = ctx.pipeline().get(SslHandler.class);
    if (handler != null) {
        handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
            @Override
            public void operationComplete(Future<Channel> future) throws Exception {
                LOG.info("Server -> SSL handshake completed. Succeeded: {}", future.isSuccess());
                if (!future.isSuccess()) {
                    ctx.close();
                }
            }
        });
    }

    channelActiveCount.incrementAndGet();
}
 
源代码8 项目: 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);
}
 
源代码9 项目: cxf   文件: NettyHttpServletPipelineFactory.java
protected ChannelPipeline getDefaulHttpChannelPipeline(Channel channel) throws Exception {

        // Create a default pipeline implementation.
        ChannelPipeline pipeline = channel.pipeline();

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

        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("encoder", new HttpResponseEncoder());
        pipeline.addLast("aggregator", new HttpObjectAggregator(maxChunkContentSize));
        
        // Remove the following line if you don't want automatic content
        // compression.
        pipeline.addLast("deflater", new HttpContentCompressor());
        // Set up the idle handler
        pipeline.addLast("idle", new IdleStateHandler(nettyHttpServerEngine.getReadIdleTime(),
                nettyHttpServerEngine.getWriteIdleTime(), 0));

        return pipeline;
    }
 
源代码10 项目: Groza   文件: MqttTransportServerInitializer.java
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();//设置ChannelPipeLine
    SslHandler sslHandler = null;
    //判断SSL处理器处理类是否为空,如果不为空,将SSL处理器加入到ChannelPipeLine
    if (sslHandlerProvider != null) {
        sslHandler = sslHandlerProvider.getSslHandler();
        pipeline.addLast(sslHandler);
    }
    //添加负载内容的解编码器
    pipeline.addLast("decoder", new MqttDecoder(maxPayloadSize));
    pipeline.addLast("encoder", MqttEncoder.INSTANCE);

    MqttTransportHandler handler = new MqttTransportHandler(processor, deviceService, authService, relationService,
            adaptor, sslHandler, quotaService);

    //添加Mqtt协议处理器
    pipeline.addLast(handler);
    //异步操作完成时回调
    ch.closeFuture().addListener(handler);
}
 
源代码11 项目: xio   文件: MutualAuthHandler.java
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
  if (evt instanceof SslHandshakeCompletionEvent) {
    ctx.pipeline().remove(this);

    SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
    String peerIdentity = TlsAuthState.UNAUTHENTICATED;
    if (handshakeEvent.isSuccess()) {
      SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
      if (sslHandler == null) {
        throw new IllegalStateException(
            "cannot find a SslHandler in the pipeline (required for MutualAuthHandler)");
      }
      peerIdentity = getPeerIdentity(sslHandler.engine());
    }
    TlsAuthState.setPeerIdentity(ctx, peerIdentity);
    peerIdentityEstablished(ctx, peerIdentity);
  }

  ctx.fireUserEventTriggered(evt);
}
 
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {

    if (!(evt instanceof SslHandshakeCompletionEvent)) {
        super.userEventTriggered(ctx, evt);
        return;
    }

    final Channel channel = ctx.channel();
    final SslHandler sslHandler = (SslHandler) channel.pipeline().get(ChannelHandlerNames.SSL_HANDLER);
    final SSLSession session = sslHandler.engine().getSession();
    channel.attr(ChannelAttributes.AUTH_CIPHER_SUITE).set(session.getCipherSuite());
    channel.attr(ChannelAttributes.AUTH_PROTOCOL).set(session.getProtocol());

    channel.pipeline().remove(this);

    super.userEventTriggered(ctx, evt);
}
 
@Override
protected void addSpecialHandlers(@NotNull final Channel ch) throws SslException {

    final int handshakeTimeout = tlsTcpListener.getTls().getHandshakeTimeout();
    final IdleStateHandler idleStateHandler = new IdleStateHandler(handshakeTimeout, 0, 0, TimeUnit.MILLISECONDS);
    final NoTlsHandshakeIdleHandler noTlsHandshakeIdleHandler = new NoTlsHandshakeIdleHandler(eventLog);
    if (handshakeTimeout > 0) {
        ch.pipeline().addLast(NEW_CONNECTION_IDLE_HANDLER, idleStateHandler);
        ch.pipeline().addLast(NO_TLS_HANDSHAKE_IDLE_EVENT_HANDLER, noTlsHandshakeIdleHandler);
    }

    final Tls tls = tlsTcpListener.getTls();
    final SslHandler sslHandler = sslFactory.getSslHandler(ch, tls);
    sslHandler.handshakeFuture().addListener(future -> {
        if (handshakeTimeout > 0) {
            ch.pipeline().remove(idleStateHandler);
            ch.pipeline().remove(noTlsHandshakeIdleHandler);
        }
        addNoConnectIdleHandlerAfterTlsHandshake(ch);
    });

    new SslInitializer(sslHandler, tls, eventLog, sslParameterHandler).addHandlers(ch);
}
 
源代码14 项目: 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;
}
 
源代码15 项目: ambry   文件: PublicAccessLogHandlerTest.java
/**
 * Creates an {@link EmbeddedChannel} that incorporates an instance of {@link PublicAccessLogHandler}
 * and {@link EchoMethodHandler}.
 * @param useSSL {@code true} to add an {@link SslHandler} to the pipeline.
 * @return an {@link EmbeddedChannel} that incorporates an instance of {@link PublicAccessLogHandler}
 *         and {@link EchoMethodHandler}, and an {@link SslHandler} if needed.
 */
private EmbeddedChannel createChannel(boolean useSSL) {
  EmbeddedChannel channel = new EmbeddedChannel();
  if (useSSL) {
    SSLEngine sslEngine = SSL_CONTEXT.newEngine(channel.alloc());
    // HttpRequests pass through the SslHandler without a handshake (it only operates on ByteBuffers) so we have
    // to mock certain methods of SSLEngine and SSLSession to ensure that we can test certificate logging.
    SSLEngine mockSSLEngine =
        new MockSSLEngine(sslEngine, new MockSSLSession(sslEngine.getSession(), new Certificate[]{PEER_CERT}));
    channel.pipeline().addLast(new SslHandler(mockSSLEngine));
  }
  channel.pipeline()
      .addLast(new PublicAccessLogHandler(publicAccessLogger, new NettyMetrics(new MetricRegistry())))
      .addLast(new EchoMethodHandler());
  return channel;
}
 
源代码16 项目: azure-cosmosdb-java   文件: RntbdRequestManager.java
/**
 * Called once a close operation is made.
 *
 * @param context the {@link ChannelHandlerContext} for which the close operation is made
 * @param promise the {@link ChannelPromise} to notify once the operation completes
 */
@Override
public void close(final ChannelHandlerContext context, final ChannelPromise promise) {

    this.traceOperation(context, "close");

    if (!this.closingExceptionally) {
        this.completeAllPendingRequestsExceptionally(context, ON_CLOSE);
    } else {
        logger.debug("{} closed exceptionally", context);
    }

    final SslHandler sslHandler = context.pipeline().get(SslHandler.class);

    if (sslHandler != null) {
        // Netty 4.1.36.Final: SslHandler.closeOutbound must be called before closing the pipeline
        // This ensures that all SSL engine and ByteBuf resources are released
        // This is something that does not occur in the call to ChannelPipeline.close that follows
        sslHandler.closeOutbound();
    }

    context.close(promise);
}
 
源代码17 项目: hivemq-community-edition   文件: SslFactoryTest.java
@Test
public void test_cert_auth_none() throws Exception {
    final File file = testKeyStoreGenerator.generateKeyStore("teststore", "JKS", "passwd1", "passwd2");
    final String keystorePath = file.getAbsolutePath();

    final Tls tls = new Tls.Builder()
            .withKeystorePath(keystorePath)
            .withKeystoreType("JKS")
            .withKeystorePassword("passwd1")
            .withPrivateKeyPassword("passwd2")
            .withProtocols(new ArrayList<>())
            .withTruststorePath(keystorePath)
            .withTruststoreType("JKS")
            .withTruststorePassword("passwd1")
            .withClientAuthMode(Tls.ClientAuthMode.NONE)
            .withCipherSuites(new ArrayList<>())
            .withHandshakeTimeout(10000)
            .build();

    final SslHandler sslHandler = sslFactory.getSslHandler(socketChannel, tls);

    assertFalse(sslHandler.engine().getNeedClientAuth());
    assertFalse(sslHandler.engine().getWantClientAuth());
}
 
源代码18 项目: hivemq-community-edition   文件: SslFactoryTest.java
@Test
public void test_cert_auth_required() throws Exception {
    final File file = testKeyStoreGenerator.generateKeyStore("teststore", "JKS", "passwd1", "passwd2");
    final String keystorePath = file.getAbsolutePath();


    final Tls tls = new Tls.Builder()
            .withKeystorePath(keystorePath)
            .withKeystoreType("JKS")
            .withKeystorePassword("passwd1")
            .withPrivateKeyPassword("passwd2")
            .withProtocols(new ArrayList<>())
            .withTruststorePath(keystorePath)
            .withTruststoreType("JKS")
            .withTruststorePassword("passwd1")
            .withClientAuthMode(Tls.ClientAuthMode.REQUIRED)
            .withCipherSuites(new ArrayList<>())
            .withHandshakeTimeout(10000)
            .build();


    final SslHandler sslHandler = sslFactory.getSslHandler(socketChannel, tls);

    assertTrue(sslHandler.engine().getNeedClientAuth());
    assertFalse(sslHandler.engine().getWantClientAuth());
}
 
源代码19 项目: ambry   文件: NettyClient.java
/**
 * Create a NettyClient.
 * @param hostname the host to connect to.
 * @param port the port to connect to.
 * @param sslFactory the {@link SSLFactory} to use if SSL is enabled.
 */
public NettyClient(final String hostname, final int port, final SSLFactory sslFactory) throws InterruptedException {
  this.hostname = hostname;
  this.port = port;
  b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
      ChannelPipeline pipeline = ch.pipeline();
      if (sslFactory != null) {
        pipeline.addLast("sslHandler",
            new SslHandler(sslFactory.createSSLEngine(hostname, port, SSLFactory.Mode.CLIENT)));
      }
      pipeline.addLast(new HttpClientCodec()).addLast(new ChunkedWriteHandler()).addLast(communicationHandler);
    }
  });
  createChannel();
}
 
源代码20 项目: arcusplatform   文件: HttpRequestInitializer.java
@Override
protected void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   pipeline.addLast(inboundIpTracking);

   if (serverTlsContext != null && serverTlsContext.useTls()) {
      SSLEngine engine = serverTlsContext.getContext().newEngine(ch.alloc());
      engine.setNeedClientAuth(serverConfig.isTlsNeedClientAuth());
      engine.setUseClientMode(false);
      pipeline.addLast(FILTER_SSL, new SslHandler(engine));
   }

   pipeline.addLast(FILTER_CODEC, new HttpServerCodec());
   pipeline.addLast(FILTER_HTTP_AGGREGATOR, new HttpObjectAggregator(65536));
   pipeline.addLast("bind-client-context", oauthBindClientContext);
   pipeline.addLast(FILTER_HANDLER, handlerProvider.get());
   pipeline.addLast(outboundIpTracking);
}
 
源代码21 项目: 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());
            }
         }
      });
   }
}
 
源代码22 项目: pulsar   文件: ServiceChannelInitializer.java
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    if (sslCtxRefresher != null && this.enableTls) {
        if (this.tlsEnabledWithKeyStore) {
            ch.pipeline().addLast(TLS_HANDLER,
                    new SslHandler(nettySSLContextAutoRefreshBuilder.get().createSSLEngine()));
        } else{
            SslContext sslContext = sslCtxRefresher.get();
            if (sslContext != null) {
                ch.pipeline().addLast(TLS_HANDLER, sslContext.newHandler(ch.alloc()));
            }
        }
    }
    ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(
        Commands.DEFAULT_MAX_MESSAGE_SIZE + Commands.MESSAGE_SIZE_FRAME_PADDING, 0, 4, 0, 4));
    ch.pipeline().addLast("handler", new ServerConnection(discoveryService));
}
 
源代码23 项目: arcusplatform   文件: SslBindClientHandler.java
private void onSslHandshakeComplete(Future<? super Channel> result, SslHandler handler) {
   try {
      if(!result.isSuccess()) {
         if (logger.isDebugEnabled()) {
            Throwable cause = result.cause();
            if (!(cause instanceof ClosedChannelException)) {
               logger.debug("SSL handshake failed: {}", (cause == null) ? "unknown" : cause.getMessage(), cause);
            }
         }
         return;
      }

      String clientName = extractClientName(handler);
      if(clientName != null) {
         Channel channel = (Channel) result.get();
         Client.bind(channel, registry.load(clientName));
      }
   }
   catch(Exception e) {
      logger.debug("Unable to determine client auth", e);
   }
}
 
源代码24 项目: reactor-netty   文件: HttpClientConfig.java
@Override
public void channelActive(ChannelHandlerContext ctx) {
	SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
	if (sslHandler == null) {
		throw new IllegalStateException("Cannot determine negotiated application-level protocol.");
	}
	String protocol = sslHandler.applicationProtocol() != null ? sslHandler.applicationProtocol() : ApplicationProtocolNames.HTTP_1_1;
	if (log.isDebugEnabled()) {
		log.debug(format(ctx.channel(), "Negotiated application-level protocol [" + protocol + "]"));
	}
	if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
		configureHttp2Pipeline(ctx.channel().pipeline(), decoder, http2Settings, observer);
	}
	else if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
		configureHttp11Pipeline(ctx.channel().pipeline(), acceptGzip, decoder, metricsRecorder, uriTagValue);
	}
	else {
		throw new IllegalStateException("unknown protocol: " + protocol);
	}

	ctx.fireChannelActive();

	ctx.channel().pipeline().remove(this);
}
 
源代码25 项目: cxf   文件: NettyHttpClientPipelineFactory.java
@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

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


    pipeline.addLast("decoder", new HttpResponseDecoder());
    // TODO need to configure the aggregator size
    pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
    pipeline.addLast("encoder", new HttpRequestEncoder());
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    if (readTimeout > 0) {
        pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS));
    }
    pipeline.addLast("client", new NettyHttpClientHandler());
}
 
源代码26 项目: netty-4.1.22   文件: OcspServerExample.java
private static ChannelInitializer<Channel> newServerHandler(final ReferenceCountedOpenSslContext context,
        final OCSPResp response) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine
                    = (ReferenceCountedOpenSslEngine) sslHandler.engine();

                engine.setOcspResponse(response.getEncoded());
            }

            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(sslHandler);

            // so on and so forth...
        }
    };
}
 
@Test
public void sslContextProvided_andProxyUsingHttps_addsSslHandler() {
    SslHandler mockSslHandler = mock(SslHandler.class);
    TestSslContext mockSslCtx = new TestSslContext(mockSslHandler);

    Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, remoteAddr, initFuture) -> {
        initFuture.setSuccess(mockChannel);
        return mock(ChannelHandler.class);
    };

    Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx,
            HTTPS_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, supplier);

    tunnelPool.acquire().awaitUninterruptibly();

    ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(mockPipeline, times(2)).addLast(handlersCaptor.capture());

    assertThat(handlersCaptor.getAllValues().get(0)).isEqualTo(mockSslHandler);
}
 
源代码28 项目: julongchain   文件: SecureChatServerHandler.java
@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // 一旦session处于安全状态, 发送一个标记将但前channel注册到全局channel列表
    // 可以接收其他channel的消息.
    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());
                }
    });
}
 
源代码29 项目: cxf   文件: NettyHttpServletRequest.java
public NettyHttpServletRequest(HttpRequest request, String contextPath, ChannelHandlerContext ctx) {
    this.originalRequest = request;
    this.contextPath = contextPath;
    this.uriParser = new URIParser(contextPath);
    uriParser.parse(request.uri());
    this.inputStream = new NettyServletInputStream((HttpContent)request);
    this.reader = new BufferedReader(new InputStreamReader(inputStream));
    this.queryStringDecoder = new QueryStringDecoder(request.uri());
    // setup the SSL security attributes
    this.channelHandlerContext = ctx;
    SslHandler sslHandler = channelHandlerContext.pipeline().get(SslHandler.class);
    if (sslHandler != null) {
        SSLSession session = sslHandler.engine().getSession();
        if (session != null) {
            attributes.put(SSL_CIPHER_SUITE_ATTRIBUTE, session.getCipherSuite());
            try {
                attributes.put(SSL_PEER_CERT_CHAIN_ATTRIBUTE, session.getPeerCertificates());
            } catch (SSLPeerUnverifiedException ex) {
                // do nothing here
            }
        }
    }
}
 
源代码30 项目: netty-4.1.22   文件: OcspTest.java
private static ChannelHandler newServerHandler(final SslContext context,
        final byte[] response, final ChannelHandler handler) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
                engine.setOcspResponse(response);
            }

            pipeline.addLast(sslHandler);

            if (handler != null) {
                pipeline.addLast(handler);
            }
        }
    };
}