## 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()