List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:com.linecorp.armeria.server.http.HttpServerHandler.java
License:Apache License
private void handleHttp2Settings(ChannelHandlerContext ctx, Http2Settings h2settings) { if (h2settings.isEmpty()) { logger.trace("{} HTTP/2 settings: <empty>", ctx.channel()); } else {//from ww w. j a va 2 s . co m logger.debug("{} HTTP/2 settings: {}", ctx.channel(), h2settings); } switch (protocol) { case H1: protocol = SessionProtocol.H2; break; case H1C: protocol = SessionProtocol.H2C; break; } final Http2ConnectionHandler handler = ctx.pipeline().get(Http2ConnectionHandler.class); if (responseEncoder != null) { responseEncoder.close(); } responseEncoder = new Http2ObjectEncoder(handler.encoder()); }
From source file:com.linecorp.armeria.server.HttpServerHandler.java
License:Apache License
private void handleHttp2Settings(ChannelHandlerContext ctx, Http2Settings h2settings) { if (h2settings.isEmpty()) { logger.trace("{} HTTP/2 settings: <empty>", ctx.channel()); } else {/*from www .j av a 2 s . co m*/ logger.debug("{} HTTP/2 settings: {}", ctx.channel(), h2settings); } if (protocol == H1) { protocol = H2; } else if (protocol == H1C) { protocol = H2C; } final Http2ConnectionHandler handler = ctx.pipeline().get(Http2ConnectionHandler.class); if (responseEncoder == null) { responseEncoder = new Http2ObjectEncoder(handler.encoder()); } else if (responseEncoder instanceof Http1ObjectEncoder) { responseEncoder.close(); responseEncoder = new Http2ObjectEncoder(handler.encoder()); } }
From source file:com.linkedin.r2.transport.http.client.Http2AlpnHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { _alpnPromise = ctx.channel().newPromise(); /** Note: {@link SslHandler} will initiate a handshake upon being added to the pipeline. */ ctx.pipeline().addFirst("sslHandler", _sslHandler); }
From source file:com.linkedin.r2.transport.http.client.Http2AlpnHandler.java
License:Apache License
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt; if (handshakeEvent.isSuccess()) { LOG.debug("SSL handshake succeeded"); SslHandler sslHandler = ctx.pipeline().get(SslHandler.class); if (sslHandler == null) { ctx.fireExceptionCaught( new IllegalStateException("cannot find a SslHandler in the pipeline (required for " + "application-level protocol negotiation)")); return; }//from w w w . j ava 2s . com String protocol = sslHandler.applicationProtocol(); if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { LOG.debug("HTTP/2 is negotiated"); // Add HTTP/2 handler ctx.pipeline().addAfter("sslHandler", "http2Handler", _http2Handler); // Remove handler from pipeline after negotiation is complete ctx.pipeline().remove(this); _alpnPromise.setSuccess(); } else { LOG.error("Protocol {}, instead of HTTP/2, is negotiated through ALPN", protocol); _alpnPromise.setFailure(new IllegalStateException("HTTP/2 ALPN negotiation failed")); } } else { LOG.error("SSL handshake failed", handshakeEvent.cause()); _alpnPromise.setFailure(handshakeEvent.cause()); } } ctx.fireUserEventTriggered(evt); }
From source file:com.linkedin.r2.transport.http.client.Http2InitializerHandler.java
License:Apache License
/** * Sets up HTTP/2 over TCP through protocol upgrade (h2c) pipeline *///from w ww .j a v a2 s . c o m private void configureHttpPipeline(ChannelHandlerContext ctx, Request request) throws Exception { Http2StreamCodec http2Codec = new Http2StreamCodecBuilder().connection(_connection) .maxContentLength(_maxResponseSize).maxHeaderSize(_maxHeaderSize) .gracefulShutdownTimeoutMillis(_gracefulShutdownTimeout).streamingTimeout(_streamingTimeout) .scheduler(_scheduler).build(); HttpClientCodec sourceCodec = new HttpClientCodec(MAX_INITIAL_LINE_LENGTH, _maxHeaderSize, _maxChunkSize); Http2ClientUpgradeCodec targetCodec = new Http2ClientUpgradeCodec(http2Codec); HttpClientUpgradeHandler upgradeCodec = new HttpClientUpgradeHandler(sourceCodec, targetCodec, MAX_CLIENT_UPGRADE_CONTENT_LENGTH); Http2SchemeHandler schemeHandler = new Http2SchemeHandler(HttpScheme.HTTP.toString()); String host = request.getURI().getAuthority(); int port = request.getURI().getPort(); String path = request.getURI().getPath(); Http2UpgradeHandler upgradeHandler = new Http2UpgradeHandler(host, port, path); Http2StreamResponseHandler responseHandler = new Http2StreamResponseHandler(); Http2ChannelPoolHandler channelPoolHandler = new Http2ChannelPoolHandler(); ctx.pipeline().addBefore(ctx.name(), "sourceCodec", sourceCodec); ctx.pipeline().addBefore(ctx.name(), "upgradeCodec", upgradeCodec); ctx.pipeline().addBefore(ctx.name(), "upgradeHandler", upgradeHandler); ctx.pipeline().addBefore(ctx.name(), "schemeHandler", schemeHandler); ctx.pipeline().addBefore(ctx.name(), "responseHandler", responseHandler); ctx.pipeline().addBefore(ctx.name(), "channelHandler", channelPoolHandler); _setupComplete = true; }
From source file:com.linkedin.r2.transport.http.client.Http2InitializerHandler.java
License:Apache License
/** * Sets up HTTP/2 over TLS through ALPN (h2) pipeline */// w w w . ja va2s . c o m private void configureHttpsPipeline(ChannelHandlerContext ctx) throws Exception { JdkSslContext context = new JdkSslContext(_sslContext, IS_CLIENT, Arrays.asList(_sslParameters.getCipherSuites()), IdentityCipherSuiteFilter.INSTANCE, new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1), _sslParameters.getNeedClientAuth() ? ClientAuth.REQUIRE : ClientAuth.OPTIONAL); SslHandler sslHandler = context.newHandler(ctx.alloc()); Http2StreamCodec http2Codec = new Http2StreamCodecBuilder().connection(_connection) .maxContentLength(_maxResponseSize).maxHeaderSize(_maxHeaderSize) .gracefulShutdownTimeoutMillis(_gracefulShutdownTimeout).streamingTimeout(_streamingTimeout) .scheduler(_scheduler).build(); Http2AlpnHandler alpnHandler = new Http2AlpnHandler(sslHandler, http2Codec); Http2SchemeHandler schemeHandler = new Http2SchemeHandler(HttpScheme.HTTPS.toString()); Http2StreamResponseHandler responseHandler = new Http2StreamResponseHandler(); Http2ChannelPoolHandler channelPoolHandler = new Http2ChannelPoolHandler(); ctx.pipeline().addBefore(ctx.name(), "alpnHandler", alpnHandler); ctx.pipeline().addBefore(ctx.name(), "schemeHandler", schemeHandler); ctx.pipeline().addBefore(ctx.name(), "responseHandler", responseHandler); ctx.pipeline().addBefore(ctx.name(), "channelHandler", channelPoolHandler); _setupComplete = true; }
From source file:com.linkedin.r2.transport.http.client.Http2UpgradeHandler.java
License:Apache License
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { LOG.debug("Received user event {}", evt); if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_ISSUED) { LOG.debug("HTTP/2 clear text upgrade issued"); } else if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_SUCCESSFUL) { LOG.debug("HTTP/2 clear text upgrade successful"); } else if (evt == HttpClientUpgradeHandler.UpgradeEvent.UPGRADE_REJECTED) { LOG.error("HTTP/2 clear text upgrade failed"); _upgradePromise.setFailure(new IllegalStateException("HTTP/2 clear text upgrade failed")); } else if (evt == Http2FrameListener.FrameEvent.SETTINGS_FRAME_RECEIVED) { LOG.debug("HTTP/2 settings frame received"); // Remove handler from pipeline after upgrade is successful ctx.pipeline().remove(this); _upgradePromise.setSuccess();/*from ww w .j a v a 2 s . com*/ } ctx.fireUserEventTriggered(evt); }
From source file:com.linkedin.r2.transport.http.client.SslRequestHandler.java
License:Apache License
/** * Override this method to set the handlers for SSL connection the first time this channel * is used to make a request. Once used, the scheme of the request on this channel cannot be changed. *//*from w ww . ja va 2 s.co m*/ @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof Request) { Request request = (Request) msg; URI uri = request.getURI(); String scheme = uri.getScheme(); if (_firstTimeScheme == null) { // If this channel is configured for TLS AND this is an HTTPS request, add SSL // handler to the channel pipeline if (scheme.equalsIgnoreCase(HTTPS_SCHEME)) { if (_sslHandler == null) { throw new IllegalStateException("The client hasn't been configured with SSLContext " + "- cannot make an https request to " + uri); } /** Note: {@link SslHandler} will initiate a handshake upon being added to the pipeline. */ ctx.pipeline().addFirst(SSL_HANDLER, _sslHandler); } _firstTimeScheme = scheme; } else if (!scheme.equalsIgnoreCase(_firstTimeScheme)) { throw new IllegalStateException(String.format("Cannot switch scheme from %s to %s for %s", _firstTimeScheme, scheme, ctx.channel().remoteAddress())); } } ctx.write(msg, promise); }
From source file:com.look.netty.demo.socksproxy.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception { if (message instanceof Socks4CommandRequest) { final Socks4CommandRequest request = (Socks4CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override/*from w w w.j a v a 2 s .co m*/ public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel() .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS)); responseFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush( new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED)); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else if (message instanceof Socks5CommandRequest) { final Socks5CommandRequest request = (Socks5CommandRequest) message; Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ChannelFuture responseFuture = ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse( Socks5CommandStatus.SUCCESS, request.dstAddrType())); responseFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(SocksServerConnectHandler.this); outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); } }); } else { ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); } else { ctx.close(); } }
From source file:com.mapple.forward.socks.SocksServerHandlerEx.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, SocksMessage socksRequest) throws Exception { switch (socksRequest.version()) { case SOCKS4a: Socks4CommandRequest socksV4CmdRequest = (Socks4CommandRequest) socksRequest; if (socksV4CmdRequest.type() == Socks4CommandType.CONNECT) { ctx.pipeline().addLast(SocksServerConnectHandlerEx.INSTANCE); ctx.pipeline().remove(this); ctx.fireChannelRead(socksRequest); } else {//from w w w . jav a 2 s . c om ctx.close(); } break; case SOCKS5: if (socksRequest instanceof Socks5InitialRequest) { // auth support example ctx.pipeline().addFirst(new Socks5PasswordAuthRequestDecoder()); ctx.write(new DefaultSocks5InitialResponse(Socks5AuthMethod.PASSWORD)); // ctx.pipeline().addFirst(new Socks5CommandRequestDecoder()); // ctx.write(new DefaultSocks5InitialResponse(Socks5AuthMethod.NO_AUTH)); } else if (socksRequest instanceof Socks5PasswordAuthRequest) { ctx.pipeline().addFirst(new Socks5CommandRequestDecoder()); Socks5PasswordAuthRequest request = (Socks5PasswordAuthRequest) socksRequest; // System.out.println("Socks5:" + request.username() + " " + request.password()); AttributeKey<String> SOCKS5 = AttributeKey.valueOf("socks5"); ctx.channel().attr(SOCKS5).set(request.username()); ctx.write(new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.SUCCESS)); } else if (socksRequest instanceof Socks5CommandRequest) { /*Socks5InitialRequestDecoder handle = ctx.pipeline().get(Socks5InitialRequestDecoder.class); if(handle != null) { System.out.println("LWZ Remove" + handle); ctx.pipeline().remove(handle); }*/ Socks5CommandRequest socks5CmdRequest = (Socks5CommandRequest) socksRequest; if (socks5CmdRequest.type() == Socks5CommandType.CONNECT) { ctx.pipeline().addLast(SocksServerConnectHandlerEx.INSTANCE); ctx.pipeline().remove(this); ctx.fireChannelRead(socksRequest); } else { ctx.close(); } } else { ctx.close(); } break; case UNKNOWN: ctx.close(); break; } }