@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (!acceptForeignIp) { if (!((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().isLoopbackAddress()) { ByteBuf cb = Unpooled.wrappedBuffer((QosConstants.BR_STR + "Foreign Ip Not Permitted." + QosConstants.BR_STR).getBytes()); ctx.writeAndFlush(cb).addListener(ChannelFutureListener.CLOSE); } } } }
@Override public void run() { ctx.close(promise); } }, 10, TimeUnit.SECONDS); // FIXME: Magic number
@Override public synchronized void close() { // Close after all data is written chctx.write(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); chctx.flush(); }
@Override public void run() { if (welcome != null) { ctx.write(Unpooled.wrappedBuffer(welcome.getBytes())); ctx.writeAndFlush(Unpooled.wrappedBuffer(prompt.getBytes())); } }
@Override public ChannelFuture sendPushMessage(ChannelHandlerContext ctx, ByteBuf mesg) { final ByteBuf newBuff = ctx.alloc().buffer(); newBuff.ensureWritable(SSE_PREAMBLE.length()); newBuff.writeCharSequence(SSE_PREAMBLE, Charsets.UTF_8); newBuff.ensureWritable(mesg.writableBytes()); newBuff.writeBytes(mesg); newBuff.ensureWritable(SSE_TERMINATION.length()); newBuff.writeCharSequence(SSE_TERMINATION, Charsets.UTF_8); mesg.release(); return ctx.channel().writeAndFlush(newBuff); }
public final void sendHttpResponse(HttpRequest req, ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, status); resp.headers().add("Content-Length", "0"); final boolean closeConn = ((status != OK) || (! HttpUtil.isKeepAlive(req))); if (closeConn) { resp.headers().add(HttpHeaderNames.CONNECTION, "Close"); } final ChannelFuture cf = ctx.channel().writeAndFlush(resp); if (closeConn) { cf.addListener(ChannelFutureListener.CLOSE); } }
private void end(ChannelHandlerContext ctx, ByteBuf buf, boolean h2c) { if (current > 0) { ByteBuf msg = Unpooled.buffer(current + buf.readableBytes()); msg.writeBytes(HTTP_2_PREFACE_ARRAY, 0, current); msg.writeBytes(buf); buf.release(); buf = msg; } configure(ctx, h2c); ctx.pipeline().remove(this); ctx.fireChannelRead(buf); }
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { // Add a handler that just catches the Http2Exception that we fire to tell the codec to gracefully shutdown a connection. // We want to catch it so that it doesn't get logged by the DefaultChannelPipeline as if it was a _real_ // exception. ChannelPipeline parentPipeline = ctx.channel().parent().pipeline(); String handlerName = "h2_exception_swallow_handler"; if (parentPipeline.get(handlerName) == null) { parentPipeline.addLast(handlerName, SWALLOW_EXCEPTION_HANDLER); } }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { RequestState state = ctx.channel().attr(ATTR_REQ_STATE).get(); if (msg instanceof HttpResponse) { state.response = (HttpResponse) msg; state.responseBodySize = 0; } if (msg instanceof HttpContent) { state.responseBodySize += ((HttpContent) msg).content().readableBytes(); } super.write(ctx, msg, promise); } }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { if (maxConnections > 0) { int currentCount = connections.getAndIncrement(); if (currentCount + 1 > maxConnections) { LOG.warn("Throttling incoming connection as above configured max connections threshold of " + maxConnections); Channel channel = ctx.channel(); channel.attr(ATTR_CH_THROTTLED).set(Boolean.TRUE); CurrentPassport.fromChannel(channel).add(PassportState.SERVER_CH_THROTTLING); channel.close(); ctx.pipeline().fireUserEventTriggered(CONNECTION_THROTTLED_EVENT); } } super.channelActive(ctx); }
private void outputContent(ChannelHandlerContext ctx, FullHttpRequest request, int code, String content, String mimeType) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code), Unpooled.wrappedBuffer(content.getBytes(Charset.forName("UTF-8")))); response.headers().set(Names.CONTENT_TYPE, mimeType); response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes()); response.headers().set(Names.SERVER, SERVER_VS); ChannelFuture future = ctx.writeAndFlush(response); if (!HttpHeaders.isKeepAlive(request)) { future.addListener(ChannelFutureListener.CLOSE); } }
@Override public ChannelFuture sendPing(ChannelHandlerContext ctx) { final ByteBuf newBuff = ctx.alloc().buffer(); newBuff.ensureWritable(SSE_PING.length()); newBuff.writeCharSequence(SSE_PING, Charsets.UTF_8); return ctx.channel().writeAndFlush(newBuff); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { String clientIP = ctx.channel().attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get(); if (IPS.get().contains(clientIP)) { ctx.channel().attr(DynamicHttp2FrameLogger.ATTR_ENABLE).set(Boolean.TRUE); ctx.pipeline().remove(this); } } finally { super.channelRead(ctx, msg); } } }
@Override protected boolean accept(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) throws Exception { final InetAddress remoteIp = remoteAddress.getAddress(); if (!connected.add(remoteIp)) { return false; } else { ctx.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { connected.remove(remoteIp); } }); return true; } } }
private void requestClientToCloseConnection() { if (ctx.channel().isActive()) { // Application level protocol for asking client to close connection ctx.writeAndFlush(pushProtocol.goAwayMessage()); // Force close connection if client doesn't close in reasonable time after we made request ctx.executor().schedule(() -> forceCloseConnectionFromServerSide(), CLIENT_CLOSE_GRACE_PERIOD.get(), TimeUnit.SECONDS); } else { forceCloseConnectionFromServerSide(); } }
private ChannelFuture finishEncode(final ChannelHandlerContext ctx, ChannelPromise promise) { if (finished) { promise.setSuccess(); return promise; } finished = true; final ByteBuf footer = ctx.alloc().heapBuffer( compressor.maxCompressedLength(buffer.readableBytes()) + HEADER_LENGTH); flushBufferedData(footer); final int idx = footer.writerIndex(); footer.setLong(idx, MAGIC_NUMBER); footer.setByte(idx + TOKEN_OFFSET, (byte) (BLOCK_TYPE_NON_COMPRESSED | compressionLevel)); footer.setInt(idx + COMPRESSED_LENGTH_OFFSET, 0); footer.setInt(idx + DECOMPRESSED_LENGTH_OFFSET, 0); footer.setInt(idx + CHECKSUM_OFFSET, 0); footer.writerIndex(idx + HEADER_LENGTH); return ctx.writeAndFlush(footer, promise); }
protected static boolean fireCompleteEventIfNotAlready(ChannelHandlerContext ctx, CompleteReason reason) { // Only allow this method to run once per request. Attribute<State> attr = ctx.channel().attr(ATTR_STATE); State state = attr.get(); if (state == null || state != State.STARTED) return false; attr.set(State.COMPLETED); HttpRequest request = ctx.channel().attr(ATTR_HTTP_REQ).get(); HttpResponse response = ctx.channel().attr(ATTR_HTTP_RESP).get(); // Cleanup channel attributes. ctx.channel().attr(ATTR_HTTP_REQ).set(null); ctx.channel().attr(ATTR_HTTP_RESP).set(null); // Fire the event to whole pipeline. ctx.pipeline().fireUserEventTriggered(new CompleteEvent(reason, request, response)); return true; }
@Override protected final void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out) { int readableBytes = in.readableBytes(); if (!isValidHeader(readableBytes)) { return; } if (log.isDebugEnabled()) { log.debug("Read from client {} : \n {}", context.channel().id().asShortText(), ByteBufUtil.prettyHexDump(in)); } doDecode(context, in, out, readableBytes); }
private void writeErrorResponse(int statusCode, String message, ChannelHandlerContext ctx) { FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(statusCode), Unpooled.copiedBuffer(message, Charset.forName(SentinelConfig.charset()))); httpResponse.headers().set("Content-Type", "text/plain; charset=" + SentinelConfig.charset()); ctx.write(httpResponse); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }