List of usage examples for io.netty.handler.ssl SslProvider JDK
SslProvider JDK
To view the source code for io.netty.handler.ssl SslProvider JDK.
Click Source Link
From source file:com.foilen.smalltools.net.netty.NettyServer.java
License:Open Source License
/** * Start the server./* w ww. j a v a 2 s . co m*/ * * @param port * the port to listen on (0 for a random port ; get it with {@link #getPort()}) * @param trustedCertificates * (optional) the certificate to trust connections from * @param certificate * (optional) the server's certificate * @param channelHandlerContainers * the channel handlers for the incoming connections */ public void start(final int port, final RSATrustedCertificates trustedCertificates, final RSACertificate certificate, final List<ChannelHandlerContainer> channelHandlerContainers) { AssertTools.assertNull(thread, "Server is already started"); final CountDownLatch countDownLatch = new CountDownLatch(1); thread = new Thread(() -> { try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(NettyCommon.EVENT_LOOP_GROUP, NettyCommon.EVENT_LOOP_GROUP); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { InetSocketAddress remoteAddress = socketChannel.remoteAddress(); logger.info("Got a connection from {}:{}", remoteAddress.getHostName(), remoteAddress.getPort()); // Add sslCtx if needed if (trustedCertificates != null || certificate != null) { TrustManagerFactory trustManagerFactory = trustedCertificates == null ? null : RSATools.createTrustManagerFactory(trustedCertificates); KeyManagerFactory keyManagerFactory = certificate == null ? null : RSATools.createKeyManagerFactory(certificate); CipherSuiteFilter cipherFilter = IdentityCipherSuiteFilter.INSTANCE; SslContext sslCtx = SslContext.newServerContext(SslProvider.JDK, null, trustManagerFactory, null, null, null, keyManagerFactory, null, cipherFilter, null, 0, 0); SslHandler sslHandler = sslCtx.newHandler(socketChannel.alloc()); if (trustManagerFactory == null) { logger.debug("Will not verify client's identity"); } else { logger.debug("Will verify client's identity"); SSLEngine sslEngine = sslHandler.engine(); sslEngine.setNeedClientAuth(true); } socketChannel.pipeline().addLast(sslHandler); } // Add the channel handlers for (ChannelHandlerContainer channelHandlerContainer : channelHandlerContainers) { socketChannel.pipeline() .addLast(ReflectionTools.instantiate( channelHandlerContainer.getChannelHandlerClass(), channelHandlerContainer.getConstructorParams())); } } }) // .option(ChannelOption.SO_BACKLOG, 128) // .childOption(ChannelOption.SO_KEEPALIVE, true); bindedPort = port; logger.info("Server on port {} is starting...", port); ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); SocketAddress socketAddress = channelFuture.channel().localAddress(); if (socketAddress instanceof InetSocketAddress) { InetSocketAddress inetSocketAddress = (InetSocketAddress) socketAddress; bindedPort = inetSocketAddress.getPort(); } logger.info("Server on port {} is started", bindedPort); countDownLatch.countDown(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { logger.info("Server on port {} is interrupted", bindedPort); } finally { countDownLatch.countDown(); } logger.info("Server on port {} is stopped", bindedPort); }); thread.setName("Netty Server-" + bindedPort); thread.start(); try { countDownLatch.await(); } catch (InterruptedException e) { logger.error("Interrupted while waiting for the server to start"); } }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java
License:Open Source License
public HttpBlobStore(URI uri, int timeoutMillis, @Nullable final Credentials creds) throws Exception { boolean useTls = uri.getScheme().equals("https"); if (uri.getPort() == -1) { int port = useTls ? 443 : 80; uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(), uri.getFragment());/*ww w. j av a2 s .c o m*/ } this.uri = uri; final SslContext sslCtx; if (useTls) { // OpenSsl gives us a > 2x speed improvement on fast networks, but requires netty tcnative // to be there which is not available on all platforms and environments. SslProvider sslProvider = OpenSsl.isAvailable() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient().sslProvider(sslProvider).build(); } else { sslCtx = null; } Bootstrap clientBootstrap = new Bootstrap().channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeoutMillis).group(eventLoop) .remoteAddress(uri.getHost(), uri.getPort()); downloadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() { @Override public void channelReleased(Channel ch) { ch.pipeline().remove("read-timeout-handler"); } @Override public void channelAcquired(Channel ch) { ch.pipeline().addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis)); } @Override public void channelCreated(Channel ch) { ChannelPipeline p = ch.pipeline(); p.addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis)); if (sslCtx != null) { SSLEngine engine = sslCtx.newEngine(ch.alloc()); engine.setUseClientMode(true); p.addFirst(new SslHandler(engine)); } p.addLast(new HttpClientCodec()); p.addLast(new HttpDownloadHandler(creds)); } }); uploadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() { @Override public void channelReleased(Channel ch) { } @Override public void channelAcquired(Channel ch) { } @Override public void channelCreated(Channel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { SSLEngine engine = sslCtx.newEngine(ch.alloc()); engine.setUseClientMode(true); p.addFirst(new SslHandler(engine)); } p.addLast(new HttpResponseDecoder()); // The 10KiB limit was chosen at random. We only expect HTTP servers to respond with // an error message in the body and that should always be less than 10KiB. p.addLast(new HttpObjectAggregator(10 * 1024)); p.addLast(new HttpRequestEncoder()); p.addLast(new ChunkedWriteHandler()); p.addLast(new HttpUploadHandler(creds)); } }); this.creds = creds; }
From source file:com.hop.hhxx.example.http2.helloworld.client.Http2Client.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {//from ww w. ja v a 2 s . co m SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient().sslProvider(provider) /* 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) .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } else { sslCtx = null; } EventLoopGroup workerGroup = new NioEventLoopGroup(); Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE); try { // Configure the client. Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(initializer); // Start the client. Channel channel = b.connect().syncUninterruptibly().channel(); System.out.println("Connected to [" + HOST + ':' + PORT + ']'); // Wait for the HTTP/2 upgrade to occur. Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler(); http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS); HttpResponseHandler responseHandler = initializer.responseHandler(); int streamId = 3; HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP; AsciiString hostName = new AsciiString(HOST + ':' + PORT); System.err.println("Sending request(s)..."); if (URL != null) { // Create a simple GET request. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL); request.headers().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise()); streamId += 2; } if (URL2 != null) { // Create a simple POST request with a body. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2, Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8))); request.headers().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise()); streamId += 2; } responseHandler.awaitResponses(5, TimeUnit.SECONDS); System.out.println("Finished HTTP/2 request(s)"); // Wait until the connection is closed. channel.close().syncUninterruptibly(); } finally { workerGroup.shutdownGracefully(); } }
From source file:com.just.server.http.https.HttpsStaticFileServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream("D:\\catest.key"), "catest".toCharArray()); kmf.init(ks, "catest".toCharArray()); sslCtx = SslContextBuilder.forServer(kmf).sslProvider(SslProvider.JDK).build(); EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from w ww. j a v a2 s .c o m ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HttpStaticFileServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.err.println("Open your web browser and navigate to " + "https" + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.liferay.sync.engine.lan.server.file.LanFileServerInitializer.java
License:Open Source License
public void updateDomainNameMapping() { DomainNameMappingBuilder<SslContext> domainNameMappingBuilder = null; for (SyncAccount syncAccount : SyncAccountService.findAll()) { if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) { continue; }/*from ww w .j av a 2s.c om*/ SslContext sslContext = null; try { X509Certificate x509Certificate = LanPEMParserUtil .parseX509Certificate(syncAccount.getLanCertificate()); SslContextBuilder sslContextBuilder = SslContextBuilder .forServer(LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey()), x509Certificate); sslContextBuilder.clientAuth(ClientAuth.REQUIRE); sslContextBuilder.sslProvider(SslProvider.JDK); sslContextBuilder.trustManager(x509Certificate); sslContext = sslContextBuilder.build(); } catch (Exception e) { _logger.error(e.getMessage(), e); continue; } if (domainNameMappingBuilder == null) { domainNameMappingBuilder = new DomainNameMappingBuilder<>(sslContext); } domainNameMappingBuilder.add(LanClientUtil.getSNIHostname(syncAccount.getLanServerUuid()), sslContext); } if (domainNameMappingBuilder == null) { return; } _domainNameMapping = domainNameMappingBuilder.build(); }
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 a 2s . co 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 {/*from ww w . j a va2 s .c om*/ // 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:// w w w .j a va 2 s. co 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 a SslContext", e); } } else { sslCtx = null; } }
From source file:com.linecorp.armeria.server.AbstractVirtualHostBuilder.java
License:Apache License
/** * Configures SSL or TLS of this {@link VirtualHost} with the specified {@code keyCertChainFile}, * {@code keyFile} and {@code keyPassword}. *//*from w ww.j ava 2 s . c o m*/ public B tls(File keyCertChainFile, File keyFile, @Nullable String keyPassword) throws SSLException { if (!keyCertChainFile.exists()) { throw new SSLException("non-existent certificate chain file: " + keyCertChainFile); } if (!keyCertChainFile.canRead()) { throw new SSLException("cannot read certificate chain file: " + keyCertChainFile); } if (!keyFile.exists()) { throw new SSLException("non-existent key file: " + keyFile); } if (!keyFile.canRead()) { throw new SSLException("cannot read key file: " + keyFile); } final SslContext sslCtx; try { sslCtx = BouncyCastleKeyFactoryProvider.call(() -> { final SslContextBuilder builder = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword); builder.sslProvider(Flags.useOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK); builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE); builder.applicationProtocolConfig(HTTPS_ALPN_CFG); return builder.build(); }); } catch (RuntimeException | SSLException e) { throw e; } catch (Exception e) { throw new SSLException("failed to configure TLS: " + e, e); } tls(sslCtx); return self(); }
From source file:com.linecorp.armeria.server.VirtualHostBuilder.java
License:Apache License
/** * Sets the {@link SslContext} of this {@link VirtualHost} from the specified {@link SessionProtocol}, * {@code keyCertChainFile}, {@code keyFile} and {@code keyPassword}. *//*from w w w. j a v a 2s.c om*/ public VirtualHostBuilder sslContext(SessionProtocol protocol, File keyCertChainFile, File keyFile, String keyPassword) throws SSLException { if (requireNonNull(protocol, "protocol") != SessionProtocol.HTTPS) { throw new IllegalArgumentException("unsupported protocol: " + protocol); } final SslContextBuilder builder = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword); builder.sslProvider(NativeLibraries.isOpenSslAvailable() ? SslProvider.OPENSSL : SslProvider.JDK); builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE); builder.applicationProtocolConfig(HTTPS_ALPN_CFG); sslContext(builder.build()); return this; }