Skip to content

Commit

Permalink
Rate limit connection requests
Browse files Browse the repository at this point in the history
  • Loading branch information
Alemiz112 committed Mar 28, 2024
1 parent c88d5be commit 9a9ab52
Showing 1 changed file with 14 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,17 @@
import org.cloudburstmc.netty.util.RakUtils;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static org.cloudburstmc.netty.channel.raknet.RakConstants.*;

public class RakServerOfflineHandler extends AdvancedChannelInboundHandler<DatagramPacket> {
public static final String NAME = "rak-offline-handler";
private static final int MAX_PACKETS_PER_SECOND = 10;

private static final InternalLogger log = InternalLoggerFactory.getInstance(RakServerOfflineHandler.class);

Expand All @@ -51,6 +54,11 @@ public class RakServerOfflineHandler extends AdvancedChannelInboundHandler<Datag
.expirationListener((key, value) -> ReferenceCountUtil.release(value))
.build();

private final ExpiringMap<InetAddress, AtomicInteger> packetsCounter = ExpiringMap.builder()
.expiration(1, TimeUnit.SECONDS)
.expirationPolicy(ExpirationPolicy.CREATED)
.build();

@Override
protected boolean acceptInboundMessage(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!super.acceptInboundMessage(ctx, msg)) {
Expand Down Expand Up @@ -91,6 +99,12 @@ protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) th
ByteBuf magicBuf = ctx.channel().config().getOption(RakChannelOption.RAK_UNCONNECTED_MAGIC);
long guid = ctx.channel().config().getOption(RakChannelOption.RAK_GUID);

AtomicInteger counter = this.packetsCounter.computeIfAbsent(packet.sender().getAddress(), s -> new AtomicInteger());
if (counter.incrementAndGet() > MAX_PACKETS_PER_SECOND) {
log.warn("[{}] Sent too many packets per second", packet.sender());
return;
}

switch (packetId) {
case ID_UNCONNECTED_PING:
this.onUnconnectedPing(ctx, packet, magicBuf, guid);
Expand Down

0 comments on commit 9a9ab52

Please sign in to comment.