List of usage examples for io.netty.channel ChannelHandlerContext fireChannelRead
@Override ChannelHandlerContext fireChannelRead(Object msg);
From source file:com.linecorp.armeria.server.Http1RequestDecoder.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof HttpObject)) { ctx.fireChannelRead(msg); return;//from www . ja v a2 s.c o m } // this.req can be set to null by fail(), so we keep it in a local variable. DecodedHttpRequest req = this.req; try { if (discarding) { return; } if (req == null) { if (msg instanceof HttpRequest) { final HttpRequest nettyReq = (HttpRequest) msg; if (!nettyReq.decoderResult().isSuccess()) { fail(ctx, HttpResponseStatus.BAD_REQUEST); return; } final HttpHeaders nettyHeaders = nettyReq.headers(); final int id = ++receivedRequests; // Validate the method. if (!HttpMethod.isSupported(nettyReq.method().name())) { fail(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } // Validate the 'content-length' header. final String contentLengthStr = nettyHeaders.get(HttpHeaderNames.CONTENT_LENGTH); final boolean contentEmpty; if (contentLengthStr != null) { final long contentLength; try { contentLength = Long.parseLong(contentLengthStr); } catch (NumberFormatException ignored) { fail(ctx, HttpResponseStatus.BAD_REQUEST); return; } if (contentLength < 0) { fail(ctx, HttpResponseStatus.BAD_REQUEST); return; } contentEmpty = contentLength == 0; } else { contentEmpty = true; } nettyHeaders.set(ExtensionHeaderNames.SCHEME.text(), scheme); this.req = req = new DecodedHttpRequest(ctx.channel().eventLoop(), id, 1, ArmeriaHttpUtil.toArmeria(nettyReq), HttpUtil.isKeepAlive(nettyReq), inboundTrafficController, cfg.defaultMaxRequestLength()); // Close the request early when it is sure that there will be // neither content nor trailing headers. if (contentEmpty && !HttpUtil.isTransferEncodingChunked(nettyReq)) { req.close(); } ctx.fireChannelRead(req); } else { fail(ctx, HttpResponseStatus.BAD_REQUEST); return; } } if (req != null && msg instanceof HttpContent) { final HttpContent content = (HttpContent) msg; final DecoderResult decoderResult = content.decoderResult(); if (!decoderResult.isSuccess()) { fail(ctx, HttpResponseStatus.BAD_REQUEST); req.close(new ProtocolViolationException(decoderResult.cause())); return; } final ByteBuf data = content.content(); final int dataLength = data.readableBytes(); if (dataLength != 0) { req.increaseTransferredBytes(dataLength); final long maxContentLength = req.maxRequestLength(); if (maxContentLength > 0 && req.transferredBytes() > maxContentLength) { fail(ctx, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE); req.close(ContentTooLargeException.get()); return; } if (req.isOpen()) { req.write(new ByteBufHttpData(data.retain(), false)); } } if (msg instanceof LastHttpContent) { final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders(); if (!trailingHeaders.isEmpty()) { req.write(ArmeriaHttpUtil.toArmeria(trailingHeaders)); } req.close(); this.req = req = null; } } } catch (URISyntaxException e) { fail(ctx, HttpResponseStatus.BAD_REQUEST); if (req != null) { req.close(e); } } catch (Throwable t) { fail(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); if (req != null) { req.close(t); } else { logger.warn("Unexpected exception:", t); } } finally { ReferenceCountUtil.release(msg); } }
From source file:com.linecorp.armeria.server.Http2RequestDecoder.java
License:Apache License
@Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endOfStream) throws Http2Exception { DecodedHttpRequest req = requests.get(streamId); if (req == null) { // Validate the method. final CharSequence method = headers.method(); if (method == null) { writeErrorResponse(ctx, streamId, HttpResponseStatus.BAD_REQUEST); return; }//from ww w . j a v a 2 s. c om if (!HttpMethod.isSupported(method.toString())) { writeErrorResponse(ctx, streamId, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } // Validate the 'content-length' header if exists. final boolean contentEmpty; if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { final long contentLength = headers.getLong(HttpHeaderNames.CONTENT_LENGTH, -1L); if (contentLength < 0) { writeErrorResponse(ctx, streamId, HttpResponseStatus.BAD_REQUEST); return; } contentEmpty = contentLength == 0; } else { contentEmpty = true; } req = new DecodedHttpRequest(ctx.channel().eventLoop(), ++nextId, streamId, ArmeriaHttpUtil.toArmeria(headers), true, inboundTrafficController, cfg.defaultMaxRequestLength()); // Close the request early when it is sure that there will be // neither content nor trailing headers. if (contentEmpty && endOfStream) { req.close(); } requests.put(streamId, req); ctx.fireChannelRead(req); } else { try { req.write(ArmeriaHttpUtil.toArmeria(headers)); } catch (Throwable t) { req.close(t); throw connectionError(INTERNAL_ERROR, t, "failed to consume a HEADERS frame"); } } if (endOfStream) { req.close(); } }
From source file:com.linkedin.r2.transport.http.client.Http2FrameListener.java
License:Apache License
@Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endOfStream) throws Http2Exception { LOG.debug("Received HTTP/2 HEADERS frame, stream={}, end={}, headers={}, padding={}bytes", new Object[] { streamId, endOfStream, headers.size(), padding }); // Ignores response for the upgrade request if (streamId == Http2CodecUtil.HTTP_UPGRADE_STREAM_ID) { return;//w w w . j a va2 s . c om } final StreamResponseBuilder builder = new StreamResponseBuilder(); // Process HTTP/2 pseudo headers if (headers.status() != null) { builder.setStatus(Integer.parseInt(headers.status().toString())); } if (headers.authority() != null) { builder.addHeaderValue(HttpHeaderNames.HOST.toString(), headers.authority().toString()); } // Process other HTTP headers for (Map.Entry<CharSequence, CharSequence> header : headers) { if (Http2Headers.PseudoHeaderName.isPseudoHeader(header.getKey())) { // Do no set HTTP/2 pseudo headers to response continue; } final String key = header.getKey().toString(); final String value = header.getValue().toString(); if (key.equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) { builder.addCookie(value); } else { builder.unsafeAddHeaderValue(key, value); } } // Gets async pool handle from stream properties Http2Connection.PropertyKey handleKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CHANNEL_POOL_HANDLE_ATTR_KEY).get(); TimeoutAsyncPoolHandle<?> handle = _connection.stream(streamId).removeProperty(handleKey); if (handle == null) { _lifecycleManager.onError(ctx, Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR, "No channel pool handle is associated with this stream", streamId)); return; } final StreamResponse response; if (endOfStream) { response = builder.build(EntityStreams.emptyStream()); ctx.fireChannelRead(handle); } else { // Associate an entity stream writer to the HTTP/2 stream final TimeoutBufferedWriter writer = new TimeoutBufferedWriter(ctx, streamId, _maxContentLength, handle); if (_connection.stream(streamId).setProperty(_writerKey, writer) != null) { _lifecycleManager.onError(ctx, Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR, "Another writer has already been associated with current stream ID", streamId)); return; } // Prepares StreamResponse for the channel pipeline EntityStream entityStream = EntityStreams.newEntityStream(writer); response = builder.build(entityStream); } // Gets callback from stream properties Http2Connection.PropertyKey callbackKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CALLBACK_ATTR_KEY).get(); TransportCallback<?> callback = _connection.stream(streamId).removeProperty(callbackKey); if (callback != null) { ctx.fireChannelRead(new ResponseWithCallback<Response, TransportCallback<?>>(response, callback)); } }
From source file:com.linkedin.r2.transport.http.client.Http2StreamCodec.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (!(msg instanceof RequestWithCallback)) { ctx.write(msg, promise);/*w w w .java 2s. c o m*/ return; } Request request = ((RequestWithCallback) msg).request(); Http2ConnectionEncoder encoder = encoder(); int streamId = connection().local().incrementAndGetNextStreamId(); if (request instanceof StreamRequest) { LOG.debug("Writing StreamRequest..."); StreamRequest streamRequest = (StreamRequest) request; Http2Headers http2Headers = NettyRequestAdapter.toHttp2Headers(streamRequest); BufferedReader reader = new BufferedReader(ctx, encoder, streamId, ((RequestWithCallback) msg).handle()); streamRequest.getEntityStream().setReader(reader); encoder.writeHeaders(ctx, streamId, http2Headers, NO_PADDING, NOT_END_STREAM, promise) .addListener(future -> reader.request()); LOG.debug("Sent HTTP/2 HEADERS frame, stream={}, end={}, headers={}, padding={}bytes", new Object[] { streamId, NOT_END_STREAM, http2Headers.size(), NO_PADDING }); } else if (request instanceof RestRequest) { LOG.debug("Writing RestRequest..."); PromiseCombiner promiseCombiner = new PromiseCombiner(); ChannelPromise headersPromise = ctx.channel().newPromise(); ChannelPromise dataPromise = ctx.channel().newPromise(); promiseCombiner.add(headersPromise); promiseCombiner.add(dataPromise); promiseCombiner.finish(promise); RestRequest restRequest = (RestRequest) request; Http2Headers headers = NettyRequestAdapter.toHttp2Headers(restRequest); encoder.writeHeaders(ctx, streamId, headers, NO_PADDING, NOT_END_STREAM, headersPromise); LOG.debug("Sent HTTP/2 HEADERS frame, stream={}, end={}, headers={}, padding={}bytes", new Object[] { streamId, NOT_END_STREAM, headers.size(), NO_PADDING }); ByteBuf data = Unpooled.wrappedBuffer(restRequest.getEntity().asByteBuffer()); encoder.writeData(ctx, streamId, data, NO_PADDING, END_STREAM, dataPromise); LOG.debug("Sent HTTP/2 DATA frame, stream={}, end={}, data={}bytes, padding={}bytes", new Object[] { streamId, END_STREAM, data.readableBytes(), NO_PADDING }); } else { // Request type is not supported. Returns channel back to the pool and throws exception. ctx.fireChannelRead(((RequestWithCallback) msg).handle()); throw new IllegalArgumentException("Request is neither StreamRequest or RestRequest"); } // Sets TransportCallback as a stream property to be retrieved later TransportCallback<?> callback = ((RequestWithCallback) msg).callback(); Http2Connection.PropertyKey callbackKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CALLBACK_ATTR_KEY).get(); connection().stream(streamId).setProperty(callbackKey, callback); // Sets AsyncPoolHandle as a stream property to be retrieved later AsyncPoolHandle<?> handle = ((RequestWithCallback) msg).handle(); Http2Connection.PropertyKey handleKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CHANNEL_POOL_HANDLE_ATTR_KEY).get(); connection().stream(streamId).setProperty(handleKey, handle); }
From source file:com.linkedin.r2.transport.http.client.Http2StreamCodec.java
License:Apache License
private void doHandleStreamException(Http2Stream stream, ChannelHandlerContext ctx, Throwable cause) { Http2Connection.PropertyKey callbackKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CALLBACK_ATTR_KEY).get(); Http2Connection.PropertyKey handleKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CHANNEL_POOL_HANDLE_ATTR_KEY).get(); // Invokes the call back with error TimeoutTransportCallback<StreamResponse> callback = stream.removeProperty(callbackKey); if (callback != null) { callback.onResponse(//from w w w . ja v a2s.c om TransportResponseImpl.<StreamResponse>error(cause, Collections.<String, String>emptyMap())); } // Signals to dispose the channel back to the pool TimeoutAsyncPoolHandle<Channel> handle = stream.removeProperty(handleKey); if (handle != null) { ctx.fireChannelRead(handle.error()); } }
From source file:com.linkedin.r2.transport.http.client.Http2StreamResponseHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ResponseWithCallback) { @SuppressWarnings("unchecked") ResponseWithCallback<StreamResponse, TransportCallback<StreamResponse>> responseWithCallback = (ResponseWithCallback<StreamResponse, TransportCallback<StreamResponse>>) msg; StreamResponse response = responseWithCallback.response(); TransportCallback<StreamResponse> callback = responseWithCallback.callback(); Map<String, String> headers = new HashMap<>(response.getHeaders()); Map<String, String> wireAttrs = new HashMap<>(WireAttributeHelper.removeWireAttributes(headers)); StreamResponse newResponse = new StreamResponseBuilder(response).unsafeSetHeaders(headers) .build(response.getEntityStream()); LOG.debug("{}: handling a response", ctx.channel().remoteAddress()); callback.onResponse(TransportResponseImpl.success(newResponse, wireAttrs)); }//from w w w . j av a 2 s. c om ctx.fireChannelRead(msg); }
From source file:com.linkedin.r2.transport.http.client.RAPResponseDecoder.java
License:Apache License
@Override protected void channelRead0(final ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpResponse) { HttpResponse m = (HttpResponse) msg; _shouldCloseConnection = !HttpUtil.isKeepAlive(m); if (HttpUtil.is100ContinueExpected(m)) { ctx.writeAndFlush(CONTINUE).addListener(new ChannelFutureListener() { @Override//from w ww .j a v a 2s . co m public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } } }); } if (!m.decoderResult().isSuccess()) { ctx.fireExceptionCaught(m.decoderResult().cause()); return; } // remove chunked encoding. if (HttpUtil.isTransferEncodingChunked(m)) { HttpUtil.setTransferEncodingChunked(m, false); } Timeout<None> timeout = ctx.channel().attr(TIMEOUT_ATTR_KEY).getAndRemove(); if (timeout == null) { LOG.debug("dropped a response after channel inactive or exception had happened."); return; } final TimeoutBufferedWriter writer = new TimeoutBufferedWriter(ctx, _maxContentLength, BUFFER_HIGH_WATER_MARK, BUFFER_LOW_WATER_MARK, timeout); EntityStream entityStream = EntityStreams.newEntityStream(writer); _chunkedMessageWriter = writer; StreamResponseBuilder builder = new StreamResponseBuilder(); builder.setStatus(m.status().code()); for (Map.Entry<String, String> e : m.headers()) { String key = e.getKey(); String value = e.getValue(); if (key.equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) { builder.addCookie(value); } else { builder.unsafeAddHeaderValue(key, value); } } ctx.fireChannelRead(builder.build(entityStream)); } else if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) msg; TimeoutBufferedWriter currentWriter = _chunkedMessageWriter; // Sanity check if (currentWriter == null) { throw new IllegalStateException("received " + HttpContent.class.getSimpleName() + " without " + HttpResponse.class.getSimpleName()); } if (!chunk.decoderResult().isSuccess()) { this.exceptionCaught(ctx, chunk.decoderResult().cause()); } currentWriter.processHttpChunk(chunk); if (chunk instanceof LastHttpContent) { _chunkedMessageWriter = null; if (_shouldCloseConnection) { ctx.fireChannelRead(ChannelPoolStreamHandler.CHANNEL_DESTROY_SIGNAL); } else { ctx.fireChannelRead(ChannelPoolStreamHandler.CHANNEL_RELEASE_SIGNAL); } } } else { // something must be wrong, but let's proceed so that // handler after us has a chance to process it. ctx.fireChannelRead(msg); } }
From source file:com.linkedin.r2.transport.http.client.RAPResponseHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, RestResponse response) throws Exception { final Map<String, String> headers = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); final Map<String, String> wireAttrs = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); headers.putAll(response.getHeaders()); wireAttrs.putAll(WireAttributeHelper.removeWireAttributes(headers)); final RestResponse newResponse = new RestResponseBuilder(response).unsafeSetHeaders(headers).build(); // In general there should always be a callback to handle a received message, // but it could have been removed due to a previous exception or closure on the // channel// ww w . ja va 2s. c o m TransportCallback<RestResponse> callback = ctx.channel().attr(CALLBACK_ATTR_KEY).getAndRemove(); if (callback != null) { LOG.debug("{}: handling a response", ctx.channel().remoteAddress()); callback.onResponse(TransportResponseImpl.success(newResponse, wireAttrs)); } else { LOG.debug("{}: dropped a response", ctx.channel().remoteAddress()); } ctx.fireChannelRead(response); }
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 . j a va 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; } }
From source file:com.mapple.socksproxy.SocksServerHandler.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(new SocksServerConnectHandler()); ctx.pipeline().remove(this); ctx.fireChannelRead(socksRequest); } else {//from ww w . ja va 2s . c om ctx.close(); } break; case SOCKS5: if (socksRequest instanceof Socks5InitialRequest) { // auth support example //ctx.pipeline().addFirst(new Socks5PasswordAuthRequestDecoder()); //ctx.write(new DefaultSocks5AuthMethodResponse(Socks5AuthMethod.PASSWORD)); ctx.pipeline().addFirst(new Socks5CommandRequestDecoder()); ctx.write(new DefaultSocks5InitialResponse(Socks5AuthMethod.NO_AUTH)); } else if (socksRequest instanceof Socks5PasswordAuthRequest) { ctx.pipeline().addFirst(new Socks5CommandRequestDecoder()); 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(new SocksServerConnectHandler()); ctx.pipeline().remove(this); ctx.fireChannelRead(socksRequest); } else { ctx.close(); } } else { ctx.close(); } break; case UNKNOWN: ctx.close(); break; } }