Search in sources :

Example 1 with TLS

use of org.apache.hc.core5.http.ssl.TLS in project httpcomponents-core by apache.

the class H2ViaHttp1ProxyExecutionExample method main.

public static void main(final String[] args) throws Exception {
    // Create and start requester
    final H2Config h2Config = H2Config.custom().setPushEnabled(false).build();
    final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setH2Config(h2Config).setVersionPolicy(HttpVersionPolicy.NEGOTIATE).setStreamListener(new Http1StreamListener() {

        @Override
        public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
            System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
        }

        @Override
        public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
            System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
        }

        @Override
        public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
            if (keepAlive) {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
            } else {
                System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
            }
        }
    }).setStreamListener(new H2StreamListener() {

        @Override
        public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
            }
        }

        @Override
        public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
            for (int i = 0; i < headers.size(); i++) {
                System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
            }
        }

        @Override
        public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
        }

        @Override
        public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }

        @Override
        public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
        }
    }).create();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        System.out.println("HTTP requester shutting down");
        requester.close(CloseMode.GRACEFUL);
    }));
    requester.start();
    final HttpHost proxy = new HttpHost("localhost", 8888);
    final HttpHost target = new HttpHost("https", "nghttp2.org");
    final ComplexFuture<AsyncClientEndpoint> tunnelFuture = new ComplexFuture<>(null);
    tunnelFuture.setDependency(requester.connect(proxy, Timeout.ofSeconds(30), null, new FutureContribution<AsyncClientEndpoint>(tunnelFuture) {

        @Override
        public void completed(final AsyncClientEndpoint endpoint) {
            if (endpoint instanceof TlsUpgradeCapable) {
                final HttpRequest connect = new BasicHttpRequest(Method.CONNECT, proxy, target.toHostString());
                endpoint.execute(new BasicRequestProducer(connect, null), new BasicResponseConsumer<>(new DiscardingEntityConsumer<>()), new FutureContribution<Message<HttpResponse, Void>>(tunnelFuture) {

                    @Override
                    public void completed(final Message<HttpResponse, Void> message) {
                        final HttpResponse response = message.getHead();
                        if (response.getCode() == HttpStatus.SC_OK) {
                            ((TlsUpgradeCapable) endpoint).tlsUpgrade(target, new FutureContribution<ProtocolIOSession>(tunnelFuture) {

                                @Override
                                public void completed(final ProtocolIOSession protocolSession) {
                                    System.out.println("Tunnel to " + target + " via " + proxy + " established");
                                    tunnelFuture.completed(endpoint);
                                }
                            });
                        } else {
                            tunnelFuture.failed(new HttpException("Tunnel refused: " + new StatusLine(response)));
                        }
                    }
                });
            } else {
                tunnelFuture.failed(new IllegalStateException("TLS upgrade not supported"));
            }
        }
    }));
    final String[] requestUris = new String[] { "/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers" };
    final AsyncClientEndpoint endpoint = tunnelFuture.get(1, TimeUnit.MINUTES);
    try {
        final CountDownLatch latch = new CountDownLatch(requestUris.length);
        for (final String requestUri : requestUris) {
            endpoint.execute(new BasicRequestProducer(Method.GET, target, requestUri), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() {

                @Override
                public void completed(final Message<HttpResponse, String> message) {
                    final HttpResponse response = message.getHead();
                    final String body = message.getBody();
                    System.out.println(requestUri + "->" + response.getCode());
                    System.out.println(body);
                    latch.countDown();
                }

                @Override
                public void failed(final Exception ex) {
                    System.out.println(requestUri + "->" + ex);
                    latch.countDown();
                }

                @Override
                public void cancelled() {
                    System.out.println(requestUri + " cancelled");
                    latch.countDown();
                }
            });
        }
        latch.await();
    } finally {
        endpoint.releaseAndDiscard();
    }
    System.out.println("Shutting down I/O reactor");
    requester.initiateShutdown();
}
Also used : Message(org.apache.hc.core5.http.Message) HttpConnection(org.apache.hc.core5.http.HttpConnection) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) ProtocolIOSession(org.apache.hc.core5.reactor.ProtocolIOSession) Http1StreamListener(org.apache.hc.core5.http.impl.Http1StreamListener) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) TlsUpgradeCapable(org.apache.hc.core5.http.nio.ssl.TlsUpgradeCapable) H2StreamListener(org.apache.hc.core5.http2.impl.nio.H2StreamListener) HttpHost(org.apache.hc.core5.http.HttpHost) List(java.util.List) HttpException(org.apache.hc.core5.http.HttpException) HttpAsyncRequester(org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester) BasicHttpRequest(org.apache.hc.core5.http.message.BasicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) StringAsyncEntityConsumer(org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) HttpResponse(org.apache.hc.core5.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncClientEndpoint(org.apache.hc.core5.http.nio.AsyncClientEndpoint) HttpException(org.apache.hc.core5.http.HttpException) StatusLine(org.apache.hc.core5.http.message.StatusLine) DiscardingEntityConsumer(org.apache.hc.core5.http.nio.entity.DiscardingEntityConsumer) RequestLine(org.apache.hc.core5.http.message.RequestLine) Header(org.apache.hc.core5.http.Header) RawFrame(org.apache.hc.core5.http2.frame.RawFrame) FutureContribution(org.apache.hc.core5.concurrent.FutureContribution) H2Config(org.apache.hc.core5.http2.config.H2Config) ComplexFuture(org.apache.hc.core5.concurrent.ComplexFuture)

Example 2 with TLS

use of org.apache.hc.core5.http.ssl.TLS in project httpcomponents-core by apache.

the class TlsVersionParser method parse.

ProtocolVersion parse(final CharSequence buffer, final Tokenizer.Cursor cursor, final BitSet delimiters) throws ParseException {
    final int lowerBound = cursor.getLowerBound();
    final int upperBound = cursor.getUpperBound();
    int pos = cursor.getPos();
    if (pos + 4 > cursor.getUpperBound()) {
        throw new ParseException("Invalid TLS protocol version", buffer, lowerBound, upperBound, pos);
    }
    if (buffer.charAt(pos) != 'T' || buffer.charAt(pos + 1) != 'L' || buffer.charAt(pos + 2) != 'S' || buffer.charAt(pos + 3) != 'v') {
        throw new ParseException("Invalid TLS protocol version", buffer, lowerBound, upperBound, pos);
    }
    pos = pos + 4;
    cursor.updatePos(pos);
    if (cursor.atEnd()) {
        throw new ParseException("Invalid TLS version", buffer, lowerBound, upperBound, pos);
    }
    final String s = this.tokenizer.parseToken(buffer, cursor, delimiters);
    final int idx = s.indexOf('.');
    if (idx == -1) {
        final int major;
        try {
            major = Integer.parseInt(s);
        } catch (final NumberFormatException e) {
            throw new ParseException("Invalid TLS major version", buffer, lowerBound, upperBound, pos);
        }
        return new ProtocolVersion("TLS", major, 0);
    } else {
        final String s1 = s.substring(0, idx);
        final int major;
        try {
            major = Integer.parseInt(s1);
        } catch (final NumberFormatException e) {
            throw new ParseException("Invalid TLS major version", buffer, lowerBound, upperBound, pos);
        }
        final String s2 = s.substring(idx + 1);
        final int minor;
        try {
            minor = Integer.parseInt(s2);
        } catch (final NumberFormatException e) {
            throw new ParseException("Invalid TLS minor version", buffer, lowerBound, upperBound, pos);
        }
        return new ProtocolVersion("TLS", major, minor);
    }
}
Also used : ParseException(org.apache.hc.core5.http.ParseException) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 3 with TLS

use of org.apache.hc.core5.http.ssl.TLS in project commons-vfs by apache.

the class Http5FileProvider method createConnectionManager.

private HttpClientConnectionManager createConnectionManager(final Http5FileSystemConfigBuilder builder, final FileSystemOptions fileSystemOptions) throws FileSystemException {
    final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(Timeout.ofMilliseconds(builder.getSoTimeoutDuration(fileSystemOptions).toMillis())).build();
    final String[] tlsVersions = builder.getTlsVersions(fileSystemOptions).split("\\s*,\\s*");
    final TLS[] tlsArray = Stream.of(tlsVersions).map(TLS::valueOf).toArray(TLS[]::new);
    final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create().setSslContext(createSSLContext(builder, fileSystemOptions)).setHostnameVerifier(createHostnameVerifier(builder, fileSystemOptions)).setTlsVersions(tlsArray).build();
    return PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).setMaxConnTotal(builder.getMaxTotalConnections(fileSystemOptions)).setMaxConnPerRoute(builder.getMaxConnectionsPerHost(fileSystemOptions)).setDefaultSocketConfig(socketConfig).build();
}
Also used : SocketConfig(org.apache.hc.core5.http.io.SocketConfig) TLS(org.apache.hc.core5.http.ssl.TLS) SSLConnectionSocketFactory(org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory)

Example 4 with TLS

use of org.apache.hc.core5.http.ssl.TLS in project wiremock by wiremock.

the class HttpsAcceptanceTest method secureContentFor.

static String secureContentFor(String url, String clientTrustStore, String trustStorePassword) throws Exception {
    KeyStore trustStore = readKeyStore(clientTrustStore, trustStorePassword);
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).loadKeyMaterial(trustStore, trustStorePassword.toCharArray()).setKeyStoreType("pkcs12").setProtocol("TLS").build();
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslcontext, // supported protocols
    null, // supported cipher suites
    null, NoopHostnameVerifier.INSTANCE);
    PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
    HttpGet get = new HttpGet(url);
    ClassicHttpResponse response = httpClient.execute(get);
    String content = EntityUtils.toString(response.getEntity());
    return content;
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) SSLConnectionSocketFactory(org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory) TrustSelfSignedStrategy(org.apache.hc.client5.http.ssl.TrustSelfSignedStrategy) PoolingHttpClientConnectionManager(org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager)

Example 5 with TLS

use of org.apache.hc.core5.http.ssl.TLS in project cxf by apache.

the class AsyncHTTPConduit method getSSLContext.

public synchronized SSLContext getSSLContext(TLSClientParameters tlsClientParameters) throws GeneralSecurityException {
    int hash = tlsClientParameters.hashCode();
    if (hash == lastTlsHash && sslContext != null) {
        return sslContext;
    }
    final SSLContext ctx;
    if (tlsClientParameters.getSslContext() != null) {
        ctx = tlsClientParameters.getSslContext();
    } else {
        String provider = tlsClientParameters.getJsseProvider();
        String protocol = tlsClientParameters.getSecureSocketProtocol() != null ? tlsClientParameters.getSecureSocketProtocol() : "TLS";
        ctx = provider == null ? SSLContext.getInstance(protocol) : SSLContext.getInstance(protocol, provider);
        KeyManager[] keyManagers = tlsClientParameters.getKeyManagers();
        if (keyManagers == null) {
            keyManagers = org.apache.cxf.configuration.jsse.SSLUtils.getDefaultKeyStoreManagers(LOG);
        }
        KeyManager[] configuredKeyManagers = org.apache.cxf.transport.https.SSLUtils.configureKeyManagersWithCertAlias(tlsClientParameters, keyManagers);
        TrustManager[] trustManagers = tlsClientParameters.getTrustManagers();
        if (trustManagers == null) {
            trustManagers = org.apache.cxf.configuration.jsse.SSLUtils.getDefaultTrustStoreManagers(LOG);
        }
        ctx.init(configuredKeyManagers, trustManagers, tlsClientParameters.getSecureRandom());
        if (ctx.getClientSessionContext() != null) {
            ctx.getClientSessionContext().setSessionTimeout(tlsClientParameters.getSslCacheTimeout());
        }
    }
    sslContext = ctx;
    lastTlsHash = hash;
    sslState = null;
    sslURL = null;
    session = null;
    return ctx;
}
Also used : SSLContext(javax.net.ssl.SSLContext) KeyManager(javax.net.ssl.KeyManager) NamedEndpoint(org.apache.hc.core5.net.NamedEndpoint) TrustManager(javax.net.ssl.TrustManager)

Aggregations

SSLContext (javax.net.ssl.SSLContext)2 SSLConnectionSocketFactory (org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory)2 HttpHost (org.apache.hc.core5.http.HttpHost)2 IOException (java.io.IOException)1 UncheckedIOException (java.io.UncheckedIOException)1 ConnectException (java.net.ConnectException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 GeneralSecurityException (java.security.GeneralSecurityException)1 KeyStore (java.security.KeyStore)1 List (java.util.List)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 KeyManager (javax.net.ssl.KeyManager)1 TrustManager (javax.net.ssl.TrustManager)1 HttpHostConnectException (org.apache.hc.client5.http.HttpHostConnectException)1 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)1 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)1 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)1 PoolingHttpClientConnectionManager (org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager)1 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)1 TrustSelfSignedStrategy (org.apache.hc.client5.http.ssl.TrustSelfSignedStrategy)1