private HttpMessage invalidMessage(ByteBuf in, Exception cause) { currentState = State.BAD_MESSAGE; // Advance the readerIndex so that ByteToMessageDecoder does not complain // when we produced an invalid message without consuming anything. in.skipBytes(in.readableBytes()); if (message != null) { message.setDecoderResult(DecoderResult.failure(cause)); } else { message = createInvalidMessage(); message.setDecoderResult(DecoderResult.failure(cause)); } HttpMessage ret = message; message = null; return ret; }
@Test public void testBadChunk() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new HttpRequestDecoder()); ch.writeInbound(Unpooled.copiedBuffer("GET / HTTP/1.0\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("Transfer-Encoding: chunked\r\n\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("BAD_LENGTH\r\n", CharsetUtil.UTF_8)); HttpRequest req = (HttpRequest) ch.readInbound(); assertTrue(req.getDecoderResult().isSuccess()); LastHttpContent chunk = (LastHttpContent) ch.readInbound(); DecoderResult dr = chunk.getDecoderResult(); assertFalse(dr.isSuccess()); assertTrue(dr.isFailure()); ensureInboundTrafficDiscarded(ch); }
@Test public void testBadChunk() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new HttpRequestDecoder()); ch.writeInbound(Unpooled.copiedBuffer("GET / HTTP/1.0\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("Transfer-Encoding: chunked\r\n\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("BAD_LENGTH\r\n", CharsetUtil.UTF_8)); HttpRequest req = (HttpRequest) ch.readInbound(); assertTrue(req.getDecoderResult().isSuccess()); HttpContent chunk = (HttpContent) ch.readInbound(); DecoderResult dr = chunk.getDecoderResult(); assertFalse(dr.isSuccess()); assertTrue(dr.isFailure()); ensureInboundTrafficDiscarded(ch); }
@Test public void testBadChunk() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new HttpRequestDecoder()); ch.writeInbound(Unpooled.copiedBuffer("GET / HTTP/1.0\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("Transfer-Encoding: chunked\r\n\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("BAD_LENGTH\r\n", CharsetUtil.UTF_8)); HttpRequest req = ch.readInbound(); assertTrue(req.getDecoderResult().isSuccess()); HttpContent chunk = ch.readInbound(); DecoderResult dr = chunk.getDecoderResult(); assertFalse(dr.isSuccess()); assertTrue(dr.isFailure()); ensureInboundTrafficDiscarded(ch); }
public MqttMessage( MqttFixedHeader fixedHeader, Object variableHeader, Object payload, DecoderResult decoderResult) { this.fixedHeader = fixedHeader; this.variableHeader = variableHeader; this.payload = payload; this.decoderResult = decoderResult; }
public MqttMessage( MqttFixedHeader mqttFixedHeader, Object variableHeader, Object payload, DecoderResult decoderResult) { this.mqttFixedHeader = mqttFixedHeader; this.variableHeader = variableHeader; this.payload = payload; this.decoderResult = decoderResult; }
private static void appendDecoderResult(StringBuilder buf, HttpObject o) { DecoderResult result = o.getDecoderResult(); if (result.isSuccess()) { return; } buf.append(".. WITH DECODER FAILURE: "); buf.append(result.cause()); buf.append("\r\n"); }
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception { DecoderResult result = httpRequest.decoderResult(); if (!result.isSuccess()) { throw new BadRequestException(result.cause()); } logger.info("Get search request: " + httpRequest.uri()); // only decode get path is enough Map<String, List<String>> requestParameters; QueryStringDecoder stringDecoder = new QueryStringDecoder(httpRequest.uri()); requestParameters = stringDecoder.parameters(); QueryMeta meta = new QueryMeta(); for(Map.Entry<String, List<String>> entry : requestParameters.entrySet()) { if (entry.getKey().equals("options[]")) { // add filters List<String> filters = entry.getValue(); filters.forEach(filter -> { String[] typeVal = filter.split(":"); meta.addMeta(typeVal[0], typeVal[1]); }); } else if (entry.getKey().equals("orderby")) { meta.setOrderBy(entry.getValue().get(0)); } else { logger.warn("Unknown query parameter, ignore it:" + entry.toString()); } } DecodedSearchRequest searchRequest = new DecodedSearchRequest(httpRequest, meta, orderNumber++); ctx.fireChannelRead(searchRequest); }
@Test public void doChannelRead_HttpRequest_throws_exception_when_failed_decoder_result() { // given HttpRequest msgMock = mock(HttpRequest.class); DecoderResult decoderResult = mock(DecoderResult.class); doReturn(true).when(decoderResult).isFailure(); doReturn(decoderResult).when(msgMock).getDecoderResult(); // when Throwable thrownException = Assertions.catchThrowable(() -> handler.doChannelRead(ctxMock, msgMock)); // then assertThat(thrownException).isExactlyInstanceOf(InvalidHttpRequestException.class); }
@Test public void doChannelRead_HttpContent_throws_exception_when_failed_decoder_result() { // given DecoderResult decoderResult = mock(DecoderResult.class); doReturn(true).when(decoderResult).isFailure(); doReturn(decoderResult).when(httpContentMock).getDecoderResult(); // when Throwable thrownException = Assertions.catchThrowable(() -> handler.doChannelRead(ctxMock, httpContentMock)); // then assertThat(thrownException).isExactlyInstanceOf(InvalidHttpRequestException.class); verify(httpContentMock).release(); }
@Override final public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg == null || msg == Unpooled.EMPTY_BUFFER || msg instanceof EmptyByteBuf) { return; } try { ChannelOperations<?, ?> ops = ChannelOperations.get(ctx.channel()); if (ops != null) { ops.onInboundNext(ctx, msg); } else { if (log.isDebugEnabled()) { String loggingMsg = msg.toString(); if (msg instanceof HttpResponse) { DecoderResult decoderResult = ((HttpResponse) msg).decoderResult(); if (decoderResult.isFailure()) { log.debug("Decoding failed: " + msg + " : ", decoderResult.cause()); } } if (msg instanceof ByteBufHolder) { loggingMsg = ((ByteBufHolder) msg).content() .toString(Charset.defaultCharset()); } log.debug("{} No ChannelOperation attached. Dropping: {}", ctx .channel().toString(), loggingMsg); } ReferenceCountUtil.release(msg); } } catch (Throwable err) { Exceptions.throwIfFatal(err); exceptionCaught(ctx, err); ReferenceCountUtil.safeRelease(msg); } }
private static void appendDecoderResult(StringBuilder buf, HttpObject o) { DecoderResult result = o.decoderResult(); if (result.isSuccess()) { return; } buf.append(".. WITH DECODER FAILURE: "); buf.append(result.cause()); buf.append("\r\n"); }
private HttpContent invalidChunk(ByteBuf in, Exception cause) { currentState = State.BAD_MESSAGE; // Advance the readerIndex so that ByteToMessageDecoder does not complain // when we produced an invalid message without consuming anything. in.skipBytes(in.readableBytes()); HttpContent chunk = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER); chunk.setDecoderResult(DecoderResult.failure(cause)); message = null; trailer = null; return chunk; }
@Override public void setDecoderResult(DecoderResult decoderResult) { if (decoderResult == null) { throw new NullPointerException("decoderResult"); } this.decoderResult = decoderResult; }
@Test public void testRequestWithBadInitialLine() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new HttpRequestDecoder()); ch.writeInbound(Unpooled.copiedBuffer("GET / HTTP/1.0 with extra\r\n", CharsetUtil.UTF_8)); HttpRequest req = (HttpRequest) ch.readInbound(); DecoderResult dr = req.getDecoderResult(); assertFalse(dr.isSuccess()); assertTrue(dr.isFailure()); ensureInboundTrafficDiscarded(ch); }
@Test public void testRequestWithBadHeader() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new HttpRequestDecoder()); ch.writeInbound(Unpooled.copiedBuffer("GET /maybe-something HTTP/1.0\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("Good_Name: Good Value\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("Bad=Name: Bad Value\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("\r\n", CharsetUtil.UTF_8)); HttpRequest req = (HttpRequest) ch.readInbound(); DecoderResult dr = req.getDecoderResult(); assertFalse(dr.isSuccess()); assertTrue(dr.isFailure()); assertEquals("Good Value", req.headers().get("Good_Name")); assertEquals("/maybe-something", req.getUri()); ensureInboundTrafficDiscarded(ch); }
@Test public void testResponseWithBadInitialLine() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder()); ch.writeInbound(Unpooled.copiedBuffer("HTTP/1.0 BAD_CODE Bad Server\r\n", CharsetUtil.UTF_8)); HttpResponse res = (HttpResponse) ch.readInbound(); DecoderResult dr = res.getDecoderResult(); assertFalse(dr.isSuccess()); assertTrue(dr.isFailure()); ensureInboundTrafficDiscarded(ch); }
@Test public void testResponseWithBadHeader() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new HttpResponseDecoder()); ch.writeInbound(Unpooled.copiedBuffer("HTTP/1.0 200 Maybe OK\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("Good_Name: Good Value\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("Bad=Name: Bad Value\r\n", CharsetUtil.UTF_8)); ch.writeInbound(Unpooled.copiedBuffer("\r\n", CharsetUtil.UTF_8)); HttpResponse res = (HttpResponse) ch.readInbound(); DecoderResult dr = res.getDecoderResult(); assertFalse(dr.isSuccess()); assertTrue(dr.isFailure()); assertEquals("Maybe OK", res.getStatus().reasonPhrase()); assertEquals("Good Value", res.headers().get("Good_Name")); ensureInboundTrafficDiscarded(ch); }
@Test public void testFullHttpRequestUpload() throws Exception { final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "http://localhost"); req.setDecoderResult(DecoderResult.SUCCESS); req.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); req.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); // Force to use memory-based data. final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false); for (String data : Arrays.asList("", "\r", "\r\r", "\r\r\r")) { final String body = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" + "Content-Type: image/gif\r\n" + "\r\n" + data + "\r\n" + "--" + boundary + "--\r\n"; req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8)); } // Create decoder instance to test. final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req); assertFalse(decoder.getBodyHttpDatas().isEmpty()); decoder.destroy(); }
@Test public void testQuotedBoundary() throws Exception { final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; final DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "http://localhost"); req.setDecoderResult(DecoderResult.SUCCESS); req.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data; boundary=\"" + boundary + '"'); req.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); // Force to use memory-based data. final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false); for (String data : Arrays.asList("", "\r", "\r\r", "\r\r\r")) { final String body = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" + "Content-Type: image/gif\r\n" + "\r\n" + data + "\r\n" + "--" + boundary + "--\r\n"; req.content().writeBytes(body.getBytes(CharsetUtil.UTF_8)); } // Create decoder instance to test. final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req); assertFalse(decoder.getBodyHttpDatas().isEmpty()); decoder.destroy(); }
private HttpMessage invalidMessage(Exception cause) { checkpoint(State.BAD_MESSAGE); if (message != null) { message.setDecoderResult(DecoderResult.failure(cause)); } else { message = createInvalidMessage(); message.setDecoderResult(DecoderResult.failure(cause)); } return message; }
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception { DecoderResult result = httpObject.getDecoderResult(); if (!result.isSuccess()) { throw new BadRequestException(result.cause()); } Attribute<UUID> sessionUuidAttr = ctx.channel().attr(AbstractNettyServer.UUID_KEY); if (httpObject instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) httpObject; LOG.trace("Session: {} got valid HTTP request:\n{}", sessionUuidAttr.get().toString(), httpRequest.headers().toString()); if (httpRequest.getMethod().equals(HttpMethod.POST)) { String uri = httpRequest.getUri(); AbstractCommand cp = (AbstractCommand) commandFactory.getCommandProcessor(uri); cp.setSessionUuid(sessionUuidAttr.get()); cp.setRequest(httpRequest); cp.parse(); ctx.fireChannelRead(cp); } else { LOG.error("Got invalid HTTP method: expecting only POST"); throw new BadRequestException( "Incorrect method " + httpRequest.getMethod().toString() + ", expected POST" ); } } else { LOG.warn("Session: {} got invalid HTTP object:\n{}", sessionUuidAttr.get().toString(), httpObject); } }
private HttpObject createHttpRequestMock(HttpMethod httpMethod, boolean isSuccessfulResult, Class requestClazz) { DecoderResult result = mock(DecoderResult.class); when(result.isSuccess()).thenReturn(isSuccessfulResult); HttpObject httpRequest = (HttpObject) mock(requestClazz); when(httpRequest.getDecoderResult()).thenReturn(result); HttpHeaders headers = mock(HttpHeaders.class); when(headers.toString()).thenReturn("Some header"); if (requestClazz.equals(HttpRequest.class)) { when(((HttpRequest) httpRequest).getMethod()).thenReturn(httpMethod); when(((HttpRequest) httpRequest).headers()).thenReturn(headers); } return httpRequest; }