|
| 1 | +package ua.nanit.limbo.connection.pipeline; |
| 2 | + |
| 3 | +import io.netty.buffer.ByteBuf; |
| 4 | +import io.netty.channel.ChannelHandlerContext; |
| 5 | +import io.netty.channel.ChannelInboundHandlerAdapter; |
| 6 | +import org.jetbrains.annotations.NotNull; |
| 7 | +import ua.nanit.limbo.server.Logger; |
| 8 | + |
| 9 | +public class ChannelTrafficHandler extends ChannelInboundHandlerAdapter { |
| 10 | + |
| 11 | + private final int packetSize; |
| 12 | + private final int packetsPerSec; |
| 13 | + private final int bytesPerSec; |
| 14 | + |
| 15 | + private int packetsCounter; |
| 16 | + private int bytesCounter; |
| 17 | + |
| 18 | + private long lastPacket; |
| 19 | + |
| 20 | + public ChannelTrafficHandler(int packetSize, int packetsPerSec, int bytesPerSec) { |
| 21 | + this.packetSize = packetSize; |
| 22 | + this.packetsPerSec = packetsPerSec; |
| 23 | + this.bytesPerSec = bytesPerSec; |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public void channelRead(@NotNull ChannelHandlerContext ctx, @NotNull Object msg) throws Exception { |
| 28 | + if (msg instanceof ByteBuf) { |
| 29 | + ByteBuf in = (ByteBuf) msg; |
| 30 | + int bytes = in.readableBytes(); |
| 31 | + |
| 32 | + System.out.println(bytes + " bytes"); |
| 33 | + |
| 34 | + if (packetSize > 0 && bytes > packetSize) { |
| 35 | + closeConnection(ctx, "Closed %s due too large packet size (%d bytes)", ctx.channel().remoteAddress(), bytes); |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + if (!measureTraffic(ctx, bytes)) return; |
| 40 | + } |
| 41 | + |
| 42 | + super.channelRead(ctx, msg); |
| 43 | + } |
| 44 | + |
| 45 | + private boolean measureTraffic(ChannelHandlerContext ctx, int bytes) { |
| 46 | + if (packetsPerSec < 0 && bytesPerSec < 0) return true; |
| 47 | + |
| 48 | + long time = System.currentTimeMillis(); |
| 49 | + |
| 50 | + if (time - lastPacket >= 1000) { |
| 51 | + bytesCounter = 0; |
| 52 | + packetsCounter = 0; |
| 53 | + } |
| 54 | + |
| 55 | + packetsCounter++; |
| 56 | + bytesCounter += bytes; |
| 57 | + |
| 58 | + if (packetsPerSec > 0 && packetsCounter > packetsPerSec) { |
| 59 | + closeConnection(ctx, "Closed %s due too frequent packet sending (%d per sec)", ctx.channel().remoteAddress(), packetsCounter); |
| 60 | + return false; |
| 61 | + } |
| 62 | + |
| 63 | + if (bytesPerSec > 0 && bytesCounter > bytesPerSec) { |
| 64 | + closeConnection(ctx, "Closed %s due too many bytes sent per second (%d per sec)", ctx.channel().remoteAddress(), bytesCounter); |
| 65 | + return false; |
| 66 | + } |
| 67 | + |
| 68 | + lastPacket = time; |
| 69 | + |
| 70 | + return true; |
| 71 | + } |
| 72 | + |
| 73 | + private void closeConnection(ChannelHandlerContext ctx, String reason, Object... args) { |
| 74 | + ctx.close(); |
| 75 | + Logger.info(reason, args); |
| 76 | + } |
| 77 | +} |
0 commit comments