List of usage examples for io.netty.handler.ssl SslHandler handshakeFuture
public Future<Channel> handshakeFuture()
From source file:com.allanbank.mongodb.netty.NettyChannelInit.java
License:Apache License
/** * {@inheritDoc}/*from w w w . j a v a 2 s .c om*/ * <p> * Overridden to initialize the channel's processing pipeline. * </p> */ @Override public void initChannel(final SocketChannel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); // Make sure we know when the connection gets closed. ch.closeFuture().addListener(new NettyCloseListener(myResponseListener)); SSLEngine engine = null; final SocketFactory socketFactory = myClientConfig.getSocketFactory(); if (socketFactory instanceof SslEngineFactory) { final SslEngineFactory factory = (SslEngineFactory) socketFactory; engine = factory.createSSLEngine(); } else if (socketFactory instanceof SSLSocketFactory) { engine = createVanillaEngine((SSLSocketFactory) socketFactory); } if (engine != null) { engine.setUseClientMode(true); final SslHandler handler = new SslHandler(engine, false /* startTLS */); pipeline.addLast("ssl", handler); if (socketFactory instanceof SocketConnectionListener) { handler.handshakeFuture().addListener(new NettyTlsConnectionCompletedListener( (SocketConnectionListener) socketFactory, engine, ch)); } } // Read side. pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(myClientConfig.getReadTimeout(), TimeUnit.MILLISECONDS)); pipeline.addLast("bufToMessageHandler", new ByteToMessageDecoder(myDecoderCache)); pipeline.addLast("replyHandler", new NettyReplyHandler(myResponseListener)); }
From source file:com.barchart.netty.server.pipeline.NegotiationHandler.java
License:BSD License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof Capabilities) { ctx.writeAndFlush(new Capabilities() { @Override/*from w w w . j ava 2s .co m*/ public Set<String> capabilities() { return capabilities; } @Override public Version version() { return version; } @Override public Version minVersion() { return minVersion; } }); } else if (msg instanceof VersionRequest) { final VersionRequest request = (VersionRequest) msg; final Version v = request.version(); if (minVersion.lessThanOrEqual(v) && version.greaterThanOrEqual(v)) { activeVersion = v; ctx.writeAndFlush(new VersionResponse() { @Override public boolean success() { return true; } @Override public Version version() { return v; } }); } else { ctx.writeAndFlush(new VersionResponse() { @Override public boolean success() { return false; } @Override public Version version() { return version; } }); } } else if (msg instanceof StartTLS) { // TODO Use a specific SSL cert? final SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine(); sslEngine.setUseClientMode(false); final SslHandler handler = new SslHandler(sslEngine, true); handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { if (future.isSuccess()) { secure = true; } else { secure = false; // Failed, remove handler ctx.pipeline().remove(SslHandler.class); } } }); // Add SslHandler to pipeline ctx.pipeline().addFirst(handler); // Confirm start TLS, initiate handshake ctx.writeAndFlush(new StartTLS() { }); } else { ctx.fireChannelRead(msg); // First non-negotiation message, we're done - clean up pipeline if (cleanup) { ctx.pipeline().remove(this); if (linked != null) { for (final ChannelHandler handler : linked) { ctx.pipeline().remove(handler); } } } } }
From source file:com.barchart.netty.server.pipeline.StartTLSHandler.java
License:BSD License
@Override protected void channelRead0(final ChannelHandlerContext ctx, final StartTLS msg) throws Exception { // TODO Use a specific SSL cert? final SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine(); sslEngine.setUseClientMode(false);//ww w. j a v a 2s . c o m final SslHandler handler = new SslHandler(sslEngine, true); handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { if (future.isSuccess()) { secure = true; } else { secure = false; // Failed, remove handler ctx.pipeline().remove(SslHandler.class); } } }); // Add SslHandler to pipeline ctx.pipeline().addFirst(handler); // Confirm start TLS, initiate handshake ctx.writeAndFlush(new StartTLS() { }); }
From source file:com.basho.riak.client.core.netty.RiakSecurityDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext chc, ByteBuf in, List<Object> out) throws Exception { // Make sure we have 4 bytes if (in.readableBytes() >= 4) { in.markReaderIndex();/*www .j av a2s . com*/ int length = in.readInt(); // See if we have the full frame. if (in.readableBytes() < length) { in.resetReaderIndex(); } else { byte code = in.readByte(); byte[] protobuf = new byte[length - 1]; in.readBytes(protobuf); switch (state) { case TLS_WAIT: switch (code) { case RiakMessageCodes.MSG_StartTls: logger.debug("Received MSG_RpbStartTls reply"); // change state this.state = State.SSL_WAIT; // insert SSLHandler SslHandler sslHandler = new SslHandler(sslEngine); // get promise Future<Channel> hsFuture = sslHandler.handshakeFuture(); // register callback hsFuture.addListener(new SslListener()); // Add handler chc.channel().pipeline().addFirst(Constants.SSL_HANDLER, sslHandler); break; case RiakMessageCodes.MSG_ErrorResp: logger.debug("Received MSG_ErrorResp reply to startTls"); promise.tryFailure((riakErrorToException(protobuf))); break; default: promise.tryFailure( new RiakResponseException(0, "Invalid return code during StartTLS; " + code)); } break; case AUTH_WAIT: chc.channel().pipeline().remove(this); switch (code) { case RiakMessageCodes.MSG_AuthResp: logger.debug("Received MSG_RpbAuthResp reply"); promise.trySuccess(null); break; case RiakMessageCodes.MSG_ErrorResp: logger.debug("Received MSG_ErrorResp reply to auth"); promise.tryFailure(riakErrorToException(protobuf)); break; default: promise.tryFailure( new RiakResponseException(0, "Invalid return code during Auth; " + code)); } break; default: // WTF? logger.error("Received message while not in TLS_WAIT or AUTH_WAIT"); promise.tryFailure( new IllegalStateException("Received message while not in TLS_WAIT or AUTH_WAIT")); } } } }
From source file:com.github.ambry.rest.ConnectionStatsHandler.java
License:Open Source License
/** * Listen to the handshake future if this is an SSL connection. Log and update metrics if the handshake failed. * @param ctx the {@link ChannelHandlerContext}. *///from www .j a v a2 s .com private void logHandshakeStatus(ChannelHandlerContext ctx) { SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); if (sslHandler != null) { sslHandler.handshakeFuture().addListener(future -> { if (!future.isSuccess()) { logger.debug("SSL handshake failed for channel: {}", ctx.channel(), future.cause()); metrics.handshakeFailureCount.inc(); } }); } }
From source file:com.github.mrstampy.gameboot.otp.netty.client.ClientHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { SslHandler handler = ctx.pipeline().get(SslHandler.class); if (handler == null) return;//from www. j av a 2 s . c o m handler.handshakeFuture().addListener(f -> validate(f, ctx)); }
From source file:com.github.mrstampy.gameboot.otp.netty.OtpEncryptedNettyHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { SslHandler handler = ctx.pipeline().get(SslHandler.class); if (handler == null) { log.error("Unencrypted channels cannot process OTP New Key requests. Disconnecting {}", ctx.channel()); ctx.close();//w ww . j a va 2 s . c o m return; } handler.handshakeFuture().addListener(f -> validate(f, ctx)); }
From source file:com.hipishare.chat.server.handler.SecureChatHandler.java
License:Apache License
@Override public void channelActive(final ChannelHandlerContext ctx) { // Once session is secured, send a greeting and register the channel to the global channel // list so the channel received the messages from others. LOG.info("[]?channel"); SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); if (null != sslHandler) { sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override/*from w w w.jav a 2 s . c om*/ public void operationComplete(Future<Channel> future) throws Exception { if (future.isSuccess()) { LOG.info("SSL??"); channels.add(ctx.channel()); } } }); } }
From source file:com.linkedin.mitm.proxy.channel.ChannelMediator.java
License:Open Source License
/** * Create {@link io.netty.handler.ssl.SslHandler} and send TCP handshaking using * {@link javax.net.ssl.SSLEngine}/*from w ww .j a va 2 s. c o m*/ * After add ssl handler to the end of {@link io.netty.channel.ChannelPipeline}, it enable * secure communications over SSL/TLS * * @param isSslClient true if the channel start handshaking or false if accept handshaking * @param channel the channel to start handshaking * */ private Future<Channel> handshake(SSLEngine sslEngine, boolean isSslClient, Channel channel) { sslEngine.setUseClientMode(isSslClient); if (channel != null) { channel.config().setAutoRead(true); } SslHandler handler = new SslHandler(sslEngine); channel.pipeline().addFirst("ssl", handler); LOG.debug("About to start handshaking..."); return handler.handshakeFuture(); }
From source file:com.mobicage.rogerthat.plugins.news.NewsChannel.java
License:Apache License
public void connect() { if (TestUtils.isRunningTest()) { return;//ww w . ja v a 2 s.c o m } T.NEWS(); if (mIsConnected) { L.d("Already connected to news channel"); return; } else if (!mService.getNetworkConnectivityManager().isConnected()) { L.d("Cannot connect to news channel: no internet connection."); return; } else if (mHost == null) { L.d("Not connecting to news channel because no host was found"); return; } else if (mPort == -1) { L.d("Not connecting to news channel because no port was found"); return; } mIsRetryingToConnect = true; L.d("Attemping to connect to news channel..."); final SslContext sslCtx; if (CloudConstants.NEWS_CHANNEL_SSL) { try { if (CloudConstants.NEWS_CHANNEL_MUST_VALIDATE_SSL_CERTIFICATE) { TrustManagerFactory factory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("AndroidCAStore"); // Gets the default system keystore keyStore.load(null, null); factory.init(keyStore); sslCtx = SslContextBuilder.forClient().trustManager(factory).build(); } else { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); } } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) { L.bug(e); return; } } else { sslCtx = null; } if (mEventLoopGroup == null) { mEventLoopGroup = new NioEventLoopGroup(); } Bootstrap b = new Bootstrap(); b.group(mEventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), mHost, mPort); Future<Channel> handshakeDone = sslHandler.handshakeFuture(); handshakeDone.addListener(new GenericFutureListener<Future<? super Channel>>() { @Override public void operationComplete(Future<? super Channel> future) throws Exception { authenticate(); } }); p.addLast(sslHandler); } // decoder p.addLast(new DelimiterBasedFrameDecoder(102400, Delimiters.lineDelimiter())); p.addLast(new StringDecoder(Charset.forName("UTF-8"))); //encoder p.addLast(new StringEncoder(Charset.forName("UTF-8"))); p.addLast(NewsChannel.this); } }); // Bind and start to accept incoming connections. mChannel = b.connect(mHost, mPort).channel(); }