List of usage examples for io.netty.handler.ssl SslHandler SslHandler
public SslHandler(SSLEngine engine, Executor delegatedTaskExecutor)
From source file:com.allanbank.mongodb.netty.NettyChannelInit.java
License:Apache License
/** * {@inheritDoc}/* w w w .jav a 2s. c o m*/ * <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 av a2s .c om 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);//from w w w .j ava 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.mongodb.connection.netty.NettyStream.java
License:Apache License
@Override public void openAsync(final AsyncCompletionHandler<Void> handler) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup);/*w ww . jav a 2 s .c o m*/ bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, settings.getConnectTimeout(MILLISECONDS)); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_KEEPALIVE, settings.isKeepAlive()); if (settings.getReceiveBufferSize() > 0) { bootstrap.option(ChannelOption.SO_RCVBUF, settings.getReceiveBufferSize()); } if (settings.getSendBufferSize() > 0) { bootstrap.option(ChannelOption.SO_SNDBUF, settings.getSendBufferSize()); } bootstrap.option(ChannelOption.ALLOCATOR, allocator); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel ch) throws Exception { if (sslSettings.isEnabled()) { SSLEngine engine = SSLContext.getDefault().createSSLEngine(address.getHost(), address.getPort()); engine.setUseClientMode(true); if (!sslSettings.isInvalidHostNameAllowed()) { engine.setSSLParameters(enableHostNameVerification(engine.getSSLParameters())); } ch.pipeline().addFirst("ssl", new SslHandler(engine, false)); } ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(settings.getReadTimeout(MILLISECONDS), MILLISECONDS)); ch.pipeline().addLast(new InboundBufferHandler()); } }); final ChannelFuture channelFuture = bootstrap.connect(address.getHost(), address.getPort()); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { channel = channelFuture.channel(); handler.completed(null); } else { handler.failed(future.cause()); } } }); }
From source file:com.zextras.modules.chat.server.xmpp.netty.ChatXmppService.java
License:Open Source License
private ServerBootstrap buildBoostrap(EventLoopGroup acceptorGroup, EventLoopGroup workerGroup, final SSLContext zimbraSSLContext, final boolean oldSSL) { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(acceptorGroup, workerGroup); serverBootstrap.channel(NioServerSocketChannel.class); ChannelHandler handler = new ChannelInitializer<SocketChannel>() { @Override/*from ww w . j ava 2s . c om*/ public void initChannel(SocketChannel ch) throws Exception { try { if (oldSSL) { final SSLEngine engine = zimbraSSLContext.createSSLEngine(); engine.setUseClientMode(false); ch.pipeline().addFirst(null, "SSL", new SslHandler(engine, false)); } ch.pipeline().addLast(null, "SubTagTokenizer", new XmlSubTagTokenizer()); FirstTags firstTagsHandler = new FirstTags(mXmppHandlerFactory, mEventManager, ch, mSchemaProvider, zimbraSSLContext, oldSSL, mChatProperties, mNettyService, mProxyAuthRequestEncoder, mXmppEventFilter, mXmppFilterOut); ch.pipeline().addAfter("SubTagTokenizer", "FirstTags", firstTagsHandler); } catch (Throwable ex) { ChatLog.log.warn("Unable to initialize XMPP connection: " + Utils.exceptionToString(ex)); ch.close(); } } }; serverBootstrap.childHandler(handler).option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 0); return serverBootstrap; }
From source file:diskCacheV111.doors.NettyLineBasedDoor.java
License:Open Source License
protected void start(ChannelHandlerContext ctx) throws Exception { LineWriter writer = ctx::writeAndFlush; clientAddress = remoteAddress.getAddress().getHostAddress(); LOGGER.debug("Client host: {}", clientAddress); interpreter = factory.create(this, getNucleus().getThisAddress(), remoteAddress, proxyAddress, localAddress, writer, executor, poolManager, idResolverFactory, spaceDescriptionCache, spaceLookupCache); if (interpreter instanceof CellCommandListener) { addCommandListener(interpreter); }//from w w w.j a v a 2 s .c om if (interpreter instanceof CellMessageReceiver) { addMessageListener((CellMessageReceiver) interpreter); } if (interpreter instanceof TlsStarter) { ((TlsStarter) interpreter).setTlsStarter(e -> { e.setUseClientMode(false); ctx.pipeline().addFirst("tls", new SslHandler(e, true)); }); } start().get(); // Blocking to prevent that we process any commands before the cell is alive }
From source file:io.grpc.netty.ProtocolNegotiatorsTest.java
License:Apache License
@Test public void tlsHandler_userEventTriggeredSslEvent_unsupportedProtocol() throws Exception { SslHandler badSslHandler = new SslHandler(engine, false) { @Override/*from w ww . j a va 2 s . c om*/ public String applicationProtocol() { return "badprotocol"; } }; ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext); pipeline.addLast(handler); final AtomicReference<Throwable> error = new AtomicReference<>(); ChannelHandler errorCapture = new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { error.set(cause); } }; pipeline.addLast(errorCapture); pipeline.replace(SslHandler.class, null, badSslHandler); channelHandlerCtx = pipeline.context(handler); Object sslEvent = SslHandshakeCompletionEvent.SUCCESS; pipeline.fireUserEventTriggered(sslEvent); // No h2 protocol was specified, so there should be an error, (normally handled by WBAEH) assertThat(error.get()).hasMessageThat().contains("Unable to find compatible protocol"); ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler); assertNull(grpcHandlerCtx); }
From source file:io.grpc.netty.ProtocolNegotiatorsTest.java
License:Apache License
@Test public void tlsHandler_userEventTriggeredSslEvent_supportedProtocolH2() throws Exception { SslHandler goodSslHandler = new SslHandler(engine, false) { @Override//from w w w .j av a 2s . c o m public String applicationProtocol() { return "h2"; } }; ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext); pipeline.addLast(handler); pipeline.replace(SslHandler.class, null, goodSslHandler); channelHandlerCtx = pipeline.context(handler); Object sslEvent = SslHandshakeCompletionEvent.SUCCESS; pipeline.fireUserEventTriggered(sslEvent); assertTrue(channel.isOpen()); ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler); assertNotNull(grpcHandlerCtx); }
From source file:io.grpc.netty.ProtocolNegotiatorsTest.java
License:Apache License
@Test public void tlsHandler_userEventTriggeredSslEvent_supportedProtocolGrpcExp() throws Exception { SslHandler goodSslHandler = new SslHandler(engine, false) { @Override/*from w ww . j a v a 2s . c o m*/ public String applicationProtocol() { return "grpc-exp"; } }; ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext); pipeline.addLast(handler); pipeline.replace(SslHandler.class, null, goodSslHandler); channelHandlerCtx = pipeline.context(handler); Object sslEvent = SslHandshakeCompletionEvent.SUCCESS; pipeline.fireUserEventTriggered(sslEvent); assertTrue(channel.isOpen()); ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler); assertNotNull(grpcHandlerCtx); }
From source file:org.jdiameter.client.impl.transport.tls.netty.StartTlsClientHandler.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*w w w . j a v a 2s . c o m*/ public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { logger.debug("StartTlsClientHandler"); ByteBuf buf = (ByteBuf) msg; byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(buf.readerIndex(), bytes); if ("StartTlsResponse".equals(new String(bytes))) { logger.debug("received StartTlsResponse"); SslContext sslContext = SslContextFactory.getSslContextForClient(this.tlsTransportClient.getConfig()); SSLEngine sslEngine = sslContext.newEngine(ctx.alloc()); sslEngine.setUseClientMode(true); SslHandler sslHandler = new SslHandler(sslEngine, false); final ChannelPipeline pipeline = ctx.pipeline(); pipeline.remove("startTlsClientHandler"); pipeline.addLast("sslHandler", sslHandler); logger.debug("StartTls starting handshake"); sslHandler.handshakeFuture().addListener(new GenericFutureListener() { @Override public void operationComplete(Future future) throws Exception { if (future.isSuccess()) { logger.debug("StartTls handshake succesfull"); tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN); logger.debug("restoring all handlers"); pipeline.addLast("decoder", new DiameterMessageDecoder( StartTlsClientHandler.this.tlsTransportClient.getParent(), StartTlsClientHandler.this.tlsTransportClient.getParser())); pipeline.addLast("msgHandler", new DiameterMessageHandler( StartTlsClientHandler.this.tlsTransportClient.getParent(), true)); pipeline.addLast("encoder", new DiameterMessageEncoder( StartTlsClientHandler.this.tlsTransportClient.getParser())); pipeline.addLast("inbandWriter", new InbandSecurityHandler()); } } }); } }