Documentation
¶
Overview ¶
Package connlimit provides per-IP connection limiting. It prevents a single client IP from consuming all proxy resources via many concurrent connections (e.g. HTTP flood, slow-read attacks). It is a self-contained leaf (stdlib only, no Culvert coupling) extracted from the flat package main per ADR-0002.
Index ¶
- type ConnLimiter
- func (cl *ConnLimiter) Acquire(ip string) bool
- func (cl *ConnLimiter) ActiveConns(ip string) int64
- func (cl *ConnLimiter) ActiveIPs() int
- func (cl *ConnLimiter) Disable()
- func (cl *ConnLimiter) Enable(maxPerIP int)
- func (cl *ConnLimiter) Enabled() bool
- func (cl *ConnLimiter) MaxPerIP() int
- func (cl *ConnLimiter) Rejected() int64
- func (cl *ConnLimiter) Release(ip string)
- func (cl *ConnLimiter) SetMaxPerIP(maxPerIP int)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ConnLimiter ¶
type ConnLimiter struct {
// contains filtered or unexported fields
}
ConnLimiter tracks active connections per client IP.
maxPerIP is atomic rather than lock-guarded: with the counters sharded there is no single lock left that could serialise it against Acquire, and none is needed. The cap is only ever read to make a point-in-time admit/reject comparison, and Enable never touches a counter, so an Enable interleaved with an Acquire has always been able to land on either side of it. What the lock DID protect — the counter increment against Release's delete (the TOCTOU note on Acquire) — is preserved exactly, per shard.
func New ¶
func New() *ConnLimiter
New returns a ConnLimiter with the default per-IP cap, initially disabled.
func (*ConnLimiter) Acquire ¶
func (cl *ConnLimiter) Acquire(ip string) bool
Acquire records a connection from ip and reports whether it is admitted (false ⇒ the per-IP limit is exceeded and the caller should reject).
The per-IP counter is ALWAYS maintained, even while the limiter is disabled; the enabled flag gates only the rejection decision, not the accounting. This keeps Acquire and Release symmetric across a runtime disable/re-enable: every admitted connection is counted exactly once and released exactly once. If Acquire skipped counting while disabled (the historical behavior), a connection admitted during the disabled window would later be Released unconditionally and decrement a DIFFERENT, still-counted connection's slot — letting a subsequent re-enable admit past the cap (fail-open). Conversely, gating Release on enabled leaks the slot of a connection counted while enabled and released after disable, wedging that IP over-limit forever (the #503 fail-closed bug). Counting unconditionally closes both.
func (*ConnLimiter) ActiveConns ¶
func (cl *ConnLimiter) ActiveConns(ip string) int64
ActiveConns returns the current connection count for an IP (testing).
func (*ConnLimiter) ActiveIPs ¶
func (cl *ConnLimiter) ActiveIPs() int
ActiveIPs returns the number of IPs currently tracked.
It is a diagnostic gauge — the admin API's activeIPs field (ui_config.go) and the tests, never the request path — and with the counters sharded it is a sum of per-shard snapshots rather than one instantaneous whole-map reading: under concurrent traffic it can land between two consistent states. Quiescent readings, every Acquire paired with its Release, stay exact. That is the one behavioural difference the shard split makes, and it is confined here.
It touches all 64 shard locks, but each is held only for a len() read, so an admin poll costs the request path nothing measurable.
func (*ConnLimiter) Disable ¶
func (cl *ConnLimiter) Disable()
Disable turns off connection limiting.
It clears the flag only: the cap stays where it was, so MaxPerIP keeps answering with it and a later Enable with no argument of its own would resume at the operator's configured value. That is deliberate and it is also why MaxPerIP can never return 0 — a reader cannot use the cap to infer whether limiting is on, and must ask Enabled.
func (*ConnLimiter) Enable ¶
func (cl *ConnLimiter) Enable(maxPerIP int)
Enable turns on connection limiting.
func (*ConnLimiter) Enabled ¶
func (cl *ConnLimiter) Enabled() bool
Enabled reports whether connection limiting is currently active.
func (*ConnLimiter) MaxPerIP ¶
func (cl *ConnLimiter) MaxPerIP() int
MaxPerIP returns the current per-IP limit.
func (*ConnLimiter) Rejected ¶ added in v1.0.187
func (cl *ConnLimiter) Rejected() int64
Rejected returns the cumulative count of connections refused because the client IP was over its per-IP cap (process lifetime; never reset). This is the only signal an admin has that a configured limit is actually rejecting live traffic rather than sitting unused — the reject path (proxy.go, socks5.go) has no other counter or metric.
func (*ConnLimiter) Release ¶
func (cl *ConnLimiter) Release(ip string)
Release decrements the connection count for ip. It does NOT gate on enabled: Acquire counts every admitted connection unconditionally (see its doc), so Release must mirror that exactly. The decrement is guarded by map-entry presence, and the delete-at-one prevents underflow, so releasing an IP with no live count is a safe no-op.
ONE CRITICAL SECTION, and that is a correctness property before it is a cost one. Release used to take the shard lock TWICE — once to look the counter up, then again to delete the entry once an UNLOCKED decrement had taken it to zero — and the second pass re-checked the counter's VALUE without re-checking its IDENTITY. Acquire's reject path had exactly that identity guard (`cur == ctr`), so the pattern was known and applied in one of the two places that needed it.
What the gap permitted (reproduced deterministically by TestRelease_LegacyTwoPhaseLosesALiveSlot, which drives the interleaving rather than racing for it): Release A reads the counter, unlocks, decrements 1 -> 0 and is descheduled. Acquire B finds the still-mapped counter, takes it 0 -> 1; Release B takes it back to 0 and deletes the entry. Acquire C then misses, allocates a FRESH counter, maps it, and takes it to 1 — a live, admitted connection. A now re-locks, loads its STALE pointer, sees 0, and deletes whatever is at ip — which is C's entry, count 1. C's accounting is destroyed, so the IP goes on to hold limit+1 concurrent connections: a fail-OPEN past a configured per-IP cap, the same direction as the #503 bug the unconditional-accounting contract above exists to close.
Doing the lookup, the decrement and the conditional delete in one critical section removes the window outright. There is no longer a pointer that can go stale, no unlocked mutation of a count the lock is supposed to serialise, and no value-vs-identity re-check to get wrong — and it halves this function's lock traffic, which is the dominant cost when traffic arrives from a single NAT egress (see the package header).
func (*ConnLimiter) SetMaxPerIP ¶ added in v1.0.404
func (cl *ConnLimiter) SetMaxPerIP(maxPerIP int)
SetMaxPerIP replaces the per-IP cap WITHOUT touching enablement.
It exists because Enable is the wrong primitive for a caller that has been handed a cap and no enablement decision, and the CP→DP config-snapshot apply is exactly that caller (CHAOS-112). `conn_limit_max_per_ip` is declared ClusterSynced in the root config-surface registry; `conn_limit_enabled` has no ConfigSnapshot binding at all — it is node-local, set by the startup resolver, the persisted admin settings, the admin API or a config import. Enable writes BOTH, so using it to apply a cluster-synced cap also wrote a surface the registry says is not synced: every Data Plane that applied any snapshot started enforcing the default cap, because MaxPerIP answers with a cap whether or not limiting is on (see Disable) and so the publisher can never emit a zero that would have been skipped.
A non-positive cap is a no-op rather than a reset to the default. The wire field's recorded semantics are semSkipIfZero — "zero keeps live state" — and an older Control Plane, or a snapshot with the field absent, must leave the node's cap exactly where it was.
Memory ordering: unlike Enable this does not move the enabled flag, so Acquire's load-bearing enabled-then-cap read order is unaffected. A reader racing this store observes either the old or the new cap alongside an unchanged flag, and both are legitimate point-in-time decisions — the hazard Enable's store order exists to prevent (enabled==true paired with a stale cap) cannot arise when the flag is not being published.