List of usage examples for io.netty.handler.ssl SslHandler handshakeFuture
public Future<Channel> handshakeFuture()
From source file:com.relayrides.pushy.apns.ApnsConnection.java
License:Open Source License
/** * Asynchronously connects to the APNs gateway in this connection's environment. The outcome of the connection * attempt is reported via this connection's listener. * * @see ApnsConnectionListener#handleConnectionSuccess(ApnsConnection) * @see ApnsConnectionListener#handleConnectionFailure(ApnsConnection, Throwable) *//* ww w .ja v a2s. c o m*/ @SuppressWarnings("deprecation") public synchronized void connect() { final ApnsConnection<T> apnsConnection = this; if (this.connectFuture != null) { throw new IllegalStateException(String.format("%s already started a connection attempt.", this.name)); } final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(this.eventLoopGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // TODO Remove this when Netty 5 is available bootstrap.option(ChannelOption.AUTO_CLOSE, false); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) { final ChannelPipeline pipeline = channel.pipeline(); final SSLEngine sslEngine = apnsConnection.sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); pipeline.addLast("ssl", new SslHandler(sslEngine)); pipeline.addLast("decoder", new RejectedNotificationDecoder()); pipeline.addLast("encoder", new ApnsPushNotificationEncoder()); pipeline.addLast("handler", new ApnsConnectionHandler(apnsConnection)); } }); log.debug("{} beginning connection process.", apnsConnection.name); this.connectFuture = bootstrap.connect(this.environment.getApnsGatewayHost(), this.environment.getApnsGatewayPort()); this.connectFuture.addListener(new GenericFutureListener<ChannelFuture>() { public void operationComplete(final ChannelFuture connectFuture) { if (connectFuture.isSuccess()) { log.debug("{} connected; waiting for TLS handshake.", apnsConnection.name); final SslHandler sslHandler = connectFuture.channel().pipeline().get(SslHandler.class); try { sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { public void operationComplete(final Future<Channel> handshakeFuture) { if (handshakeFuture.isSuccess()) { log.debug("{} successfully completed TLS handshake.", apnsConnection.name); apnsConnection.handshakeCompleted = true; apnsConnection.listener.handleConnectionSuccess(apnsConnection); } else { log.debug("{} failed to complete TLS handshake with APNs gateway.", apnsConnection.name, handshakeFuture.cause()); connectFuture.channel().close(); apnsConnection.listener.handleConnectionFailure(apnsConnection, handshakeFuture.cause()); } } }); } catch (NullPointerException e) { log.warn("{} failed to get SSL handler and could not wait for a TLS handshake.", apnsConnection.name); connectFuture.channel().close(); apnsConnection.listener.handleConnectionFailure(apnsConnection, e); } } else { log.debug("{} failed to connect to APNs gateway.", apnsConnection.name, connectFuture.cause()); apnsConnection.listener.handleConnectionFailure(apnsConnection, connectFuture.cause()); } } }); }
From source file:com.relayrides.pushy.apns.ApnsConnection.java
License:Open Source License
private Runnable getImmediateShutdownRunnable() { final ApnsConnection<T> apnsConnection = this; return new Runnable() { public void run() { final SslHandler sslHandler = apnsConnection.connectFuture.channel().pipeline() .get(SslHandler.class); if (apnsConnection.connectFuture.isCancellable()) { apnsConnection.connectFuture.cancel(true); } else if (sslHandler != null && sslHandler.handshakeFuture().isCancellable()) { sslHandler.handshakeFuture().cancel(true); } else { apnsConnection.connectFuture.channel().close(); }/*from w ww . ja v a 2 s . c o m*/ } }; }
From source file:com.relayrides.pushy.apns.FeedbackServiceClient.java
License:Open Source License
/** * <p>Retrieves a list of expired tokens from the APNs feedback service. Be warned that this is a * <strong>destructive operation</strong>. According to Apple's documentation:</p> * * <blockquote>The feedback service's list is cleared after you read it. Each time you connect to the feedback * service, the information it returns lists only the failures that have happened since you last * connected.</blockquote>// w w w .ja v a 2 s .c o m * * @param timeout the time after the last received data after which the connection to the feedback service should * be closed * @param timeoutUnit the unit of time in which the given {@code timeout} is measured * * @return a list of tokens that have expired since the last connection to the feedback service * * @throws InterruptedException if interrupted while waiting for a response from the feedback service * @throws FeedbackConnectionException if the connection to the feedback service failed for any reason */ public synchronized List<ExpiredToken> getExpiredTokens(final long timeout, final TimeUnit timeoutUnit) throws InterruptedException, FeedbackConnectionException { this.expiredTokens.clear(); final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(this.eventLoopGroup); bootstrap.channel(NioSocketChannel.class); final FeedbackServiceClient feedbackClient = this; bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); final SSLEngine sslEngine = feedbackClient.sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); pipeline.addLast("ssl", new SslHandler(sslEngine)); pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(timeout, timeoutUnit)); pipeline.addLast("decoder", new ExpiredTokenDecoder()); pipeline.addLast("handler", new FeedbackClientHandler(feedbackClient)); } }); final ChannelFuture connectFuture = bootstrap .connect(this.environment.getFeedbackHost(), this.environment.getFeedbackPort()).await(); if (connectFuture.isSuccess()) { log.debug("Connected to feedback service."); final SslHandler sslHandler = connectFuture.channel().pipeline().get(SslHandler.class); if (sslHandler != null) { final Future<Channel> handshakeFuture = sslHandler.handshakeFuture().await(); if (handshakeFuture.isSuccess()) { log.debug("Completed TLS handshake with feedback service."); // The feedback service will send us a list of device tokens as soon as we complete the SSL // handshake, then hang up. While we're waiting to sync with the connection closure, we'll be // receiving messages from the feedback service from another thread. connectFuture.channel().closeFuture().await(); } else { log.debug("Failed to complete TLS handshake with feedback service.", handshakeFuture.cause()); connectFuture.channel().close().await(); throw new FeedbackConnectionException(handshakeFuture.cause()); } } else { log.warn("Feedback client failed to get SSL handler and could not wait for TLS handshake."); connectFuture.channel().close().await(); throw new FeedbackConnectionException(null); } } else { log.debug("Failed to connect to feedback service.", connectFuture.cause()); throw new FeedbackConnectionException(connectFuture.cause()); } return new ArrayList<ExpiredToken>(this.expiredTokens); }
From source file:com.relayrides.pushy.apns.FeedbackServiceConnection.java
License:Open Source License
/** * <p>Connects to the APNs feedback service and waits for expired tokens to arrive. Be warned that this is a * <strong>destructive operation</strong>. According to Apple's documentation:</p> * * <blockquote>The feedback service's list is cleared after you read it. Each time you connect to the feedback * service, the information it returns lists only the failures that have happened since you last * connected.</blockquote>//from ww w . j a va 2 s.c o m */ public synchronized void connect() { if (this.connectFuture != null) { throw new IllegalStateException(String.format("%s already started a connection attempt.", this.name)); } final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(this.eventLoopGroup); bootstrap.channel(NioSocketChannel.class); final FeedbackServiceConnection feedbackConnection = this; bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); final SSLEngine sslEngine = feedbackConnection.sslContext.createSSLEngine(); sslEngine.setUseClientMode(true); pipeline.addLast("ssl", new SslHandler(sslEngine)); pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(feedbackConnection.configuration.getReadTimeout())); pipeline.addLast("decoder", new ExpiredTokenDecoder()); pipeline.addLast("handler", new FeedbackClientHandler(feedbackConnection)); } }); this.connectFuture = bootstrap.connect(this.environment.getFeedbackHost(), this.environment.getFeedbackPort()); this.connectFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture connectFuture) { if (connectFuture.isSuccess()) { log.debug("{} connected; waiting for TLS handshake.", feedbackConnection.name); final SslHandler sslHandler = connectFuture.channel().pipeline().get(SslHandler.class); try { sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> handshakeFuture) { if (handshakeFuture.isSuccess()) { log.debug("{} successfully completed TLS handshake.", feedbackConnection.name); if (feedbackConnection.listener != null) { feedbackConnection.listener.handleConnectionSuccess(feedbackConnection); } } else { log.debug("{} failed to complete TLS handshake with APNs feedback service.", feedbackConnection.name, handshakeFuture.cause()); connectFuture.channel().close(); if (feedbackConnection.listener != null) { feedbackConnection.listener.handleConnectionFailure(feedbackConnection, handshakeFuture.cause()); } } } }); } catch (NullPointerException e) { log.warn("{} failed to get SSL handler and could not wait for a TLS handshake.", feedbackConnection.name); connectFuture.channel().close(); if (feedbackConnection.listener != null) { feedbackConnection.listener.handleConnectionFailure(feedbackConnection, e); } } } else { log.debug("{} failed to connect to APNs feedback service.", feedbackConnection.name, connectFuture.cause()); if (feedbackConnection.listener != null) { feedbackConnection.listener.handleConnectionFailure(feedbackConnection, connectFuture.cause()); } } } }); }
From source file:com.turo.pushy.apns.ApnsChannelFactory.java
License:Open Source License
ApnsChannelFactory(final SslContext sslContext, final ApnsSigningKey signingKey, final ProxyHandlerFactory proxyHandlerFactory, final int connectTimeoutMillis, final long idlePingIntervalMillis, final long gracefulShutdownTimeoutMillis, final Http2FrameLogger frameLogger, final InetSocketAddress apnsServerAddress, final EventLoopGroup eventLoopGroup) { this.sslContext = sslContext; if (this.sslContext instanceof ReferenceCounted) { ((ReferenceCounted) this.sslContext).retain(); }/*from w w w . j a va 2 s. co m*/ this.addressResolverGroup = proxyHandlerFactory == null ? new RoundRobinDnsAddressResolverGroup( ClientChannelClassUtil.getDatagramChannelClass(eventLoopGroup), DefaultDnsServerAddressStreamProvider.INSTANCE) : NoopAddressResolverGroup.INSTANCE; this.bootstrapTemplate = new Bootstrap(); this.bootstrapTemplate.group(eventLoopGroup); this.bootstrapTemplate.option(ChannelOption.TCP_NODELAY, true); this.bootstrapTemplate.remoteAddress(apnsServerAddress); this.bootstrapTemplate.resolver(this.addressResolverGroup); if (connectTimeoutMillis > 0) { this.bootstrapTemplate.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis); } this.bootstrapTemplate.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) { final ChannelPipeline pipeline = channel.pipeline(); if (proxyHandlerFactory != null) { pipeline.addFirst(proxyHandlerFactory.createProxyHandler()); } final SslHandler sslHandler = sslContext.newHandler(channel.alloc()); sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> handshakeFuture) { if (handshakeFuture.isSuccess()) { final String authority = channel.remoteAddress().getHostName(); final ApnsClientHandler.ApnsClientHandlerBuilder clientHandlerBuilder; if (signingKey != null) { clientHandlerBuilder = new TokenAuthenticationApnsClientHandler.TokenAuthenticationApnsClientHandlerBuilder() .signingKey(signingKey).authority(authority) .idlePingIntervalMillis(idlePingIntervalMillis); } else { clientHandlerBuilder = new ApnsClientHandler.ApnsClientHandlerBuilder() .authority(authority).idlePingIntervalMillis(idlePingIntervalMillis); } if (frameLogger != null) { clientHandlerBuilder.frameLogger(frameLogger); } final ApnsClientHandler apnsClientHandler = clientHandlerBuilder.build(); if (gracefulShutdownTimeoutMillis > 0) { apnsClientHandler.gracefulShutdownTimeoutMillis(gracefulShutdownTimeoutMillis); } // TODO Use a named constant when https://github.com/netty/netty/pull/8683 is available pipeline.addLast(new FlushConsolidationHandler(256, true)); pipeline.addLast( new IdleStateHandler(idlePingIntervalMillis, 0, 0, TimeUnit.MILLISECONDS)); pipeline.addLast(apnsClientHandler); pipeline.remove(ConnectionNegotiationErrorHandler.INSTANCE); channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get().trySuccess(channel); } else { tryFailureAndLogRejectedCause(channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get(), handshakeFuture.cause()); } } }); pipeline.addLast(sslHandler); pipeline.addLast(ConnectionNegotiationErrorHandler.INSTANCE); } }); }
From source file:com.turo.pushy.apns.server.BaseHttp2Server.java
License:Open Source License
BaseHttp2Server(final SslContext sslContext, final EventLoopGroup eventLoopGroup) { this.sslContext = sslContext; if (this.sslContext instanceof ReferenceCounted) { ((ReferenceCounted) this.sslContext).retain(); }//from w w w .ja v a 2 s. co m this.bootstrap = new ServerBootstrap(); if (eventLoopGroup != null) { this.bootstrap.group(eventLoopGroup); this.shouldShutDownEventLoopGroup = false; } else { this.bootstrap.group(new NioEventLoopGroup(1)); this.shouldShutDownEventLoopGroup = true; } this.allChannels = new DefaultChannelGroup(this.bootstrap.config().group().next()); this.bootstrap.channel(ServerChannelClassUtil.getServerSocketChannelClass(this.bootstrap.config().group())); this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) { final SslHandler sslHandler = sslContext.newHandler(channel.alloc()); channel.pipeline().addLast(sslHandler); channel.pipeline().addLast(ConnectionNegotiationErrorHandler.INSTANCE); sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> handshakeFuture) throws Exception { if (handshakeFuture.isSuccess()) { BaseHttp2Server.this.addHandlersToPipeline(sslHandler.engine().getSession(), channel.pipeline()); channel.pipeline().remove(ConnectionNegotiationErrorHandler.INSTANCE); BaseHttp2Server.this.allChannels.add(channel); } else { log.debug("TLS handshake failed.", handshakeFuture.cause()); } } }); } }); }
From source file:connection.bootstrap.Handler.java
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { Channel incomming = ctx.channel(); final SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); System.out.println("Attempting handshake"); sslHandler.handshakeFuture().addListener(new Authentication(sslHandler)); }
From source file:de.saxsys.synchronizefx.netty.base.NonValidatingSSLEngineFactory.java
License:Open Source License
/** * Creates a new {@link SslHandler} in client or server mode. * /*from w ww .j a v a2s . c o m*/ * @param clientMode if <code>true</code> a client engine is created, if <code>false</code> a server engine. * @return The new handler */ public static SslHandler createSslHandler(final boolean clientMode) { final SSLEngine engine = createEngine(clientMode); final SslHandler handler = new SslHandler(engine); handler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() { @Override public void operationComplete(final Future<? super Channel> future) throws Exception { LOG.debug("Using cipher " + engine.getSession().getCipherSuite() + " for the encrypted connection to the server."); } }); return handler; }
From source file:io.advantageous.conekt.http.impl.HttpClientImpl.java
License:Open Source License
private void internalConnect(ContextImpl clientContext, int port, String host, Handler<ClientConnection> connectHandler, Handler<Throwable> connectErrorHandler, ConnectionLifeCycleListener listener) { ContextImpl context;//from www .j a v a2s.co m if (clientContext == null) { // Embedded context = vertx.getOrCreateContext(); } else { context = clientContext; } Bootstrap bootstrap = new Bootstrap(); bootstrap.group(context.nettyEventLoop()); bootstrap.channelFactory(new VertxNioSocketChannelFactory()); sslHelper.validate(vertx); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (options.isSsl()) { pipeline.addLast("ssl", sslHelper.createSslHandler(vertx, true, host, port)); } pipeline.addLast("codec", new HttpClientCodec(4096, 8192, options.getMaxChunkSize(), false, false)); if (options.isTryUseCompression()) { pipeline.addLast("inflater", new HttpContentDecompressor(true)); } if (options.getIdleTimeout() > 0) { pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout())); } pipeline.addLast("handler", new ClientHandler(vertx, context)); } }); applyConnectionOptions(bootstrap); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.addListener((ChannelFuture channelFuture) -> { Channel ch = channelFuture.channel(); if (channelFuture.isSuccess()) { if (options.isSsl()) { // TCP connected, so now we must do the SSL handshake SslHandler sslHandler = ch.pipeline().get(SslHandler.class); io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(fut2 -> { if (fut2.isSuccess()) { connected(context, port, host, ch, connectHandler, connectErrorHandler, listener); } else { SSLHandshakeException sslException = new SSLHandshakeException( "Failed to create SSL connection"); Optional.ofNullable(fut2.cause()).ifPresent(sslException::initCause); connectionFailed(context, ch, connectErrorHandler, sslException, listener); } }); } else { connected(context, port, host, ch, connectHandler, connectErrorHandler, listener); } } else { connectionFailed(context, ch, connectErrorHandler, channelFuture.cause(), listener); } }); }
From source file:io.advantageous.conekt.net.impl.NetClientImpl.java
License:Open Source License
private void connect(int port, String host, Handler<AsyncResult<NetSocket>> connectHandler, int remainingAttempts) { Objects.requireNonNull(host, "No null host accepted"); Objects.requireNonNull(connectHandler, "No null connectHandler accepted"); ContextImpl context = vertx.getOrCreateContext(); sslHelper.validate(vertx);/*from www . j a va 2s. c o m*/ Bootstrap bootstrap = new Bootstrap(); bootstrap.group(context.nettyEventLoop()); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (sslHelper.isSSL()) { SslHandler sslHandler = sslHelper.createSslHandler(vertx, true); pipeline.addLast("ssl", sslHandler); } if (sslHelper.isSSL()) { // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used. pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support } if (options.getIdleTimeout() > 0) { pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout())); } pipeline.addLast("handler", new ConektNetHandler(socketMap)); } }); applyConnectionOptions(bootstrap); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); future.addListener((ChannelFuture channelFuture) -> { Channel ch = channelFuture.channel(); if (channelFuture.isSuccess()) { if (sslHelper.isSSL()) { // TCP connected, so now we must do the SSL handshake SslHandler sslHandler = ch.pipeline().get(SslHandler.class); io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(future2 -> { if (future2.isSuccess()) { connected(context, ch, connectHandler); } else { failed(context, ch, future2.cause(), connectHandler); } }); } else { connected(context, ch, connectHandler); } } else { if (remainingAttempts > 0 || remainingAttempts == -1) { context.executeFromIO(() -> { log.debug("Failed to create connection. Will retry in " + options.getReconnectInterval() + " milliseconds"); //Set a timer to retry connection vertx.setTimer(options.getReconnectInterval(), tid -> connect(port, host, connectHandler, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1)); }); } else { failed(context, ch, channelFuture.cause(), connectHandler); } } }); }