Files
tidewall/src/net/source_limiter.gd
T
claudeandClaude Opus 5.5 f795ee3fa5 N6: Joining games: direct connect, LAN and server list
- LAN discovery: a listening server answers QUERY packets on its game port
  plus one (ServerBeacon, off with --no-lan). ServerBrowser scans eight game
  ports from 24650 by broadcast.
- A self-hostable list server: --list-server [--port=N] (ListServer,
  default UDP 24660). Game servers register with --list=HOST[:PORT] and
  --name=NAME; they are listed under their source address only after
  echoing a CHALLENGE token. Entries expire after 45 s, 8 per address,
  256 in all; every source is rate-limited (SourceLimiter).
- NetDiscovery messages: every QUERY is padded to 512 bytes and no answer
  is bigger, so neither service amplifies spoofed requests.
- tidewall --browse [--list=...] [--lan-target=IP] [--lan-port=N] prints
  the servers found as JSON until menus (A10) show them.
- People who connect mid-match or during results watch a living player
  (Match.watch) and take places ahead of bots in the next lobby, instead
  of being told the server is full. Bots fill only the places left when
  the match starts.
- Tests: codec round trips, size limits and a 40,000-message fuzz; list
  server with fake servers (challenge, stolen and wrong tokens, renewal,
  expiry, caps, flood); LAN scan over loopback; watchers over UDP; lobby
  backfill. make discovery-check runs it all as real processes.

Closes #37

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:33:32 -05:00

45 lines
1.4 KiB
GDScript

## Counts packets per sending address over fixed windows and says when one has sent
## too many. Used by everything that answers unauthenticated UDP (the LAN beacon and
## the list server) so a flood from one address is mostly ignored. Memory is bounded:
## once `max_sources` addresses have been seen in a window, new ones are refused
## until the next window.
class_name SourceLimiter
extends RefCounted
var per_window: int = 20
var window_msec: int = 1000
var max_sources: int = 4096
## Packets refused so far.
var refused: int = 0
var _window_start: int = -1
var _counts: Dictionary = {}
func _init(packets_per_window: int = 20, window: int = 1000, sources: int = 4096) -> void:
per_window = packets_per_window
window_msec = window
max_sources = sources
## True if a packet from `address` may be handled now. `now_msec` is for tests.
func allow(address: String, now_msec: int = -1) -> bool:
var now: int = now_msec if now_msec >= 0 else Time.get_ticks_msec()
if _window_start < 0 or now - _window_start >= window_msec:
_window_start = now
_counts.clear()
var count: int = int(_counts.get(address, 0))
if count == 0 and _counts.size() >= max_sources:
refused += 1
return false
if count >= per_window:
refused += 1
return false
_counts[address] = count + 1
return true
## Addresses being counted in the current window.
func tracked() -> int:
return _counts.size()