io.netty.handler.ssl.ApplicationProtocolNames Java Examples

The following examples show how to use io.netty.handler.ssl.ApplicationProtocolNames. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Http2OrHttpHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.pipeline().addLast(Http2MultiplexCodecBuilder.forServer(new HelloWorldHttp2Handler()).build());
        return;
    }

    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        ctx.pipeline().addLast(new HttpServerCodec(),
                               new HttpObjectAggregator(MAX_CONTENT_LENGTH),
                               new HelloWorldHttp1Handler("ALPN Negotiation"));
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}
 
Example #2
Source File: HttpClientConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: ServerSSLContextManager.java    From cute-proxy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private SslContext getNettySslContextInner(String host, boolean useH2) throws Exception {
        long start = System.currentTimeMillis();
        PrivateKeyAndCertChain keyAndCertChain = keyStoreGenerator.generateCertChain(host, Settings.certValidityDays);
        logger.debug("Create certificate for {}, cost {} ms", host, System.currentTimeMillis() - start);
        SslContextBuilder builder = SslContextBuilder
                .forServer(keyAndCertChain.privateKey(), keyAndCertChain.certificateChain());
        if (useH2) {
//                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            builder.applicationProtocolConfig(new ApplicationProtocolConfig(
                    ApplicationProtocolConfig.Protocol.ALPN,
                    SelectorFailureBehavior.NO_ADVERTISE,
                    SelectedListenerFailureBehavior.ACCEPT,
                    ApplicationProtocolNames.HTTP_2,
                    ApplicationProtocolNames.HTTP_1_1));
        }
        return builder.build();
    }
 
Example #4
Source File: Http2ConnectionProvider.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
boolean notHttp2() {
	Channel channel = pooledRef.poolable().channel();
	SslHandler handler = channel.pipeline().get(SslHandler.class);
	if (handler != null) {
		String protocol = handler.applicationProtocol() != null ? handler.applicationProtocol() : ApplicationProtocolNames.HTTP_1_1;
		if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
			// No information for the negotiated application-level protocol
			// or it is HTTP/1.1, continue as an HTTP/1.1 request
			// and remove the connection from this pool.
			ChannelOperations<?, ?> ops = ChannelOperations.get(channel);
			if (ops != null) {
				sink.success(ops);
				invalidate(this, channel);
				return true;
			}
		}
		else if (!ApplicationProtocolNames.HTTP_2.equals(handler.applicationProtocol())) {
			channel.attr(OWNER).set(null);
			invalidate(this, channel);
			sink.error(new IOException("Unknown protocol [" + protocol + "]."));
			return true;
		}
	}
	return false;
}
 
Example #5
Source File: Http2ConnectionProvider.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
Publisher<Connection> connectChannel() {
	return parent.acquire(config, new DelegatingConnectionObserver(), remoteAddress, resolver)
		         .map(conn -> {
		             if (log.isDebugEnabled()) {
		                 log.debug(format(conn.channel(), "Channel acquired from the parent pool, " +
		                                 "now {} active connections and {} inactive connections"),
		                         pool.metrics().acquiredSize(),
		                         pool.metrics().idleSize());
		             }

		             SslHandler handler = conn.channel().pipeline().get(SslHandler.class);
		             if (handler != null) {
		                 String protocol = handler.applicationProtocol() != null ? handler.applicationProtocol() : ApplicationProtocolNames.HTTP_1_1;
		                 if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
		                     if (allocationStrategy.compareAndSet(initialMaxConnection, Integer.MAX_VALUE)) {
		                         if (log.isDebugEnabled()) {
		                             log.debug(format(conn.channel(), "Negotiated protocol HTTP/1.1, " +
		                                     "upgrade the max connections to Integer.MAX_VALUE"));
		                         }
		                     }
		                 }
		             }

		             return conn;
		         });
}
 
Example #6
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
H2OrHttp11Codec(
		@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
		ServerCookieDecoder cookieDecoder,
		ServerCookieEncoder cookieEncoder,
		HttpRequestDecoderSpec decoder,
		boolean forwarded,
		Http2Settings http2Settings,
		ConnectionObserver listener,
		@Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder,
		int minCompressionSize,
		ChannelOperations.OnSetup opsFactory,
		@Nullable Function<String, String> uriTagValue) {
	super(ApplicationProtocolNames.HTTP_1_1);
	this.compressPredicate = compressPredicate;
	this.cookieDecoder = cookieDecoder;
	this.cookieEncoder = cookieEncoder;
	this.decoder = decoder;
	this.forwarded = forwarded;
	this.http2Settings = http2Settings;
	this.listener = listener;
	this.metricsRecorder = metricsRecorder;
	this.minCompressionSize = minCompressionSize;
	this.opsFactory = opsFactory;
	this.uriTagValue = uriTagValue;
}
 
Example #7
Source File: TlsUtil.java    From nitmproxy with MIT License 6 votes vote down vote up
private static ApplicationProtocolConfig applicationProtocolConfig(NitmProxyConfig config, boolean http2) {
    if (http2) {
        return new ApplicationProtocolConfig(
                Protocol.ALPN,
                SelectorFailureBehavior.NO_ADVERTISE,
                SelectedListenerFailureBehavior.ACCEPT,
                ApplicationProtocolNames.HTTP_2,
                ApplicationProtocolNames.HTTP_1_1);
    } else {
        return new ApplicationProtocolConfig(
                Protocol.ALPN,
                SelectorFailureBehavior.NO_ADVERTISE,
                SelectedListenerFailureBehavior.ACCEPT,
                ApplicationProtocolNames.HTTP_1_1);
    }
}
 
Example #8
Source File: HttpServerConfig.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
	if (log.isDebugEnabled()) {
		log.debug(format(ctx.channel(), "Negotiated application-level protocol [" + protocol + "]"));
	}

	ChannelPipeline p = ctx.pipeline();

	if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
		configureH2Pipeline(p, cookieDecoder, cookieEncoder, forwarded, http2Settings,
				listener, opsFactory, decoder.validateHeaders());
		return;
	}

	if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
		configureHttp11Pipeline(p, compressPredicate, cookieDecoder, cookieEncoder, decoder, forwarded,
				listener, metricsRecorder, minCompressionSize, uriTagValue);
		return;
	}

	throw new IllegalStateException("unknown protocol: " + protocol);
}
 
Example #9
Source File: Http2ServerChannelInitializer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Configure the pipeline for TLS NPN negotiation to HTTP/2.
 */
private void configureSSL(SocketChannel ch) {
    final ChannelPipeline p = ch.pipeline();
    // 先通过 SSL/TLS 协商版本
    p.addLast(sslCtx.newHandler(ch.alloc()));
    // 根据版本加载不同的 ChannelHandler
    p.addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {
        @Override
        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                ctx.pipeline().addLast(bizGroup, "Http2ChannelHandler",
                    new Http2ChannelHandlerBuilder(serverHandler).build());
                return;
            }

            if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
                ctx.pipeline().addLast("HttpServerCodec", new HttpServerCodec());
                ctx.pipeline().addLast("HttpObjectAggregator", new HttpObjectAggregator(maxHttpContentLength));
                ctx.pipeline().addLast(bizGroup, "Http1ChannelHandler",
                    new Http1ServerChannelHandler(serverHandler));
                return;
            }

            throw new IllegalStateException("unknown protocol: " + protocol);
        }
    });
}
 
Example #10
Source File: Http2ClientInitializer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Configure the pipeline for TLS NPN negotiation to HTTP/2.
 */
private void configureSsl(SocketChannel ch) {
    SslContext sslCtx = SslContextBuilder.buildForClient();
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    // We must wait for the handshake to finish and the protocol to be negotiated
    // before configuring
    // the HTTP/2 components of the pipeline.
    pipeline.addLast(new ApplicationProtocolNegotiationHandler("") {
        @Override
        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                ChannelPipeline p = ctx.pipeline();
                p.addLast(connectionHandler);
                configureEndOfPipeline(p);
                return;
            }
            ctx.close();
            throw new IllegalStateException("unknown protocol: " + protocol);
        }
    });
}
 
Example #11
Source File: Http2OrHttpHandler.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.pipeline().addLast(new Http2HandlerBuilder().build());
        return;
    }

    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        ctx.pipeline().addLast(new HttpServerCodec(),
                new HttpObjectAggregator(MAX_CONTENT_LENGTH),
                new Http1Handler("ALPN Negotiation"));
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}
 
Example #12
Source File: NettyHttp2Client.java    From jmeter-http2-plugin with Apache License 2.0 6 votes vote down vote up
private SslContext getSslContext() {
    SslContext sslCtx = null;

    final SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;

    try {
        sslCtx = SslContextBuilder.forClient()
            .sslProvider(provider)
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(
                Protocol.ALPN,
                SelectorFailureBehavior.NO_ADVERTISE,
                SelectedListenerFailureBehavior.ACCEPT,
                ApplicationProtocolNames.HTTP_2))
            .build();
    } catch(SSLException exception) {
        return null;
    }

    return sslCtx;
}
 
Example #13
Source File: Http2ClientInitializer.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Configure the pipeline for TLS NPN negotiation to HTTP/2.
 */
private void configureSsl(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    // We must wait for the handshake to finish and the protocol to be negotiated before configuring
    // the HTTP/2 components of the pipeline.
    pipeline.addLast(new ApplicationProtocolNegotiationHandler("") {
        @Override
        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                ChannelPipeline p = ctx.pipeline();
                p.addLast(connectionHandler);
                configureEndOfPipeline(p);
                return;
            }
            ctx.close();
            throw new IllegalStateException("unknown protocol: " + protocol);
        }
    });
}
 
Example #14
Source File: Http2Util.java    From tutorials with MIT License 6 votes vote down vote up
public static ApplicationProtocolNegotiationHandler getServerAPNHandler() {
    ApplicationProtocolNegotiationHandler serverAPNHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) {

        @Override
        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                ctx.pipeline()
                    .addLast(Http2FrameCodecBuilder.forServer()
                        .build(), new Http2ServerResponseHandler());
                return;
            }
            throw new IllegalStateException("Protocol: " + protocol + " not supported");
        }
    };
    return serverAPNHandler;

}
 
Example #15
Source File: Http2OrHttpHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.pipeline().addLast(Http2FrameCodecBuilder.forServer().build(), new HelloWorldHttp2Handler());
        return;
    }

    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        ctx.pipeline().addLast(new HttpServerCodec(),
                               new HttpObjectAggregator(MAX_CONTENT_LENGTH),
                               new HelloWorldHttp1Handler("ALPN Negotiation"));
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}
 
Example #16
Source File: NettySslHttp2Factory.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * @param config the {@link SSLConfig}
 * @return a configured {@link SslContext} object for a client.
 * @throws GeneralSecurityException
 * @throws IOException
 */
static SslContext getServerSslContext(SSLConfig config) throws GeneralSecurityException, IOException {
  logger.info("Using {} provider for server SslContext", SslContext.defaultServerProvider());
  SslContextBuilder sslContextBuilder;
  if (config.sslHttp2SelfSign) {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    sslContextBuilder = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
    logger.info("Using Self Signed Certificate.");
  } else {
    sslContextBuilder = SslContextBuilder.forServer(NettySslFactory.getKeyManagerFactory(config))
        .trustManager(NettySslFactory.getTrustManagerFactory(config));
  }
  return sslContextBuilder.sslProvider(SslContext.defaultClientProvider())
      .clientAuth(NettySslFactory.getClientAuth(config))
      /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
       * Please refer to the HTTP/2 specification for cipher requirements. */
      .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
      .applicationProtocolConfig(new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
          // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
          ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
          // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
          ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2))
      .build();
}
 
Example #17
Source File: NettySslHttp2Factory.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * @param config the {@link SSLConfig}
 * @return a configured {@link SslContext} object for a server.
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static SslContext getClientSslContext(SSLConfig config) throws GeneralSecurityException, IOException {
  logger.info("Using {} provider for client ", SslContext.defaultClientProvider());
  SslContextBuilder sslContextBuilder;
  if (config.sslHttp2SelfSign) {
    sslContextBuilder = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE);
    logger.info("Using Self Signed Certificate.");
  } else {
    sslContextBuilder = SslContextBuilder.forClient()
        .keyManager(NettySslFactory.getKeyManagerFactory(config))
        .trustManager(NettySslFactory.getTrustManagerFactory(config));
  }
  return sslContextBuilder.sslProvider(SslContext.defaultClientProvider())
      /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
       * Please refer to the HTTP/2 specification for cipher requirements. */
      .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
      .applicationProtocolConfig(new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
          // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
          ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
          // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
          ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2))
      .build();
}
 
Example #18
Source File: Http2OrHttpHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.pipeline().addLast(new HelloWorldHttp2HandlerBuilder().build());
        return;
    }

    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        ctx.pipeline().addLast(new HttpServerCodec(),
                               new HttpObjectAggregator(MAX_CONTENT_LENGTH),
                               new HelloWorldHttp1Handler("ALPN Negotiation"));
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}
 
Example #19
Source File: Http2ClientInitializer.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Configure the pipeline for TLS NPN negotiation to HTTP/2.
 */
private void configureSsl(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    // We must wait for the handshake to finish and the protocol to be negotiated before configuring
    // the HTTP/2 components of the pipeline.
    pipeline.addLast(new ApplicationProtocolNegotiationHandler("") {
        @Override
        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                ChannelPipeline p = ctx.pipeline();
                p.addLast(connectionHandler);
                configureEndOfPipeline(p);
                return;
            }
            ctx.close();
            throw new IllegalStateException("unknown protocol: " + protocol);
        }
    });
}
 
Example #20
Source File: VerificationHost_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
    // we create a random userAgent string to validate host to host communication when
    // the client appears to be from an external, non-Xenon source.
    ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
            null,
            h.getScheduledExecutor(), h);

    if (NettyChannelContext.isALPNEnabled()) {
        SslContext http2ClientContext = SslContextBuilder.forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(
                        ApplicationProtocolConfig.Protocol.ALPN,
                        ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                        ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                        ApplicationProtocolNames.HTTP_2))
                .build();
        ((NettyHttpServiceClient) client).setHttp2SslContext(http2ClientContext);
    }

    SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
    clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
    client.setSSLContext(clientContext);
    h.setClient(client);

    SelfSignedCertificate ssc = new SelfSignedCertificate();
    h.setCertificateFileReference(ssc.certificate().toURI());
    h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
 
Example #21
Source File: HttpNegotiationHandler.java    From xio with Apache License 2.0 5 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
  if (protocol.equals(ApplicationProtocolNames.HTTP_1_1)) {
    replaceCodec(ctx, new HttpServerCodec());
    replaceApplicationCodec(ctx, new Http1ServerCodec());
  } else if (protocol.equals(ApplicationProtocolNames.HTTP_2)) {
    replaceCodec(ctx, http2Handler.get());
    replaceApplicationCodec(ctx, new Http2ServerCodec());
  } else {
    throw new RuntimeException("Unknown Application Protocol '" + protocol + "'");
  }
}
 
Example #22
Source File: HttpClientNegotiationHandler.java    From xio with Apache License 2.0 5 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
  if (protocol.equals(ApplicationProtocolNames.HTTP_1_1)) {
    replaceCodec(ctx, new HttpClientCodec());
    replaceApplicationCodec(ctx, new Http1ClientCodec());
    ctx.fireUserEventTriggered(RequestBuffer.WriteReady.INSTANCE);
  } else if (protocol.equals(ApplicationProtocolNames.HTTP_2)) {
    replaceCodec(ctx, http2Handler.get());
    replaceApplicationCodec(ctx, new Http2ClientCodec());
  } else {
    throw new RuntimeException("Unknown Application Protocol '" + protocol + "'");
  }
}
 
Example #23
Source File: HttpServerPipelineConfigurator.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        addHttp2Handlers(ctx);
        return;
    }

    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        addHttpHandlers(ctx);
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}
 
Example #24
Source File: VerificationHost_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
    // we create a random userAgent string to validate host to host communication when
    // the client appears to be from an external, non-Xenon source.
    ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
            null,
            h.getScheduledExecutor(), h);

    if (NettyChannelContext.isALPNEnabled()) {
        SslContext http2ClientContext = SslContextBuilder.forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(
                        ApplicationProtocolConfig.Protocol.ALPN,
                        ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                        ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                        ApplicationProtocolNames.HTTP_2))
                .build();
        ((NettyHttpServiceClient) client).setHttp2SslContext(http2ClientContext);
    }

    SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
    clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
    client.setSSLContext(clientContext);
    h.setClient(client);

    SelfSignedCertificate ssc = new SelfSignedCertificate();
    h.setCertificateFileReference(ssc.certificate().toURI());
    h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
 
Example #25
Source File: Http2Util.java    From tutorials with MIT License 5 votes vote down vote up
public static SslContext createSSLContext(boolean isServer) throws SSLException, CertificateException {

        SslContext sslCtx;

        SelfSignedCertificate ssc = new SelfSignedCertificate();

        if (isServer) {
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
                .sslProvider(SslProvider.JDK)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                    SelectorFailureBehavior.NO_ADVERTISE,
                    SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
                .build();
        } else {
            sslCtx = SslContextBuilder.forClient()
                .sslProvider(SslProvider.JDK)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                    SelectorFailureBehavior.NO_ADVERTISE,
                    SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2))
                .build();
        }
        return sslCtx;

    }
 
Example #26
Source File: Http2Util.java    From tutorials with MIT License 5 votes vote down vote up
public static ApplicationProtocolNegotiationHandler getClientAPNHandler(int maxContentLength, Http2SettingsHandler settingsHandler, Http2ClientResponseHandler responseHandler) {
    final Http2FrameLogger logger = new Http2FrameLogger(INFO, Http2Util.class);
    final Http2Connection connection = new DefaultHttp2Connection(false);

    HttpToHttp2ConnectionHandler connectionHandler = new HttpToHttp2ConnectionHandlerBuilder()
        .frameListener(new DelegatingDecompressorFrameListener(connection, new InboundHttp2ToHttpAdapterBuilder(connection).maxContentLength(maxContentLength)
        .propagateSettings(true)
        .build()))
        .frameLogger(logger)
        .connection(connection)
        .build();

    ApplicationProtocolNegotiationHandler clientAPNHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) {
        @Override
        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                ChannelPipeline p = ctx.pipeline();
                p.addLast(connectionHandler);
                p.addLast(settingsHandler, responseHandler);
                return;
            }
            ctx.close();
            throw new IllegalStateException("Protocol: " + protocol + " not supported");
        }
    };

    return clientAPNHandler;

}
 
Example #27
Source File: Http2OrHttpHandler.java    From zuul with Apache License 2.0 5 votes vote down vote up
public Http2OrHttpHandler(ChannelHandler http2StreamHandler, ChannelConfig channelConfig,
                          Consumer<ChannelPipeline> addHttpHandlerFn) {
    super(ApplicationProtocolNames.HTTP_1_1);
    this.http2StreamHandler = http2StreamHandler;
    this.maxConcurrentStreams = channelConfig.get(CommonChannelConfigKeys.maxConcurrentStreams);
    this.initialWindowSize = channelConfig.get(CommonChannelConfigKeys.initialWindowSize);
    this.maxHeaderTableSize = channelConfig.get(CommonChannelConfigKeys.maxHttp2HeaderTableSize);
    this.maxHeaderListSize = channelConfig.get(CommonChannelConfigKeys.maxHttp2HeaderListSize);
    this.addHttpHandlerFn = addHttpHandlerFn;
}
 
Example #28
Source File: Http2OrHttpHandler.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
    if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
        ctx.channel().attr(PROTOCOL_NAME).set("HTTP/2");
        configureHttp2(ctx.pipeline());
        return;
    }
    if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
        ctx.channel().attr(PROTOCOL_NAME).set("HTTP/1.1");
        configureHttp1(ctx.pipeline());
        return;
    }

    throw new IllegalStateException("unknown protocol: " + protocol);
}
 
Example #29
Source File: Http2Configuration.java    From zuul with Apache License 2.0 5 votes vote down vote up
public static SslContext configureSSL(SslContextFactory sslContextFactory, String metricId) {
    SslContextBuilder builder = sslContextFactory.createBuilderForServer();

    String[] supportedProtocol;
    if (HTTP2_DISABLED.get()) {
        supportedProtocol = new String[]{ApplicationProtocolNames.HTTP_1_1};
    }
    else {
        supportedProtocol = new String[]{ApplicationProtocolNames.HTTP_2,
                ApplicationProtocolNames.HTTP_1_1};
    }

    ApplicationProtocolConfig apn = new ApplicationProtocolConfig(
            ApplicationProtocolConfig.Protocol.ALPN,
            // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
            ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
            // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
            ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
            supportedProtocol);

    final SslContext sslContext;
    try {
        sslContext = builder
                .applicationProtocolConfig(apn)
                .build();
    }
    catch (SSLException e) {
        throw new RuntimeException("Error configuring SslContext with ALPN!", e);
    }

    // Enable TLS Session Tickets support.
    sslContextFactory.enableSessionTickets(sslContext);

    // Setup metrics tracking the OpenSSL stats.
    sslContextFactory.configureOpenSslStatsMetrics(sslContext, metricId);

    return sslContext;
}
 
Example #30
Source File: ClientSSLContextManager.java    From cute-proxy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static SslContext createNettyClientSSlContext() {
    try {
        return SslContextBuilder.forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(
                        ApplicationProtocolConfig.Protocol.ALPN,
                        SelectorFailureBehavior.NO_ADVERTISE,
                        SelectedListenerFailureBehavior.ACCEPT,
                        ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } catch (SSLException e) {
        throw new SSLContextException(e);
    }
}