if (!req.headers().containsValue(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true) || !HttpHeaderValues.WEBSOCKET.contentEqualsIgnoreCase(req.headers().get(HttpHeaderNames.UPGRADE))) { throw new WebSocketHandshakeException("not a WebSocket handshake request: missing upgrade"); boolean isHixie76 = req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY1) && req.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_KEY2); res.headers().add(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, req.headers().get(HttpHeaderNames.ORIGIN)); String subprotocols = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL); if (subprotocols != null) { String selectedSubprotocol = selectSubprotocol(subprotocols); if (selectedSubprotocol == null) { if (logger.isDebugEnabled()) { logger.debug("Requested subprotocol(s) not supported: {}", subprotocols); String key1 = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY1); String key2 = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_KEY2); int a = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key1).replaceAll("")) / BEGINNING_SPACE.matcher(key1).replaceAll("").length()); int b = (int) (Long.parseLong(BEGINNING_DIGIT.matcher(key2).replaceAll("")) / BEGINNING_SPACE.matcher(key2).replaceAll("").length()); long c = req.content().readLong(); ByteBuf input = Unpooled.buffer(16); input.writeInt(a); input.writeInt(b); res.headers().add(HttpHeaderNames.WEBSOCKET_ORIGIN, req.headers().get(HttpHeaderNames.ORIGIN));
@Override public void channelRead(final ChannelHandlerContext ctx, final Object mesg) throws Exception { if (mesg instanceof FullHttpRequest) { final FullHttpRequest req = (FullHttpRequest) mesg; if ((req.method() == HttpMethod.GET) && (PushProtocol.SSE.getPath().equals(req.uri()))) { ctx.pipeline().fireUserEventTriggered(PushProtocol.SSE.getHandshakeCompleteEvent()); final DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); final HttpHeaders headers = resp.headers(); headers.add("Connection", "keep-alive"); headers.add("Content-Type", "text/event-stream"); headers.add("Transfer-Encoding", "chunked"); final ChannelFuture cf = ctx.channel().writeAndFlush(resp); cf.addListener(future -> { if (future.isSuccess()) { ChannelPipeline pipeline = ctx.pipeline(); if (pipeline.get(HttpObjectAggregator.class) != null) { pipeline.remove(HttpObjectAggregator.class); } if (pipeline.get(HttpContentCompressor.class) != null) { pipeline.remove(HttpContentCompressor.class); } final String reconnetInterval = "retry: " + SSE_RETRY_BASE_INTERVAL.get() + "\r\n\r\n"; ctx.writeAndFlush(reconnetInterval); } }); } } }
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (wsUri.equalsIgnoreCase(request.getUri())) { ctx.fireChannelRead(request.retain()); } else { if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx); request.getProtocolVersion(), HttpResponseStatus.OK); response.headers().set( HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8"); boolean keepAlive = HttpHeaders.isKeepAlive(request); if (keepAlive) { response.headers().set( HttpHeaders.Values.KEEP_ALIVE); ctx.write(response); if (ctx.pipeline().get(SslHandler.class) == null) { ctx.write(new DefaultFileRegion( file.getChannel(), 0, file.length())); LastHttpContent.EMPTY_LAST_CONTENT); if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE);
@Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { ctx.channel().read(); } else { if (isNotSocketClosedException(future.cause())) { mockServerLogger.error("Exception while returning response for request \"" + request.method() + " " + request.uri() + "\"", future.cause()); } future.channel().close(); } } });
@Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } else { // Kept for compatibility ctx.fireUserEventTriggered( WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE); ctx.fireUserEventTriggered( new WebSocketServerProtocolHandler.HandshakeComplete( req.uri(), req.headers(), handshaker.selectedSubprotocol())); } } });
private void setBody(HttpRequest httpRequest, FullHttpRequest fullHttpRequest) { if (fullHttpRequest.content() != null && fullHttpRequest.content().readableBytes() > 0) { byte[] bodyBytes = new byte[fullHttpRequest.content().readableBytes()]; fullHttpRequest.content().readBytes(bodyBytes); if (bodyBytes.length > 0) { if (ContentTypeMapper.isBinary(fullHttpRequest.headers().get(CONTENT_TYPE))) { httpRequest.withBody(new BinaryBody(bodyBytes)); } else { Charset requestCharset = ContentTypeMapper.getCharsetFromContentTypeHeader(fullHttpRequest.headers().get(CONTENT_TYPE)); httpRequest.withBody(new StringBody(new String(bodyBytes, requestCharset), DEFAULT_HTTP_CHARACTER_SET.equals(requestCharset) ? null : requestCharset)); } } } } }
final FullHttpRequest req = (FullHttpRequest) msg; if ("/favicon.ico".equals(req.uri())) { sendError(ctx, NOT_FOUND, "Gremlin Server doesn't have a favicon.ico"); ReferenceCountUtil.release(msg); ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); if (req.method() != GET && req.method() != POST) { sendError(ctx, METHOD_NOT_ALLOWED, METHOD_NOT_ALLOWED.toString()); ReferenceCountUtil.release(msg); final String acceptString = Optional.ofNullable(req.headers().get("Accept")).orElse("application/json"); final Pair<String, MessageTextSerializer> serializer = chooseSerializer(acceptString); if (null == serializer) { final String origin = req.headers().get(ORIGIN); final boolean keepAlive = HttpUtil.isKeepAlive(req); final ChannelPromise promise = ctx.channel().newPromise(); final AtomicReference<Object> resultHolder = new AtomicReference<>(); promise.addListener(future -> { ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
ch = b.connect(host, port).syncUninterruptibly().channel(); final THttp2ClientHandler handler = initHandler.clientHandler; final FullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, path, Unpooled.wrappedBuffer(out.getArray(), 0, out.length())); request.headers().add(HttpHeaderNames.HOST, host); request.headers().set(ExtensionHeaderNames.SCHEME.text(), uri.getScheme()); request.headers().add(defaultHeaders); ch.writeAndFlush(request).sync(); final byte[] array = new byte[response.readableBytes()]; response.readBytes(array); in = new TMemoryInputTransport(array); response.release(); } catch (Exception e) { throw new TTransportException(TTransportException.UNKNOWN, e);
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); lastContentFuture.addListener(ChannelFutureListener.CLOSE);
SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.INVALID_STREAM); ctx.writeAndFlush(spdyRstStreamFrame); return; SpdyRstStreamFrame spdyRstStreamFrame = new DefaultSpdyRstStreamFrame(streamId, SpdyStreamStatus.PROTOCOL_ERROR); ctx.writeAndFlush(spdyRstStreamFrame); return; httpRequestWithEntity.headers().setInt(Names.STREAM_ID, streamId); httpRequestWithEntity.headers().setInt(Names.ASSOCIATED_TO_STREAM_ID, associatedToStreamId); httpRequestWithEntity.headers().setInt(Names.PRIORITY, spdySynStreamFrame.priority()); httpRequestWithEntity.headers().setInt(Names.STREAM_ID, streamId); httpResponseWithEntity.headers().setInt(Names.STREAM_ID, streamId); HttpUtil.setContentLength(fullHttpMessage, fullHttpMessage.content().readableBytes()); removeMessage(streamId); out.add(fullHttpMessage); if (content.readableBytes() > maxContentLength - spdyDataFrame.content().readableBytes()) { removeMessage(streamId); throw new TooLongFrameException(
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); lastContentFuture.addListener(ChannelFutureListener.CLOSE);
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception { ByteBuf buf = msg.content(); byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(0, bytes); YarRequest yarRequest = YarProtocol.buildRequest(bytes); YarResponse yarResponse = process(yarRequest); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(YarProtocol .toProtocolBytes(yarResponse))); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); if (HttpHeaders.isKeepAlive(msg)) { response.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE); } ctx.write(response); ctx.flush(); ctx.close(); }
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof UpgradeEvent) { // Generate the initial Http2Settings frame, // so that the next handler knows the protocol upgrade occurred as well. ctx.fireChannelRead(DEFAULT_HTTP2_SETTINGS); // Continue handling the upgrade request after the upgrade is complete. final FullHttpRequest nettyReq = ((UpgradeEvent) evt).upgradeRequest(); // Remove the headers related with the upgrade. nettyReq.headers().remove(HttpHeaderNames.CONNECTION); nettyReq.headers().remove(HttpHeaderNames.UPGRADE); nettyReq.headers().remove(Http2CodecUtil.HTTP_UPGRADE_SETTINGS_HEADER); if (logger.isDebugEnabled()) { logger.debug("{} Handling the pre-upgrade request ({}): {} {} {} ({}B)", ctx.channel(), ((UpgradeEvent) evt).protocol(), nettyReq.method(), nettyReq.uri(), nettyReq.protocolVersion(), nettyReq.content().readableBytes()); } channelRead(ctx, nettyReq); channelReadComplete(ctx); return; } ctx.fireUserEventTriggered(evt); } }
@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; clientFuture.addListener(cf -> { HttpResponseStatus status; if (cf.isSuccess()) {
@Override public Object handle(Channel channel, Object message) { FullHttpRequest httpRequest = (FullHttpRequest) message; String uri = httpRequest.getUri(); int index = uri.indexOf("?");// should not be null String requestPath = uri; String packagerName = "JSON"; try { ByteBuf buf = httpRequest.content(); final byte[] contentBytes = new byte[buf.readableBytes()]; buf.getBytes(0, contentBytes); YarRequest yarRequest = new AttachmentRequest(YarProtocol.buildRequest(contentBytes), attachments); yarRequest.setRequestPath(requestPath); new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(responseBytes)); httpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); httpResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, httpResponse.content().readableBytes()); if (HttpHeaders.isKeepAlive(httpRequest)) { httpResponse.headers().set(HttpHeaders.Names.CONNECTION, Values.KEEP_ALIVE); } else {
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { SchedulerKey key = new SchedulerKey(Type.PING_TIMEOUT, ctx.channel()); disconnectScheduler.cancel(key); if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; Channel channel = ctx.channel(); QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri()); if (!configuration.isAllowCustomRequests() && !queryDecoder.path().startsWith(connectPath)) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST); channel.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE); req.release(); return; } List<String> sid = queryDecoder.parameters().get("sid"); if (queryDecoder.path().equals(connectPath) && sid == null) { String origin = req.headers().get(HttpHeaderNames.ORIGIN); if (!authorize(ctx, channel, origin, queryDecoder.parameters(), req)) { req.release(); return; } // forward message to polling or websocket handler to bind channel } } ctx.fireChannelRead(msg); }
private void upgradeChannel(final ChannelHandlerContext ctx, FullHttpRequest httpRequest) { handshaker = new WebSocketServerHandshakerFactory( "ws://" + httpRequest.headers().get(HOST) + UPGRADE_CHANNEL_FOR_UI_WEB_SOCKET_URI, null, true, Integer.MAX_VALUE ).newHandshaker(httpRequest); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake( ctx.channel(), httpRequest, new DefaultHttpHeaders(), ctx.channel().newPromise() ).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { clientRegistry.put(ctx, request()); } }); } }
@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); }
final FullHttpRequest req = (FullHttpRequest) msg; if (isNotWebSocketPath(req)) { ctx.fireChannelRead(msg); return; if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; getWebSocketLocation(ctx.pipeline(), req, websocketPath), subprotocols, allowExtensions, maxFramePayloadSize, allowMaskMismatch); final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req); handshakeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { req.release();
final List<CharSequence> requestedProtocols = splitHeader(request.headers().get(HttpHeaderNames.UPGRADE)); final int numRequestedProtocols = requestedProtocols.size(); UpgradeCodec upgradeCodec = null; CharSequence connectionHeader = request.headers().get(HttpHeaderNames.CONNECTION); if (connectionHeader == null) { return false; if (!request.headers().contains(requiredHeader)) { return false; if (!upgradeCodec.prepareUpgradeResponse(ctx, request, upgradeResponse.headers())) { return false; final ChannelFuture writeComplete = ctx.writeAndFlush(upgradeResponse); ctx.pipeline().remove(HttpServerUpgradeHandler.this); ctx.fireUserEventTriggered(event.retain()); writeComplete.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } finally {