private void serveContent(ChannelHandlerContext ctx, FullHttpRequest request) { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST); return; if (request.method() != HttpMethod.GET) { return; response.headers().set(CONTENT_TYPE, "text/html"); response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); ByteBuf buf = ctx.alloc().buffer(content.length()); buf.writeBytes(content.getBytes()); ctx.write(buf); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
ctx.channel().attr(ATTR_LAST_CONTENT_RECEIVED).set(Boolean.TRUE); if (clientRequest.decoderResult().isFailure()) { String errorMsg = "Invalid http request. " + "clientRequest = " + clientRequest.toString() + ", uri = " + String.valueOf(clientRequest.uri()) + ", info = " + ChannelUtils.channelInfoForLogging(ctx.channel()); String causeMsg = String.valueOf(clientRequest.decoderResult().cause()); final ZuulException ze = new ZuulException(errorMsg, causeMsg, true); ze.setStatusCode(400); ctx.fireChannelRead(zuulRequest);
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 String toString() { if (isFinished()) { if (isSuccess()) { return "success"; } String cause = cause().toString(); return new StringBuilder(cause.length() + 17) .append("failure(") .append(cause) .append(')') .toString(); } else { return "unfinished"; } } }
private Throwable validateMessage(Object msg) { if (msg instanceof HttpObject) { HttpObject obj = (HttpObject) msg; DecoderResult result = obj.decoderResult(); if (result.isFailure()) { return result.cause(); } else if (obj instanceof HttpResponse) { io.netty.handler.codec.http.HttpVersion version = ((HttpResponse) obj).protocolVersion(); if (version != io.netty.handler.codec.http.HttpVersion.HTTP_1_0 && version != io.netty.handler.codec.http.HttpVersion.HTTP_1_1) { return new IllegalStateException("Unsupported HTTP version: " + version); } } } return null; }
Object continueResponse = newContinueResponse(m, maxContentLength, ctx.pipeline()); if (continueResponse != null) { handlingOversizedMessage = ignoreContentAfterContinueResponse(continueResponse); final ChannelFuture future = ctx.writeAndFlush(continueResponse).addListener(listener); if (m instanceof DecoderResultProvider && !((DecoderResultProvider) m).decoderResult().isSuccess()) { O aggregated; if (m instanceof ByteBufHolder) { aggregated = beginAggregation(m, ((ByteBufHolder) m).content().retain()); } else { aggregated = beginAggregation(m, EMPTY_BUFFER); CompositeByteBuf content = ctx.alloc().compositeBuffer(maxCumulationBufferComponents); if (m instanceof ByteBufHolder) { appendPartialContent(content, ((ByteBufHolder) m).content()); final C m = (C) msg; if (content.readableBytes() > maxContentLength - m.content().readableBytes()) { if (m instanceof DecoderResultProvider) { DecoderResult decoderResult = ((DecoderResultProvider) m).decoderResult(); if (!decoderResult.isSuccess()) { if (currentMessage instanceof DecoderResultProvider) { ((DecoderResultProvider) currentMessage).setDecoderResult( DecoderResult.failure(decoderResult.cause()));
if (msg instanceof HttpRequest) { final HttpRequest nettyReq = (HttpRequest) msg; if (!nettyReq.decoderResult().isSuccess()) { fail(id, HttpResponseStatus.BAD_REQUEST); return; final String contentLengthStr = nettyHeaders.get(HttpHeaderNames.CONTENT_LENGTH); final boolean contentEmpty; if (contentLengthStr != null) { ctx.pipeline().fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE); fail(id, HttpResponseStatus.EXPECTATION_FAILED); return; nettyHeaders.set(ExtensionHeaderNames.SCHEME.text(), scheme); final HttpContent content = (HttpContent) msg; final DecoderResult decoderResult = content.decoderResult(); if (!decoderResult.isSuccess()) { fail(id, HttpResponseStatus.BAD_REQUEST); req.close(new ProtocolViolationException(decoderResult.cause())); return; req.write(new ByteBufHttpData(data.retain(), false)); if (!trailingHeaders.isEmpty()) { req.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; if ("/".equals(req.getUri()) || "/favicon.ico".equals(req.getUri())) { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); return; FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, "application/javascript"); setContentLength(res, content.readableBytes()); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req);
private void serveStatic(ChannelHandlerContext ctx, FullHttpRequest request, StaticFile staticFile) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST); return; if (request.method() != HttpMethod.GET) { return; String uri = request.uri(); String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty() && !(staticFile instanceof NoCacheStaticFile)) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); .set(CONTENT_LENGTH, fileLength) .set(CONTENT_TYPE, ContentTypeUtil.getContentType(file.getName())) .set(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); ctx.write(response); if (ctx.pipeline().get(SslHandler.class) == null) { ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } // Allow only GET methods. if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the index page if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) { ByteBuf content = getContent(); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); HttpUtil.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); } ctx.pipeline().remove(this); }
if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; final String uriString = req.uri(); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); HttpUtil.setContentLength(res, content.readableBytes()); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
frame = new DefaultStompHeadersSubframe(command); frame.setDecoderResult(DecoderResult.failure(e)); out.add(frame); checkpoint(State.BAD_FRAME); in.skipBytes(actualReadableBytes()); return; toRead = remainingLength; ByteBuf chunkBuffer = readBytes(ctx.alloc(), in, toRead); if ((alreadyReadChunkSize += toRead) >= contentLength) { lastContent = new DefaultLastStompContentSubframe(chunkBuffer); int nulIndex = indexOf(in, in.readerIndex(), in.writerIndex(), StompConstants.NUL); if (nulIndex == in.readerIndex()) { checkpoint(State.FINALIZE_FRAME_READ); toRead = in.writerIndex() - in.readerIndex(); ByteBuf chunkBuffer = readBytes(ctx.alloc(), in, toRead); alreadyReadChunkSize += toRead; if (nulIndex > 0) { errorContent.setDecoderResult(DecoderResult.failure(e)); out.add(errorContent); checkpoint(State.BAD_FRAME);
@Override protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendHttpResponse(ctx, request, BAD_REQUEST, null); return; final String path = request.uri(); if (path == null) { sendHttpResponse(ctx, request, BAD_REQUEST, null); logPushAttempt(); final HttpMethod method = request.method(); if ((method != HttpMethod.POST) && (method != HttpMethod.GET)) { sendHttpResponse(ctx, request, METHOD_NOT_ALLOWED, null); final ByteBuf body = request.content().retain(); if (body.readableBytes() <= 0) { sendHttpResponse(ctx, request, NO_CONTENT, userAuth); return;
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // 如果HTTP解码失败,返回HHTP异常 if (!req.getDecoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } // 构造握手响应返回,本机测试 WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( "ws://localhost:8080/websocket", null, false); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory .sendUnsupportedWebSocketVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } }
if (msg instanceof FullHttpRequest) { FullHttpRequest nettyRequest = (FullHttpRequest) msg; if (!nettyRequest.decoderResult().isSuccess()) { throw new BadRequestException("Netty Decoder Failed"); content.writeBytes(response.getRawContent(), response.getRawContent().available()); DefaultFullHttpResponse nettyResponse = new DefaultFullHttpResponse( NettyUtils.convertHttpVersion(response.getHttpVersion()), HttpResponseStatus.valueOf(response.getResponseCode()), ); for (Map.Entry<String, String> pair : response.getHeaders().entrySet()) { nettyResponse.headers().set(pair.getKey(), pair.getValue()); nettyResponse.headers().add(HttpHeaderNames.SET_COOKIE, cookie.getKey().toHeaderString(cookie.getValue())); ChannelFuture future = ctx.writeAndFlush(nettyResponse); if (!request.isKeepAlive()) { future.addListener(ChannelFutureListener.CLOSE);
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { if (!WEBSOCKET_PATH.equalsIgnoreCase(req.getUri()) || !req.headers().contains(HttpHeaders.UPGRADE) || req.getMethod() != GET) { //if the web socket path doesn't match then it's a normal GET request super.channelRead0(ctx, req); return; } // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } try { // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(req), null, false); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } } catch (WebSocketHandshakeException wshe) { super.channelRead0(ctx, req); } }
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } if (!WEB_SOCKET_PATH.equals(req.getUri())) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(req), null, true); handshake = wsFactory.newHandshaker(req); if (handshake == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshake.handshake(ctx.channel(), req); } }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof HttpObject)) { ctx.fireChannelRead(msg); return; final HttpResponse nettyRes = (HttpResponse) msg; final DecoderResult decoderResult = nettyRes.decoderResult(); if (!decoderResult.isSuccess()) { fail(ctx, new ProtocolViolationException(decoderResult.cause())); return; final HttpContent content = (HttpContent) msg; final DecoderResult decoderResult = content.decoderResult(); if (!decoderResult.isSuccess()) { fail(ctx, new ProtocolViolationException(decoderResult.cause())); return; final int dataLength = data.readableBytes(); if (dataLength > 0) { assert res != null; if (!trailingHeaders.isEmpty()) { res.write(ArmeriaHttpUtil.toArmeria(trailingHeaders)); ctx.close();
private void writeResponse(StringBuilder respone, HttpObject current, ChannelHandlerContext ctx) { if (respone != null) { boolean keepAlive = HttpUtil.isKeepAlive(request); FullHttpResponse response = new DefaultFullHttpResponse( HTTP_1_1, current == null ? OK : current.decoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(respone.toString(), GATEWAY_OPTION_CHARSET)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=GBK"); if (keepAlive) { response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ctx.write(response); } }
@Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception { if (!fullHttpRequest.getDecoderResult().isSuccess()) { sendError(channelHandlerContext, BAD_REQUEST); return; response.headers().add(name, value); channelHandlerContext.write(response); ChannelFuture writeFuture = channelHandlerContext.writeAndFlush(new ChunkedStream(contentStream)); writeFuture.addListener(ChannelFutureListener.CLOSE);