List of usage examples for io.netty.handler.ssl SslHandler handshakeFuture
public Future<Channel> handshakeFuture()
From source file:io.vertx.core.net.impl.NetSocketImpl.java
License:Open Source License
@Override public synchronized NetSocket upgradeToSsl(final Handler<Void> handler) { SslHandler sslHandler = channel.pipeline().get(SslHandler.class); if (sslHandler == null) { if (host != null) { sslHandler = helper.createSslHandler(vertx, host, port); } else {/*from www. j av a 2 s. c o m*/ sslHandler = helper.createSslHandler(vertx, this.remoteName(), this.remoteAddress().port()); } channel.pipeline().addFirst("ssl", sslHandler); } sslHandler.handshakeFuture().addListener(future -> context.executeFromIO(() -> { if (future.isSuccess()) { handler.handle(null); } else { log.error(future.cause()); } })); return this; }
From source file:io.vertx.core.net.impl.VertxSniHandler.java
License:Open Source License
@Override protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext) throws Exception { SslHandler sslHandler = null; try {/* ww w .j a v a 2 s.co m*/ SSLEngine engine = helper.createEngine(sslContext); sslHandler = new SslHandler(engine); ctx.pipeline().replace(this, "ssl", sslHandler); Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(future -> { if (future.isSuccess()) { Attribute<String> val = ctx.channel().attr(SERVER_NAME_ATTR); val.set(hostname); handshakeFuture.setSuccess(ctx.channel()); } else { handshakeFuture.setFailure(future.cause()); } }); sslHandler = null; } finally { // Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not // transferred to the SslHandler. // See https://github.com/netty/netty/issues/5678 if (sslHandler != null) { ReferenceCountUtil.safeRelease(sslHandler.engine()); } } }
From source file:org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnector.java
License:Apache License
public Connection createConnection() { if (channelClazz == null) { return null; }/*from w w w . j a v a 2 s .c o m*/ // HORNETQ-907 - strip off IPv6 scope-id (if necessary) SocketAddress remoteDestination = new InetSocketAddress(host, port); InetAddress inetAddress = ((InetSocketAddress) remoteDestination).getAddress(); if (inetAddress instanceof Inet6Address) { Inet6Address inet6Address = (Inet6Address) inetAddress; if (inet6Address.getScopeId() != 0) { try { remoteDestination = new InetSocketAddress(InetAddress.getByAddress(inet6Address.getAddress()), ((InetSocketAddress) remoteDestination).getPort()); } catch (UnknownHostException e) { throw new IllegalArgumentException(e.getMessage()); } } } ActiveMQClientLogger.LOGGER.debug("Remote destination: " + remoteDestination); ChannelFuture future; //port 0 does not work so only use local address if set if (localPort != 0) { SocketAddress localDestination; if (localAddress != null) { localDestination = new InetSocketAddress(localAddress, localPort); } else { localDestination = new InetSocketAddress(localPort); } future = bootstrap.connect(remoteDestination, localDestination); } else { future = bootstrap.connect(remoteDestination); } future.awaitUninterruptibly(); if (future.isSuccess()) { final Channel ch = future.channel(); SslHandler sslHandler = ch.pipeline().get(SslHandler.class); if (sslHandler != null) { Future<Channel> handshakeFuture = sslHandler.handshakeFuture(); if (handshakeFuture.awaitUninterruptibly(30000)) { if (handshakeFuture.isSuccess()) { ChannelPipeline channelPipeline = ch.pipeline(); ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class); channelHandler.active = true; } else { ch.close().awaitUninterruptibly(); ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause()); return null; } } else { //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds")); ch.close().awaitUninterruptibly(); return null; } } if (httpUpgradeEnabled) { // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler. try { //get this first incase it removes itself HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade"); URI uri = new URI("http", null, host, port, null, null, null); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.UPGRADE, ACTIVEMQ_REMOTING); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE); final String endpoint = ConfigurationHelper.getStringProperty( TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, null, configuration); if (endpoint != null) { request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint); } // Get 16 bit nonce and base 64 encode it byte[] nonce = randomBytes(16); String key = base64(nonce); request.headers().set(SEC_ACTIVEMQ_REMOTING_KEY, key); ch.attr(REMOTING_KEY).set(key); ActiveMQClientLogger.LOGGER.debugf("Sending HTTP request %s", request); // Send the HTTP request. ch.writeAndFlush(request); if (!httpUpgradeHandler.awaitHandshake()) { return null; } } catch (URISyntaxException e) { ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(e); return null; } } else { ChannelPipeline channelPipeline = ch.pipeline(); ActiveMQChannelHandler channelHandler = channelPipeline.get(ActiveMQChannelHandler.class); channelHandler.active = true; } // No acceptor on a client connection Listener connectionListener = new Listener(); NettyConnection conn = new NettyConnection(configuration, ch, connectionListener, !httpEnabled && batchDelay > 0, false); connectionListener.connectionCreated(null, conn, protocolManager.getName()); return conn; } else { Throwable t = future.cause(); if (t != null && !(t instanceof ConnectException)) { ActiveMQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause()); } return null; } }
From source file:org.apache.bookkeeper.proto.BookieRequestProcessor.java
License:Apache License
private void processStartTLSRequestV3(final BookkeeperProtocol.Request r, final Channel c) { BookkeeperProtocol.Response.Builder response = BookkeeperProtocol.Response.newBuilder(); BookkeeperProtocol.BKPacketHeader.Builder header = BookkeeperProtocol.BKPacketHeader.newBuilder(); header.setVersion(BookkeeperProtocol.ProtocolVersion.VERSION_THREE); header.setOperation(r.getHeader().getOperation()); header.setTxnId(r.getHeader().getTxnId()); response.setHeader(header.build());/*from ww w . ja v a2s . c om*/ if (shFactory == null) { LOG.error("Got StartTLS request but TLS not configured"); response.setStatus(BookkeeperProtocol.StatusCode.EBADREQ); c.writeAndFlush(response.build()); } else { // there is no need to execute in a different thread as this operation is light SslHandler sslHandler = shFactory.newTLSHandler(); c.pipeline().addFirst("tls", sslHandler); response.setStatus(BookkeeperProtocol.StatusCode.EOK); BookkeeperProtocol.StartTLSResponse.Builder builder = BookkeeperProtocol.StartTLSResponse.newBuilder(); response.setStartTLSResponse(builder.build()); sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { // notify the AuthPlugin the completion of the handshake, even in case of failure AuthHandler.ServerSideHandler authHandler = c.pipeline() .get(AuthHandler.ServerSideHandler.class); authHandler.authProvider.onProtocolUpgrade(); if (future.isSuccess()) { LOG.info("Session is protected by: {}", sslHandler.engine().getSession().getCipherSuite()); } else { LOG.error("TLS Handshake failure: {}", future.cause()); BookkeeperProtocol.Response.Builder errResponse = BookkeeperProtocol.Response.newBuilder() .setHeader(r.getHeader()).setStatus(BookkeeperProtocol.StatusCode.EIO); c.writeAndFlush(errResponse.build()); if (statsEnabled) { bkStats.getOpStats(BKStats.STATS_UNKNOWN).incrementFailedOps(); } } } }); c.writeAndFlush(response.build()); } }
From source file:org.apache.bookkeeper.proto.PerChannelBookieClient.java
License:Apache License
void initTLSHandshake() { // create TLS handler PerChannelBookieClient parentObj = PerChannelBookieClient.this; SslHandler handler = parentObj.shFactory.newTLSHandler(); channel.pipeline().addFirst(parentObj.shFactory.getHandlerName(), handler); handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override/*from ww w . j av a2s . co m*/ public void operationComplete(Future<Channel> future) throws Exception { int rc; Queue<GenericCallback<PerChannelBookieClient>> oldPendingOps; synchronized (PerChannelBookieClient.this) { if (future.isSuccess() && state == ConnectionState.CONNECTING) { LOG.error("Connection state changed before TLS handshake completed {}/{}", addr, state); rc = BKException.Code.BookieHandleNotAvailableException; closeChannel(channel); channel = null; if (state != ConnectionState.CLOSED) { state = ConnectionState.DISCONNECTED; } } else if (future.isSuccess() && state == ConnectionState.START_TLS) { rc = BKException.Code.OK; LOG.info("Successfully connected to bookie using TLS: " + addr); state = ConnectionState.CONNECTED; AuthHandler.ClientSideHandler authHandler = future.get().pipeline() .get(AuthHandler.ClientSideHandler.class); authHandler.authProvider.onProtocolUpgrade(); activeTlsChannelCounter.inc(); } else if (future.isSuccess() && (state == ConnectionState.CLOSED || state == ConnectionState.DISCONNECTED)) { LOG.warn("Closed before TLS handshake completed, clean up: {}, current state {}", channel, state); closeChannel(channel); rc = BKException.Code.BookieHandleNotAvailableException; channel = null; } else if (future.isSuccess() && state == ConnectionState.CONNECTED) { LOG.debug("Already connected with another channel({}), so close the new channel({})", channel, channel); closeChannel(channel); return; // pendingOps should have been completed when other channel connected } else { LOG.error("TLS handshake failed with bookie: {}/{}, current state {} : ", channel, addr, state, future.cause()); rc = BKException.Code.SecurityException; closeChannel(channel); channel = null; if (state != ConnectionState.CLOSED) { state = ConnectionState.DISCONNECTED; } failedTlsHandshakeCounter.inc(); } // trick to not do operations under the lock, take the list // of pending ops and assign it to a new variable, while // emptying the pending ops by just assigning it to a new // list oldPendingOps = pendingOps; pendingOps = new ArrayDeque<>(); } makeWritable(); for (GenericCallback<PerChannelBookieClient> pendingOp : oldPendingOps) { pendingOp.operationComplete(rc, PerChannelBookieClient.this); } } }); }
From source file:org.apache.qpid.jms.transports.netty.NettySslTransport.java
License:Apache License
@Override protected void handleConnected(final Channel channel) throws Exception { SslHandler sslHandler = channel.pipeline().get(SslHandler.class); Future<Channel> channelFuture = sslHandler.handshakeFuture(); channelFuture.addListener(new GenericFutureListener<Future<Channel>>() { @Override/*ww w . j a v a2 s. c om*/ public void operationComplete(Future<Channel> future) throws Exception { if (future.isSuccess()) { LOG.trace("SSL Handshake has completed: {}", channel); connectionEstablished(channel); } else { LOG.trace("SSL Handshake has failed: {}", channel); connectionFailed(IOExceptionSupport.create(future.cause())); } } }); }
From source file:org.asterisque.netty.WireConnect.java
License:Apache License
/** * ???????????/*from w w w .j av a 2 s.c o m*/ * SSL ?????? * @param ctx */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { trace("channelActive(" + ctx.name() + ")"); assert (!wire.isPresent()); // SSLHandler ???????? SSLSession ? CompletableFuture<Optional<SSLSession>> future = new CompletableFuture<>(); if (sslHandler.isPresent()) { SslHandler h = sslHandler.get(); h.handshakeFuture().addListener(f -> { SSLSession session = h.engine().getSession(); if (session.isValid()) { // SSL ? future.complete(Optional.of(session)); debug("tls handshake success"); } else { // SSL ? future.completeExceptionally(new IOException("tls handshake failure: invalid session")); debug("tls handshake failure: invalid session"); } Debug.dumpSSLSession(logger, sym + "[" + id + "]", session); }); } else { // SSL ?? future.complete(Optional.empty()); } // Wire NettyWire w = new NettyWire(node, local, remote, isServer, future, ctx); wire = Optional.of(w); super.channelActive(ctx); // onWireCreate.accept(w); }
From source file:org.asynchttpclient.netty.channel.NettyConnectListener.java
License:Open Source License
public void onSuccess(Channel channel, InetSocketAddress remoteAddress) { TimeoutsHolder timeoutsHolder = future.getTimeoutsHolder(); if (futureIsAlreadyCancelled(channel)) { return;// w w w . jav a2s .c o m } Request request = future.getTargetRequest(); Uri uri = request.getUri(); timeoutsHolder.initRemoteAddress(remoteAddress); // in case of proxy tunneling, we'll add the SslHandler later, after the CONNECT request if (future.getProxyServer() == null && uri.isSecured()) { SslHandler sslHandler = channelManager.addSslHandler(channel.pipeline(), uri, request.getVirtualHost()); final AsyncHandlerExtensions asyncHandlerExtensions = toAsyncHandlerExtensions( future.getAsyncHandler()); if (asyncHandlerExtensions != null) asyncHandlerExtensions.onTlsHandshakeAttempt(); sslHandler.handshakeFuture().addListener(new SimpleFutureListener<Channel>() { @Override protected void onSuccess(Channel value) throws Exception { if (asyncHandlerExtensions != null) asyncHandlerExtensions.onTlsHandshakeSuccess(); writeRequest(channel); } @Override protected void onFailure(Throwable cause) throws Exception { if (asyncHandlerExtensions != null) asyncHandlerExtensions.onTlsHandshakeFailure(cause); NettyConnectListener.this.onFailure(channel, cause); } }); } else { writeRequest(channel); } }
From source file:org.asynchttpclient.providers.netty.request.NettyConnectListener.java
License:Apache License
public void onFutureSuccess(final Channel channel) throws ConnectException { Channels.setDefaultAttribute(channel, future); final HostnameVerifier hostnameVerifier = config.getHostnameVerifier(); final SslHandler sslHandler = Channels.getSslHandler(channel); if (hostnameVerifier != null && sslHandler != null) { final String host = future.getURI().getHost(); sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() { @Override/*from ww w . j a v a 2 s .c o m*/ public void operationComplete(Future<? super Channel> handshakeFuture) throws Exception { if (handshakeFuture.isSuccess()) { Channel channel = (Channel) handshakeFuture.getNow(); SSLEngine engine = sslHandler.engine(); SSLSession session = engine.getSession(); LOGGER.debug("onFutureSuccess: session = {}, id = {}, isValid = {}, host = {}", session.toString(), Base64.encode(session.getId()), session.isValid(), host); if (!hostnameVerifier.verify(host, session)) { ConnectException exception = new ConnectException("HostnameVerifier exception"); future.abort(exception); throw exception; } else { requestSender.writeRequest(future, channel); } } } }); } else { requestSender.writeRequest(future, channel); } }
From source file:org.asynchttpclient.providers.netty4.request.NettyConnectListener.java
License:Open Source License
private void onFutureSuccess(final Channel channel) throws ConnectException { Channels.setAttribute(channel, future); final HostnameVerifier hostnameVerifier = config.getHostnameVerifier(); final SslHandler sslHandler = ChannelManager.getSslHandler(channel.pipeline()); if (hostnameVerifier != null && sslHandler != null) { final String host = future.getUri().getHost(); sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() { @Override//from www. j a v a 2s . c o m public void operationComplete(Future<? super Channel> handshakeFuture) throws Exception { if (handshakeFuture.isSuccess()) { Channel channel = (Channel) handshakeFuture.getNow(); SSLEngine engine = sslHandler.engine(); SSLSession session = engine.getSession(); LOGGER.debug("onFutureSuccess: session = {}, id = {}, isValid = {}, host = {}", session.toString(), Base64.encode(session.getId()), session.isValid(), host); if (hostnameVerifier.verify(host, session)) { final AsyncHandler<T> asyncHandler = future.getAsyncHandler(); if (asyncHandler instanceof AsyncHandlerExtensions) AsyncHandlerExtensions.class.cast(asyncHandler).onSslHandshakeCompleted(); writeRequest(channel); } else { onFutureFailure(channel, new ConnectException("HostnameVerifier exception")); } } else { onFutureFailure(channel, handshakeFuture.cause()); } } }); } else { writeRequest(channel); } }