List of usage examples for io.netty.handler.ssl SslHandler engine
SSLEngine engine
To view the source code for io.netty.handler.ssl SslHandler engine.
Click Source Link
From source file:com.foilen.smalltools.net.netty.NettyServer.java
License:Open Source License
/** * Start the server.// w w w. j a v a 2s. com * * @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.linecorp.armeria.server.HttpServerHandler.java
License:Apache License
@Nullable private static SSLSession getSSLSession(Channel channel) { final SslHandler sslHandler = channel.pipeline().get(SslHandler.class); return sslHandler != null ? sslHandler.engine().getSession() : null; }
From source file:com.ning.http.client.providers.netty_4.NettyConnectListener.java
License:Apache License
public final void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { Channel channel = f.channel(); channel.pipeline().context(NettyAsyncHttpProvider.class).attr(NettyAsyncHttpProvider.DEFAULT_ATTRIBUTE) .set(future);//from w w w.ja v a 2 s.com SslHandler sslHandler = (SslHandler) channel.pipeline().get(NettyAsyncHttpProvider.SSL_HANDLER); if (!handshakeDone.getAndSet(true) && (sslHandler != null)) { ((SslHandler) channel.pipeline().get(NettyAsyncHttpProvider.SSL_HANDLER)).handshake() .addListener(this); return; } HostnameVerifier v = config.getHostnameVerifier(); if (sslHandler != null) { if (!v.verify(future.getURI().getHost(), sslHandler.engine().getSession())) { ConnectException exception = new ConnectException("HostnameVerifier exception."); future.abort(exception); throw exception; } } future.provider().writeRequest(f.channel(), config, future, nettyRequest); } else { Throwable cause = f.cause(); logger.debug("Trying to recover a dead cached channel {} with a retry value of {} ", f.channel(), future.canRetry()); if (future.canRetry() && cause != null && (NettyAsyncHttpProvider.abortOnDisconnectException(cause) || ClosedChannelException.class.isAssignableFrom(cause.getClass()) || future.getState() != NettyResponseFuture.STATE.NEW)) { logger.debug("Retrying {} ", nettyRequest); if (future.provider().remotelyClosed(f.channel(), future)) { return; } } logger.debug("Failed to recover from exception: {} with channel {}", cause, f.channel()); boolean printCause = f.cause() != null && cause.getMessage() != null; ConnectException e = new ConnectException( printCause ? cause.getMessage() + " to " + future.getURI().toString() : future.getURI().toString()); if (cause != null) { e.initCause(cause); } future.abort(e); } }
From source file:com.tc.websocket.server.handler.ProxyFrontendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) { ByteBuf buf = (ByteBuf) msg;//from w ww. jav a 2 s .com String data = new String(ByteBufUtil.getBytes(buf)); if (data.contains(Const.UPGRADE_WEBSOCKET) || data.contains(Const.GET_WEBSOCKET)) { proxy.set(false); } else if (data.contains(StringCache.HTTP_1_1)) { proxy.set(true); } if (proxy.get() == false) { writeToFile("frontend." + ctx.channel().id(), ByteBufUtil.getBytes(buf)); } if (Config.getInstance().isCertAuth()) { SslHandler sslhandler = (SslHandler) ctx.channel().pipeline().get("ssl"); try { X509Certificate cert = sslhandler.engine().getSession().getPeerCertificateChain()[0]; Principal p = cert.getSubjectDN(); /* Added by Miguel */ LdapName ldapDN = new LdapName(p.getName()); String username = ""; String thumbprint = getThumbPrint(cert.getEncoded()); for (Rdn rdn : ldapDN.getRdns()) { //System.out.println(rdn.getType() + " -> " + rdn.getValue()); if (rdn.getType().equals("CN")) { username = rdn.getValue().toString(); break; } } /* End Added by Miguel*/ String sessionId = parseSessionID(data); if (sessionId != null) { String current = System.getProperty("user.dir"); //System.out.println("Current working directory in Java : " + current); //File sessionFile = new File("c:/sessions/" + sessionId + ".txt"); File sessionFile = new File(current + "/data/sessions/" + sessionId + ".txt"); //only write the file if it hasn't been written yet. if (sessionFile.createNewFile()) { FileUtils.write(sessionFile, p.getName().replaceAll("\"", "").replaceAll("\\+", ",") + "\n" + username + "\n" + thumbprint); } } } catch (Exception e) { LOG.log(Level.SEVERE, null, e); } } if (proxy.get()) { ctx.channel().config().setAutoRead(false); if (outboundChannel.isActive()) { outboundChannel.writeAndFlush(buf).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // was able to flush out data, start to read the next chunk ctx.channel().read(); } else { future.channel().close(); } } }); } } else { //make sure the backend handler knows its a websocket connection. this.handler.setWebsocket(true); //get handle on the pipeline. ChannelPipeline pipeline = ctx.pipeline(); //apply the websocket handlers builder.apply(pipeline); //remove this handler. pipeline.remove(this); //fire the event to move on to the next handler. ctx.fireChannelRead(msg); } }
From source file:com.turo.pushy.apns.MockApnsServer.java
License:Open Source License
protected MockApnsServer(final SslContext sslContext, final EventLoopGroup eventLoopGroup) { this.bootstrap = new ServerBootstrap(); if (eventLoopGroup != null) { this.bootstrap.group(eventLoopGroup); this.shouldShutDownEventLoopGroup = false; } else {// ww w .j a va2 s . co m this.bootstrap.group(new NioEventLoopGroup(1)); this.shouldShutDownEventLoopGroup = true; } this.bootstrap.channel(SocketChannelClassUtil.getServerSocketChannelClass(this.bootstrap.config().group())); this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final SslHandler sslHandler = sslContext.newHandler(channel.alloc()); channel.pipeline().addLast(sslHandler); channel.pipeline() .addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) { @Override protected void configurePipeline(final ChannelHandlerContext context, final String protocol) throws Exception { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { AbstractMockApnsServerHandler.AbstractMockApnsServerHandlerBuilder handlerBuilder; try { final SSLSession sslSession = sslHandler.engine().getSession(); // This will throw an exception if the peer hasn't authenticated (i.e. we're expecting // token authentication). final String principalName = sslSession.getPeerPrincipal().getName(); final Pattern pattern = Pattern.compile(".*UID=([^,]+).*"); final Matcher matcher = pattern.matcher(principalName); final String baseTopic; if (matcher.matches()) { baseTopic = matcher.group(1); } else { throw new IllegalArgumentException( "Client certificate does not specify a base topic."); } final TlsAuthenticationMockApnsServerHandler.TlsAuthenticationMockApnsServerHandlerBuilder tlsAuthenticationHandlerBuilder = new TlsAuthenticationMockApnsServerHandler.TlsAuthenticationMockApnsServerHandlerBuilder(); tlsAuthenticationHandlerBuilder.baseTopic(baseTopic); handlerBuilder = tlsAuthenticationHandlerBuilder; } catch (final SSLPeerUnverifiedException e) { // No need for alarm; this is an expected case final TokenAuthenticationMockApnsServerHandler.TokenAuthenticationMockApnsServerHandlerBuilder tokenAuthenticationHandlerBuilder = new TokenAuthenticationMockApnsServerHandler.TokenAuthenticationMockApnsServerHandlerBuilder(); tokenAuthenticationHandlerBuilder.verificationKeysByKeyId( MockApnsServer.this.verificationKeysByKeyId); tokenAuthenticationHandlerBuilder.topicsByVerificationKey( MockApnsServer.this.topicsByVerificationKey); tokenAuthenticationHandlerBuilder.emulateExpiredFirstToken( MockApnsServer.this.emulateExpiredFirstToken); handlerBuilder = tokenAuthenticationHandlerBuilder; } context.pipeline().addLast(handlerBuilder .initialSettings(new Http2Settings().maxConcurrentStreams(8)) .emulateInternalErrors(MockApnsServer.this.emulateInternalErrors) .deviceTokenExpirationsByTopic( MockApnsServer.this.deviceTokenExpirationsByTopic) .build()); MockApnsServer.this.allChannels.add(context.channel()); } else { throw new IllegalStateException("Unexpected protocol: " + protocol); } } }); } }); }
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(); }/*www.j a v a 2s . c om*/ 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:com.vmware.dcp.common.http.netty.NettyHttpClientRequestHandler.java
License:Open Source License
private void parseRequestHeaders(ChannelHandlerContext ctx, Operation request, HttpRequest nettyRequest) { HttpHeaders headers = nettyRequest.headers(); String referer = headers.getAndRemoveAndConvert(HttpHeaderNames.REFERER); if (referer != null) { try {//w w w . j av a 2s . co m request.setReferer(new URI(referer)); } catch (URISyntaxException e) { setRefererFromSocketContext(ctx, request); } } else { setRefererFromSocketContext(ctx, request); } if (headers.isEmpty()) { return; } request.setKeepAlive(HttpHeaderUtil.isKeepAlive(nettyRequest)); if (HttpHeaderUtil.isContentLengthSet(nettyRequest)) { request.setContentLength(HttpHeaderUtil.getContentLength(nettyRequest)); } request.setContextId(headers.getAndRemoveAndConvert(Operation.CONTEXT_ID_HEADER)); String contentType = headers.getAndRemoveAndConvert(HttpHeaderNames.CONTENT_TYPE); if (contentType != null) { request.setContentType(contentType); } String cookie = headers.getAndRemoveAndConvert(HttpHeaderNames.COOKIE); if (cookie != null) { request.setCookies(CookieJar.decodeCookies(cookie)); } for (Entry<String, String> h : headers.entriesConverted()) { String key = h.getKey(); String value = h.getValue(); request.addRequestHeader(key, value); } // Add peer Principal and CertificateChain to operation in case if client was successfully authenticated // by Netty using client certificate SslHandler sslHandler = (SslHandler) ctx.channel().pipeline().get(NettyHttpServerInitializer.SSL_HANDLER); if (sslHandler != null) { try { if (sslHandler.engine().getWantClientAuth() || sslHandler.engine().getNeedClientAuth()) { SSLSession session = sslHandler.engine().getSession(); request.setPeerCertificates(session.getPeerPrincipal(), session.getPeerCertificateChain()); } } catch (Exception e) { this.host.log(Level.FINE, "Failed to get peer principal " + Utils.toString(e)); } } }
From source file:com.vmware.dcp.common.http.netty.NettyHttpServerInitializer.java
License:Open Source License
@Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline();/*from w w w . j ava 2 s . c o m*/ ch.config().setAllocator(NettyChannelContext.ALLOCATOR); ch.config().setSendBufferSize(NettyChannelContext.BUFFER_SIZE); ch.config().setReceiveBufferSize(NettyChannelContext.BUFFER_SIZE); if (this.sslContext != null) { SslHandler handler = this.sslContext.newHandler(ch.alloc()); SslClientAuthMode mode = this.host.getState().sslClientAuthMode; if (mode != null) { switch (mode) { case NEED: handler.engine().setNeedClientAuth(true); break; case WANT: handler.engine().setWantClientAuth(true); break; default: break; } } p.addLast(SSL_HANDLER, handler); } p.addLast(DECODER_HANDLER, new HttpRequestDecoder(MAX_INITIAL_LINE_LENGTH, MAX_HEADER_SIZE, MAX_CHUNK_SIZE)); p.addLast(ENCODER_HANDLER, new HttpResponseEncoder()); p.addLast(AGGREGATOR_HANDLER, new HttpObjectAggregator(NettyChannelContext.MAX_REQUEST_SIZE)); p.addLast(DCP_WEBSOCKET_HANDLER, new NettyWebSocketRequestHandler(this.host, ServiceUriPaths.CORE_WEB_SOCKET_ENDPOINT, ServiceUriPaths.WEB_SOCKET_SERVICE_PREFIX)); p.addLast(DCP_HANDLER, new NettyHttpClientRequestHandler(this.host)); }
From source file:com.vmware.xenon.common.http.netty.NettyHttpServerInitializer.java
License:Open Source License
/** * initChannel is called by Netty when a channel is first used. *//*from w ww . j ava2s. co m*/ @Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); ch.config().setAllocator(NettyChannelContext.ALLOCATOR); ch.config().setSendBufferSize(NettyChannelContext.BUFFER_SIZE); ch.config().setReceiveBufferSize(NettyChannelContext.BUFFER_SIZE); SslHandler sslHandler = null; if (this.sslContext != null) { sslHandler = this.sslContext.newHandler(ch.alloc()); SslClientAuthMode mode = this.host.getState().sslClientAuthMode; if (mode != null) { switch (mode) { case NEED: sslHandler.engine().setNeedClientAuth(true); break; case WANT: sslHandler.engine().setWantClientAuth(true); break; default: break; } } p.addLast(SSL_HANDLER, sslHandler); } // The HttpServerCodec combines the HttpRequestDecoder and the HttpResponseEncoder, and it // also provides a method for upgrading the protocol, which we use to support HTTP/2. It // also supports a couple other minor features (support for HEAD and CONNECT), which // probably don't matter to us. HttpServerCodec http1_codec = new HttpServerCodec(NettyChannelContext.MAX_INITIAL_LINE_LENGTH, NettyChannelContext.MAX_HEADER_SIZE, NettyChannelContext.MAX_CHUNK_SIZE, false); p.addLast(HTTP1_CODEC, http1_codec); if (this.sslContext == null) { // Today we only use HTTP/2 when SSL is disabled final HttpToHttp2ConnectionHandler connectionHandler = makeHttp2ConnectionHandler(); UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() { @Override public UpgradeCodec newUpgradeCodec(CharSequence protocol) { if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { return new Http2ServerUpgradeCodec(connectionHandler); } else { return null; } } }; // On upgrade, the upgradeHandler will remove the http1_codec and replace it // with the connectionHandler. Ideally we'd remove the aggregator (chunked transfer // isn't allowed in HTTP/2) and the WebSocket handler (we don't support it over HTTP/2 yet) // but we're not doing that yet. HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(http1_codec, upgradeCodecFactory); p.addLast(HTTP2_UPGRADE_HANDLER, upgradeHandler); } p.addLast(AGGREGATOR_HANDLER, new HttpObjectAggregator(this.responsePayloadSizeLimit)); p.addLast(WEBSOCKET_HANDLER, new NettyWebSocketRequestHandler(this.host, ServiceUriPaths.CORE_WEB_SOCKET_ENDPOINT, ServiceUriPaths.WEB_SOCKET_SERVICE_PREFIX)); p.addLast(HTTP_REQUEST_HANDLER, new NettyHttpClientRequestHandler(this.host, sslHandler, this.responsePayloadSizeLimit)); }
From source file:de.jpaw.bonaparte.netty.testServer.TestServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, BonaPortable request) throws Exception { // String cipher; SslHandler sslH = ctx.pipeline().get(SslHandler.class); if (sslH != null) { SSLSession session = sslH.engine().getSession(); // cipher = " (with cipher " + session.getCipherSuite() + ")"; SessionInfo.logSessionInfo(session, "Client"); } else {//from w ww .jav a 2 s . c o m // cipher = " (unencrypted)"; } // logger.info("Received an object of type " + request.getClass().getCanonicalName() + cipher); Request myRequest = (Request) request; Response myResponse = new Response(); myResponse.setSerialNo(myRequest.getSerialNo()); myResponse.setUniqueId(myRequest.getUniqueId()); myResponse.setThreadNo(thisThreadId); myResponse.setSerialInThread(0); // counterInThread.incrementAndGet()); => locking issue! myResponse.setWhenReceiced(new LocalDateTime()); if (myRequest.getDuration() > 0) { Thread.sleep(myRequest.getDuration()); } ctx.write(myResponse); ctx.flush(); }