Example usage for io.netty.handler.ssl ApplicationProtocolConfig selectorFailureBehavior

List of usage examples for io.netty.handler.ssl ApplicationProtocolConfig selectorFailureBehavior

Introduction

In this page you can find the example usage for io.netty.handler.ssl ApplicationProtocolConfig selectorFailureBehavior.

Prototype

public SelectorFailureBehavior selectorFailureBehavior() 

Source Link

Document

Get the desired behavior for the peer who selects the application protocol.

Usage

From source file:com.linecorp.armeria.client.http.HttpClientPipelineConfigurator.java

License:Apache License

HttpClientPipelineConfigurator(SessionProtocol sessionProtocol, SessionOptions options) {
    switch (sessionProtocol) {
    case HTTP:/*from   ww  w.j  a v  a2s . c o m*/
    case HTTPS:
        httpPreference = HttpPreference.HTTP2_PREFERRED;
        break;
    case H1:
    case H1C:
        httpPreference = HttpPreference.HTTP1_REQUIRED;
        break;
    case H2:
    case H2C:
        httpPreference = HttpPreference.HTTP2_REQUIRED;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    this.options = requireNonNull(options, "options");

    if (sessionProtocol.isTls()) {
        try {
            final SslContextBuilder builder = SslContextBuilder.forClient();

            builder.sslProvider(NativeLibraries.isOpenSslAvailable() ? SslProvider.OPENSSL : SslProvider.JDK);
            options.trustManagerFactory().ifPresent(builder::trustManager);

            if (httpPreference == HttpPreference.HTTP2_REQUIRED
                    || httpPreference == HttpPreference.HTTP2_PREFERRED) {

                builder.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));
            }
            sslCtx = builder.build();
        } catch (SSLException e) {
            throw new IllegalStateException("failed to create an SslContext", e);
        }
    } else {
        sslCtx = null;
    }
}

From source file:com.linecorp.armeria.client.HttpClientPipelineConfigurator.java

License:Apache License

HttpClientPipelineConfigurator(HttpClientFactory clientFactory, SessionProtocol sessionProtocol) {
    this.clientFactory = clientFactory;

    if (sessionProtocol == HTTP || sessionProtocol == HTTPS) {
        httpPreference = HttpPreference.HTTP2_PREFERRED;
    } else if (sessionProtocol == H1 || sessionProtocol == H1C) {
        httpPreference = HttpPreference.HTTP1_REQUIRED;
    } else if (sessionProtocol == H2 || sessionProtocol == H2C) {
        httpPreference = HttpPreference.HTTP2_REQUIRED;
    } else {/*www  .j  a va2 s  .  co  m*/
        // Should never reach here.
        throw new Error();
    }

    if (sessionProtocol.isTls()) {
        try {
            final SslContextBuilder builder = SslContextBuilder.forClient();

            builder.sslProvider(Flags.useOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK);
            clientFactory.sslContextCustomizer().accept(builder);

            if (httpPreference == HttpPreference.HTTP2_REQUIRED
                    || httpPreference == HttpPreference.HTTP2_PREFERRED) {

                builder.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));
            }
            sslCtx = builder.build();
        } catch (SSLException e) {
            throw new IllegalStateException("failed to create an SslContext", e);
        }
    } else {
        sslCtx = null;
    }
}

From source file:com.linecorp.armeria.client.HttpConfigurator.java

License:Apache License

HttpConfigurator(SessionProtocol sessionProtocol, RemoteInvokerOptions options) {
    switch (sessionProtocol) {
    case HTTP:/*from www .  ja  v a2  s  .com*/
    case HTTPS:
        httpPreference = HttpPreference.HTTP2_PREFERRED;
        break;
    case H1:
    case H1C:
        httpPreference = HttpPreference.HTTP1_REQUIRED;
        break;
    case H2:
    case H2C:
        httpPreference = HttpPreference.HTTP2_REQUIRED;
        break;
    default:
        // Should never reach here.
        throw new Error();
    }

    this.options = requireNonNull(options, "options");

    if (sessionProtocol.isTls()) {
        try {
            final SslContextBuilder builder = SslContextBuilder.forClient();

            builder.sslProvider(NativeLibraries.isOpenSslAvailable() ? SslProvider.OPENSSL : SslProvider.JDK);
            options.trustManagerFactory().ifPresent(builder::trustManager);

            if (httpPreference == HttpPreference.HTTP2_REQUIRED
                    || httpPreference == HttpPreference.HTTP2_PREFERRED) {

                builder.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));
            }
            sslCtx = builder.build();
        } catch (SSLException e) {
            throw new IllegalStateException("failed to create a SslContext", e);
        }
    } else {
        sslCtx = null;
    }
}

From source file:com.linkedin.r2.transport.http.client.Http2InitializerHandler.java

License:Apache License

/**
 * Sets up HTTP/2 over TLS through ALPN (h2) pipeline
 *//*from   w w  w .  ja v  a  2s.c o m*/
private void configureHttpsPipeline(ChannelHandlerContext ctx) throws Exception {
    JdkSslContext context = new JdkSslContext(_sslContext, IS_CLIENT,
            Arrays.asList(_sslParameters.getCipherSuites()), IdentityCipherSuiteFilter.INSTANCE,
            new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1),
            _sslParameters.getNeedClientAuth() ? ClientAuth.REQUIRE : ClientAuth.OPTIONAL);
    SslHandler sslHandler = context.newHandler(ctx.alloc());

    Http2StreamCodec http2Codec = new Http2StreamCodecBuilder().connection(_connection)
            .maxContentLength(_maxResponseSize).maxHeaderSize(_maxHeaderSize)
            .gracefulShutdownTimeoutMillis(_gracefulShutdownTimeout).streamingTimeout(_streamingTimeout)
            .scheduler(_scheduler).build();

    Http2AlpnHandler alpnHandler = new Http2AlpnHandler(sslHandler, http2Codec);
    Http2SchemeHandler schemeHandler = new Http2SchemeHandler(HttpScheme.HTTPS.toString());
    Http2StreamResponseHandler responseHandler = new Http2StreamResponseHandler();
    Http2ChannelPoolHandler channelPoolHandler = new Http2ChannelPoolHandler();

    ctx.pipeline().addBefore(ctx.name(), "alpnHandler", alpnHandler);
    ctx.pipeline().addBefore(ctx.name(), "schemeHandler", schemeHandler);
    ctx.pipeline().addBefore(ctx.name(), "responseHandler", responseHandler);
    ctx.pipeline().addBefore(ctx.name(), "channelHandler", channelPoolHandler);

    _setupComplete = true;
}

From source file:com.turo.pushy.apns.BenchmarkApnsServer.java

License:Open Source License

public BenchmarkApnsServer(final InputStream certificateChainInputStream,
        final InputStream privateKeyPkcs8InputStream, final NioEventLoopGroup eventLoopGroup)
        throws SSLException {
    final SslContext sslContext;
    {/*  w w w.j  av  a2  s. c  om*/
        final SslProvider sslProvider;

        if (OpenSsl.isAvailable()) {
            if (OpenSsl.isAlpnSupported()) {
                sslProvider = SslProvider.OPENSSL;
            } else {
                sslProvider = SslProvider.JDK;
            }
        } else {
            sslProvider = SslProvider.JDK;
        }

        sslContext = SslContextBuilder.forServer(certificateChainInputStream, privateKeyPkcs8InputStream, null)
                .sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL)
                .applicationProtocolConfig(
                        new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                ApplicationProtocolNames.HTTP_2))
                .build();
    }

    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(eventLoopGroup);

    this.bootstrap.channel(NioServerSocketChannel.class);
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());
            channel.pipeline().addLast(sslHandler);
            channel.pipeline()
                    .addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {

                        @Override
                        protected void configurePipeline(final ChannelHandlerContext context,
                                final String protocol) throws Exception {
                            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                                context.pipeline().addLast(
                                        new BenchmarkApnsServerHandler.BenchmarkApnsServerHandlerBuilder()
                                                .initialSettings(new Http2Settings()
                                                        .maxConcurrentStreams(MAX_CONCURRENT_STREAMS))
                                                .build());

                                BenchmarkApnsServer.this.allChannels.add(context.channel());
                            } else {
                                throw new IllegalStateException("Unexpected protocol: " + protocol);
                            }
                        }
                    });
        }
    });
}

From source file:com.turo.pushy.apns.server.BaseHttp2ServerBuilder.java

License:Open Source License

/**
 * Constructs a new server with the previously-set configuration.
 *
 * @return a new server instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new server for any reason
 *
 * @since 0.8//from  ww  w  .  jav  a2  s.c o m
 */
public T build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (OpenSsl.isAvailable()) {
            log.info("Native SSL provider is available; will use native provider.");
            sslProvider = SslProvider.OPENSSL;
        } else {
            log.info("Native SSL provider not available; will use JDK SSL provider.");
            sslProvider = SslProvider.JDK;
        }

        final SslContextBuilder sslContextBuilder;

        if (this.certificateChain != null && this.privateKey != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword,
                    this.certificateChain);
        } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile,
                    this.privateKeyPkcs8File, this.privateKeyPassword);
        } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream,
                    this.privateKeyPkcs8InputStream, this.privateKeyPassword);
        } else {
            throw new IllegalStateException("Must specify server credentials before building a mock server.");
        }

        sslContextBuilder.sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL);

        if (this.trustedClientCertificatePemFile != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificatePemFile);
        } else if (this.trustedClientCertificateInputStream != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificateInputStream);
        } else if (this.trustedClientCertificates != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificates);
        }

        if (this.useAlpn) {
            sslContextBuilder.applicationProtocolConfig(
                    new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                            ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                            ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                            ApplicationProtocolNames.HTTP_2));
        }

        sslContext = sslContextBuilder.build();
    }

    final T server = this.constructServer(sslContext);

    if (sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) sslContext).release();
    }

    return server;
}

From source file:com.vmware.xenon.host.XenonHostWithPeerListener.java

License:Open Source License

private int startPeerListener() throws Throwable {
    if (this.hostArgs.nodeGroupPublicUri == null) {
        return ServiceHost.PORT_VALUE_LISTENER_DISABLED;
    }// www  .j av a2s . c o  m

    URI uri = URI.create(this.hostArgs.nodeGroupPublicUri);
    NettyHttpListener peerListener = new NettyHttpListener(this);

    boolean isHttps = uri.getScheme().equals("https");
    if (isHttps) {
        SslContextBuilder builder;
        if (this.hostArgs.peerCertificateFile != null && this.hostArgs.peerKeyFile != null) {
            builder = SslContextBuilder.forServer(this.hostArgs.peerCertificateFile.toFile(),
                    this.hostArgs.peerKeyFile.toFile(), this.hostArgs.peerKeyPassphrase);
        } else {
            builder = SslContextBuilder.forServer(this.hostArgs.certificateFile.toFile(),
                    this.hostArgs.keyFile.toFile(), this.hostArgs.keyPassphrase);
        }

        if (OpenSsl.isAlpnSupported()) {
            builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .applicationProtocolConfig(
                            new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1));
        }

        peerListener.setSSLContext(builder.build());
    }

    peerListener.start(uri.getPort(), uri.getHost());
    int assignedPort = peerListener.getPort();
    log(Level.INFO, "Started peer listener on %s",
            UriUtils.buildUri(uri.getScheme(), uri.getHost(), assignedPort, null, null));
    return assignedPort;
}

From source file:com.vmware.xenon.host.XenonHostWithPeerListenerTest.java

License:Open Source License

private ServiceClient createAllTrustingHttp2ServiceClient() throws Throwable {
    ServiceClient client = newAllTrustingServiceClient();

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    try (InputStream stream = new FileInputStream("../xenon-common/src/test/resources/ssl/client.p12")) {
        keyStore.load(stream, "changeit".toCharArray());
    }/*from  w ww  . ja v a 2  s  .  co m*/
    kmf.init(keyStore, "changeit".toCharArray());

    SslContext http2ClientContext = SslContextBuilder.forClient().keyManager(kmf)
            .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);
    client.start();
    return client;
}

From source file:io.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

public DefaultHttpClient(HttpClientConfig config) {
    this.config = config;
    try {/*from ww  w  .j a va  2  s.c  o  m*/
        SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

        if (config.getSslSessionCacheSize() > 0) {
            sslContextBuilder.sessionCacheSize(config.getSslSessionCacheSize());
        }

        if (config.getSslSessionTimeout() > 0) {
            sslContextBuilder.sessionTimeout(config.getSslSessionTimeout());
        }

        if (isNonEmpty(config.getEnabledSslProtocols())) {
            sslContextBuilder.protocols(config.getEnabledSslProtocols());
        }

        if (isNonEmpty(config.getEnabledSslCipherSuites())) {
            sslContextBuilder.ciphers(Arrays.asList(config.getEnabledSslCipherSuites()));
        } else if (!config.isFilterInsecureCipherSuites()) {
            sslContextBuilder.ciphers(null, IdentityCipherSuiteFilter.INSTANCE_DEFAULTING_TO_SUPPORTED_CIPHERS);
        }

        sslContextBuilder.sslProvider(config.isUseOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK)
                .keyManager(config.getKeyManagerFactory()).trustManager(config.getTrustManagerFactory());

        this.sslContext = sslContextBuilder.build();

        this.alpnSslContext = sslContextBuilder.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, ApplicationProtocolNames.HTTP_1_1))
                .build();

    } catch (SSLException e) {
        throw new IllegalArgumentException("Impossible to create SslContext", e);
    }

    DefaultThreadFactory threadFactory = new DefaultThreadFactory(config.getThreadPoolName());
    eventLoopGroup = config.isUseNativeTransport() ? new EpollEventLoopGroup(0, threadFactory)
            : new NioEventLoopGroup(0, threadFactory);
    eventLoopPicker = new AffinityEventLoopPicker(eventLoopGroup);
    channelGroup = new DefaultChannelGroup(eventLoopGroup.next());
}

From source file:io.vertx.core.net.impl.SSLHelper.java

License:Open Source License

private SslContext createContext(VertxInternal vertx) {
    try {/*from  w  w  w .ja v a  2s  . c om*/
        KeyManagerFactory keyMgrFactory = getKeyMgrFactory(vertx);
        TrustManagerFactory trustMgrFactory = getTrustMgrFactory(vertx);
        SslContextBuilder builder;
        if (client) {
            builder = SslContextBuilder.forClient();
            if (keyMgrFactory != null) {
                builder.keyManager(keyMgrFactory);
            }
        } else {
            if (keyMgrFactory == null) {
                throw new VertxException("Key/certificate is mandatory for SSL");
            }
            builder = SslContextBuilder.forServer(keyMgrFactory);
        }
        Collection<String> cipherSuites = enabledCipherSuites;
        if (openSsl) {
            builder.sslProvider(SslProvider.OPENSSL);
            if (cipherSuites == null || cipherSuites.isEmpty()) {
                cipherSuites = OpenSsl.availableOpenSslCipherSuites();
            }
        } else {
            builder.sslProvider(SslProvider.JDK);
            if (cipherSuites == null || cipherSuites.isEmpty()) {
                cipherSuites = DEFAULT_JDK_CIPHER_SUITE;
            }
        }
        if (trustMgrFactory != null) {
            builder.trustManager(trustMgrFactory);
        }
        if (cipherSuites != null && cipherSuites.size() > 0) {
            builder.ciphers(cipherSuites);
        }
        if (useAlpn && applicationProtocols != null && applicationProtocols.size() > 0) {
            builder.applicationProtocolConfig(new ApplicationProtocolConfig(
                    ApplicationProtocolConfig.Protocol.ALPN,
                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, applicationProtocols
                            .stream().map(PROTOCOL_NAME_MAPPING::get).collect(Collectors.toList())));
        }
        return builder.build();
    } catch (Exception e) {
        throw new VertxException(e);
    }
}