diff --git a/README.md b/README.md
index a98f801..166013f 100644
--- a/README.md
+++ b/README.md
@@ -572,6 +572,8 @@ than 30 minutes is ignored.
for read-only checks, stored in `monitor_state.modem_checks`:
- **NAT sessions** every 30 minutes, from the NAT Table page. Needs attention warns when 80% of the
gateway's sessions (32,767 on a BGW320) are in use, since new connections stall once it is full.
+ The same read counts incoming sessions to the public IP by destination port, so the panel shows
+ the *busiest inbound port* (protocol, port, sessions and how many addresses they come from).
- **Side-by-side latency test** (gandalf#70): the provider's "plug a device straight into the modem
and see if it's slow too" test, run by Gandalf. The gateway pings 1.1.1.1 from its Troubleshoot page
while, at the same moment, Gandalf times TCP handshakes to 1.1.1.1:443 through the router and to the
@@ -593,10 +595,22 @@ for read-only checks, stored in `monitor_state.modem_checks`:
what the tests showed while it built up, and its *Cleared* note sums up the whole episode in words
that can go straight to the provider. The latest result is in the Internet line in Needs attention
and on the WAN / Fiber panel.
-- **Firewall drops** every 5 minutes, from the Logs page, counted per hour for a day. Most are *FLOOD
- limit 50pps*: AT&T's firmware caps new incoming connections at 50 per second (visitors to hosted
- services, peers), with no setting to change it. The log records at most one drop every 2 seconds and
- keeps about ten minutes, so the counts are a lower bound. Shown on the panel only.
+- **Firewall drops** every 5 minutes, from the Logs page, counted per hour and kept for 14 days. Most
+ are *FLOOD limit 50pps*: AT&T's firmware caps new incoming connections at 50 per second (visitors to
+ hosted services, peers), even in IP Passthrough, with no setting to change it. The log records at
+ most one drop every 2 seconds (about 1,800 an hour) and keeps about ten minutes, so the counts are a
+ lower bound. The WAN / Fiber panel charts them per hour, with the full-limit line marked.
+
+ **When the limit stays full**, outside users, Sia and every other inbound service fail to connect or
+ feel slow, while everything from inside works (hairpin traffic never reaches the modem). Gandalf
+ raises *Modem dropping new incoming connections (flood limit)* when 2 complete hours in a row each
+ log 1,500 or more flood drops (the hour still filling doesn't count; an hour missing from the log
+ counts as quiet). It shows in Needs attention with the busiest inbound port, opens a P2 ticket after
+ the usual consecutive checks, and clears, with a *Cleared* note, once a complete hour logs under 500.
+ Between 500 and 1,500 an open alert stays as it is. Counts more than an hour old decide nothing.
+ The fix is upstream of the modem: blocking in nginx or on the UDM can't help, because the modem
+ counts connection attempts before they reach either. In November 2026 it was a crawler on the
+ Gitea site, fixed by turning on Cloudflare's proxy for that hostname.
- **The gateway's own speed tests** (AT&T runs them from the modem), read with the NAT check; the latest
down and up results are shown on the panel as a reference for what the line itself delivers.
@@ -1074,7 +1088,7 @@ Take LED colors from the model's quick start guide. See the comment at the top o
`recovery_notified` once the recovery note is on its ticket (column added automatically at monitor startup)
- `suppression_rules`: `active=FALSE` when removed; `expires_at` checked at query time
- `monitor_state`: key/value store; `interface_baseline`, `link_stats`, and `modem_stats` are JSON blobs
-- `monitor_state` also holds `wan_history` (WAN outages, modem restarts), `wan_quality` (UniFi's 5 minute WAN health timeline), `modem_checks` (NAT sessions, the latest side-by-side ping and 7 days of them in `ping_history`, hourly firewall drops and the gateway's speed test results) and `unifi_log_cursor` (how far the UniFi log has been read)
+- `monitor_state` also holds `wan_history` (WAN outages, modem restarts), `wan_quality` (UniFi's 5 minute WAN health timeline), `modem_checks` (NAT sessions, the latest side-by-side ping and 7 days of them in `ping_history`, hourly firewall drops for 14 days, the busiest inbound ports and the gateway's speed test results) and `unifi_log_cursor` (how far the UniFi log has been read)
- Database sessions run in UTC (`db.py`), whatever the server's time zone
- `modem_samples`: optical readings per poll, kept 90 days; created automatically at monitor startup
- `cutsheet_items`, `cutsheet_cables`, `cutsheet_port_labels`, `cutsheet_history`: cutsheet records and
diff --git a/attention.py b/attention.py
index b157e02..2537350 100644
--- a/attention.py
+++ b/attention.py
@@ -144,8 +144,28 @@ def _modem_ping_note(checks: Optional[dict], now: float) -> str:
return f"Modem's own ping {when}: {theirs}{ours_txt}, {verdict}. "
-def _modem_checks(checks: Optional[dict]) -> List[dict]:
- out = []
+_FLOOD_STALE_S = 3600
+
+
+def _inbound_flood(checks: Optional[dict], now: float) -> List[dict]:
+ """The modem's flood limit full for hours: new incoming connections are being dropped."""
+ fw = (checks or {}).get('firewall') or {}
+ if not fw.get('hours') or now - (fw.get('checked_at') or 0) > _FLOOD_STALE_S:
+ return []
+ sat = modem.flood_saturation(fw['hours'])
+ if sat is None:
+ return []
+ detail = (f'Its flood limit (50 new connections a second) has been full for {sat["hours"]} hours. '
+ 'Outside users, Sia and other inbound services may fail to connect or feel slow. ')
+ busiest = modem.inbound_text(((checks or {}).get('nat') or {}).get('inbound'), top=1)
+ if busiest:
+ detail += f'Busiest inbound port: {busiest}.'
+ return [_entry('broken', 'warn', 'Modem is dropping new incoming connections', '#modem-section',
+ detail.strip())]
+
+
+def _modem_checks(checks: Optional[dict], now: Optional[float] = None) -> List[dict]:
+ out = _inbound_flood(checks, time.time() if now is None else now)
nat = (checks or {}).get('nat') or {}
if nat.get('available') and nat.get('in_use', 0) / nat['available'] >= _NAT_FULL:
pct = round(100 * nat['in_use'] / nat['available'])
@@ -225,7 +245,7 @@ def build(events: List[dict], power: List[dict], cutsheet_view: Optional[dict],
Entry: {group, severity: bad|warn|info, text, href, detail}.
"""
now = time.time() if now is None else now
- entries = (_wan(wan_quality, now, modem_checks) + _modem_checks(modem_checks)
+ entries = (_wan(wan_quality, now, modem_checks) + _modem_checks(modem_checks, now)
+ _smart_power(modem_restart) + _alerts(events) + _rebooting(events) + _power(power))
if cutsheet_view is not None:
entries += _cutsheet(cutsheet_view)
diff --git a/modem.py b/modem.py
index cd3eb3c..4f43c1e 100644
--- a/modem.py
+++ b/modem.py
@@ -28,7 +28,7 @@ import html
import logging
import re
import time
-from datetime import datetime, timezone
+from datetime import datetime, timedelta, timezone
from typing import Dict, List, Optional
import requests
@@ -576,6 +576,94 @@ def firewall_kind(reason: str) -> str:
return 'flood' if 'flood' in reason else 'invalid' if 'invalid' in reason else 'other'
+# The gateway drops new incoming connections over a fixed limit (50 a second) and logs at
+# most one drop every 2 seconds: about 1,800 an hour when the limit stays full.
+FIREWALL_LOG_CEILING = 1800
+FLOOD_SATURATED_PER_HOUR = 1500 # logged flood drops in an hour that count as "full"
+FLOOD_SATURATED_HOURS = 2 # full hours in a row before raising it
+FLOOD_CLEAR_PER_HOUR = 500 # an hour under this ends it
+
+
+def _hour(key: str) -> Optional[datetime]:
+ try:
+ return datetime.strptime(key, '%Y-%m-%dT%H')
+ except (TypeError, ValueError):
+ return None
+
+
+def _complete_hours(hours: dict) -> List[tuple]:
+ """[(hour key, flood count)] for each hour before the newest (which is still filling),
+ oldest first, with hours missing from the log filled in as 0."""
+ keys = sorted(k for k in hours if _hour(k))
+ if len(keys) < 2:
+ return []
+ out = []
+ start, end = _hour(keys[0]), _hour(keys[-1])
+ t = start
+ while t < end:
+ key = t.strftime('%Y-%m-%dT%H')
+ out.append((key, int((hours.get(key) or {}).get('flood') or 0)))
+ t += timedelta(hours=1)
+ return out
+
+
+def flood_saturation(hours: dict, per_hour: int = FLOOD_SATURATED_PER_HOUR,
+ need: int = FLOOD_SATURATED_HOURS) -> Optional[dict]:
+ """The gateway's flood limit has been full for the last `need` complete hours or more.
+
+ hours: the monitor's per-hour firewall counts ({'YYYY-MM-DDTHH': {'flood': n, ...}},
+ gateway local time). Returns {'hours': run length, 'counts': [n, ...] newest last,
+ 'since': first hour key of the run} or None.
+ """
+ complete = _complete_hours(hours)
+ run = 0
+ for _, n in reversed(complete):
+ if n < per_hour:
+ break
+ run += 1
+ if run < max(need, 1):
+ return None
+ tail = complete[-run:]
+ return {'hours': run, 'counts': [n for _, n in tail], 'since': tail[0][0]}
+
+
+def flood_cleared(hours: dict, clear: int = FLOOD_CLEAR_PER_HOUR) -> bool:
+ """The last complete hour had few enough flood drops that new connections get through."""
+ complete = _complete_hours(hours)
+ return bool(complete) and complete[-1][1] < clear
+
+
+def parse_inbound_ports(page: str, wan_ip: str, top: int = 5) -> List[dict]:
+ """The busiest destination ports of incoming sessions to wan_ip in the NAT table page:
+ [{'proto', 'port', 'sessions', 'sources'}], busiest first. Shows what an inbound
+ flood is aimed at."""
+ if not wan_ip:
+ return []
+ sessions: Dict[tuple, int] = {}
+ sources: Dict[tuple, set] = {}
+ for row in re.findall(r'
]*>(.*?)
', page, re.I | re.S):
+ cells = [_TAG_RE.sub('', c).strip() for c in _CELL_RE.findall(row)]
+ # IP family, protocol, number, lifetime, TCP state, source, source port, destination,
+ # destination port, then the same four after NAT
+ if (len(cells) < 9 or cells[0] != 'ipv4' or cells[1] not in ('tcp', 'udp')
+ or cells[7] != wan_ip or not cells[8].isdigit()):
+ continue
+ key = (cells[1], cells[8])
+ sessions[key] = sessions.get(key, 0) + 1
+ sources.setdefault(key, set()).add(cells[5])
+ ranked = sorted(sessions, key=lambda k: (-sessions[k], k))[:top]
+ return [{'proto': p, 'port': port, 'sessions': sessions[(p, port)], 'sources': len(sources[(p, port)])}
+ for p, port in ranked]
+
+
+def inbound_text(inbound: Optional[List[dict]], top: int = 3) -> str:
+ """'TCP 443: 1,268 sessions from 1,250 addresses; ...' for the busiest inbound ports."""
+ def n(count: int, word: str) -> str:
+ return f'{count:,} {word}' + ('' if count == 1 else ('es' if word.endswith('s') else 's'))
+ return '; '.join(f'{(p.get("proto") or "").upper()} {p.get("port")}: {n(p.get("sessions", 0), "session")} '
+ f'from {n(p.get("sources", 0), "address")}' for p in (inbound or [])[:top])
+
+
def parse_speed_tests(page: str) -> List[dict]:
"""The gateway's own speed test history, newest first:
{'at' (as the page shows it), 'direction', 'mbps', 'latency_ms', 'ok'}."""
@@ -644,11 +732,15 @@ class ModemAdmin:
raise ModemDataInvalid(f'{path} returned HTTP {resp.status_code} after logging in')
return resp.text
- def nat_sessions(self) -> Dict[str, int]:
+ def nat_sessions(self, wan_ip: str = '') -> dict:
+ """{'in_use', 'available'}, plus 'inbound' (parse_inbound_ports) when wan_ip is known."""
# The page lists every session too, so it can be large (hundreds of KB)
- counts = parse_nat_summary(self._page(_NAT_PAGE, timeout=max(self.timeout, 30)))
+ page = self._page(_NAT_PAGE, timeout=max(self.timeout, 30))
+ counts = parse_nat_summary(page)
if counts is None:
raise ModemDataInvalid('NAT table page has no session counts')
+ if wan_ip:
+ counts['inbound'] = parse_inbound_ports(page, wan_ip)
return counts
def firewall_log(self) -> List[dict]:
diff --git a/monitor.py b/monitor.py
index 5ea6b2d..02ec67d 100644
--- a/monitor.py
+++ b/monitor.py
@@ -2429,7 +2429,7 @@ class NetworkMonitor:
_NAT_EVERY_S = 1800 # NAT sessions and the gateway's speed test history
_FIREWALL_EVERY_S = 300 # the firewall log only holds about ten minutes
- _FIREWALL_HOURS = 24
+ _FIREWALL_HOURS = 14 * 24 # two weeks, so the start of a flood is still on record
_PING_SLOW_EVERY_S = 120 # while the internet is slow: every check (gandalf#70 evidence)
_PING_HEALTHY_EVERY_S = 1800 # otherwise now and then, to learn the line's normal latency
_CHECKS_ERROR_WAIT_S = 600 # after a failed login or read, leave the gateway alone this long
@@ -2478,7 +2478,7 @@ class NetworkMonitor:
return # failed recently: don't keep knocking on the gateway
try:
if due_nat:
- checks['nat'] = dict(admin.nat_sessions(), at=now)
+ checks['nat'] = dict(admin.nat_sessions(self._modem_wan_ip()), at=now)
checks['speed'] = self._latest_speed_tests(admin.speed_tests(), now)
if due_fw:
checks['firewall'] = self._count_firewall_drops(checks.get('firewall'), admin.firewall_log(), now)
@@ -2497,6 +2497,53 @@ class NetworkMonitor:
'login': isinstance(e, modem_api.ModemLoginFailed)}
db.set_state('modem_checks', checks)
+ @staticmethod
+ def _modem_wan_ip() -> str:
+ """The modem's public IPv4 address from its last poll, or ''."""
+ try:
+ raw = db.get_state('modem_stats')
+ stats = (json.loads(raw) if isinstance(raw, str) else raw) or {}
+ except (ValueError, AttributeError):
+ return ''
+ return stats.get('wan_ip') or ''
+
+ _FLOOD_STALE_S = 3600 # firewall counts older than this are too old to judge by
+
+ def _process_inbound_flood(self, suppressions: list) -> None:
+ """Alert when the modem's flood limit stays full: it drops new incoming connections
+ over 50 a second before they reach the router, so outside users, Sia and other
+ inbound services fail to connect or feel slow. Clears once an hour is quiet again."""
+ raw = db.get_state('modem_checks')
+ try:
+ checks = (json.loads(raw) if isinstance(raw, str) else raw) or {}
+ except (ValueError, AttributeError):
+ return
+ fw = checks.get('firewall') or {}
+ if not fw.get('hours') or time.time() - (fw.get('checked_at') or 0) > self._FLOOD_STALE_S:
+ return # nothing fresh to judge by: leave any open alert as it is
+ sat = modem_api.flood_saturation(fw['hours'])
+ if sat is None:
+ if modem_api.flood_cleared(fw['hours']):
+ db.resolve_event('inbound_flood', self.modem_name, '')
+ return
+ counts = ', '.join(f'{n:,}' for n in sat['counts'][-6:])
+ description = (
+ f'The modem has been dropping new incoming connections over its built-in flood limit '
+ f'(50 a second) for {sat["hours"]} hours in a row (since {sat["since"].replace("T", " ")}:00, '
+ f'modem time). Logged drops per hour: {counts}. The log keeps at most one drop every 2 '
+ f'seconds, about {modem_api.FIREWALL_LOG_CEILING:,} an hour, so the real number is higher.\n\n'
+ f'Outside users, Sia and other inbound services may fail to connect or feel slow. '
+ f'Connections from inside the network are not affected.')
+ busiest = modem_api.inbound_text((checks.get('nat') or {}).get('inbound'))
+ if busiest:
+ description += f'\n\nBusiest inbound ports in the modem\'s session table: {busiest}.'
+ advice = ('Find what the busiest port serves and stop the traffic before it reaches the '
+ 'connection, for example Cloudflare\'s proxy in front of a crawled site. Blocking in '
+ 'nginx or on the UDM does not help: the modem counts connection attempts before '
+ 'they reach either.')
+ self._modem_event(suppressions, 'inbound_flood', 'warning', '', description,
+ 'Modem dropping new incoming connections (flood limit)', '2', advice)
+
@staticmethod
def _ping_evidence(start: float, end: float) -> Optional[dict]:
"""modem.episode_evidence over the saved side-by-side pings, or None."""
@@ -2777,6 +2824,12 @@ class NetworkMonitor:
self._collect_modem_checks()
except Exception as e:
logger.error(f'Modem checks failed: {e}', exc_info=True)
+ try:
+ if self.modem:
+ with self._wan_batch():
+ self._process_inbound_flood(suppressions)
+ except Exception as e:
+ logger.error(f'Inbound flood check failed: {e}', exc_info=True)
# Note on the tickets of anything that cleared this cycle (or failed to post before)
try:
diff --git a/static/app.js b/static/app.js
index 2ba5f1f..79ee10b 100644
--- a/static/app.js
+++ b/static/app.js
@@ -400,12 +400,18 @@ function _modemChecks(c) {
}
const fw = c.firewall && c.firewall.hours;
if (fw && Object.keys(fw).length) {
- const sum = k => Object.values(fw).reduce((n, h) => n + (h[k] || 0), 0);
+ const day = Object.keys(fw).sort().slice(-24).map(k => fw[k]);
+ const sum = k => day.reduce((n, h) => n + (h[k] || 0), 0);
const flood = sum('flood'), invalid = sum('invalid'), total = flood + invalid + sum('other');
- out += _modemStat('Firewall drops', `${total.toLocaleString()} in ${Object.keys(fw).length} h`, '',
+ out += _modemStat('Firewall drops', `${total.toLocaleString()} in ${day.length} h`, '',
`${flood.toLocaleString()} incoming over the flood limit, ${invalid.toLocaleString()} invalid; ` +
'at least (the log keeps 1 per 2 s)');
}
+ const busiest = c.nat && (c.nat.inbound || [])[0];
+ if (busiest) {
+ out += _modemStat('Busiest inbound port', `${String(busiest.proto).toUpperCase()} ${busiest.port}`,
+ '', `${busiest.sessions.toLocaleString()} sessions from ${busiest.sources.toLocaleString()} addresses, ${ago(c.nat.at)}`);
+ }
const sp = c.speed;
if (sp && sp.down && sp.up) {
out += _modemStat('AT&T speed test', `↓ ${Math.round(sp.down.mbps)} ↑ ${Math.round(sp.up.mbps)} Mbps`, '',
@@ -472,6 +478,41 @@ function _modemQuality(q) {
`;
}
+// Flood limit: the modem drops new incoming connections over 50 a second and logs at most
+// one every 2 s (about 1,800 an hour). Hours near that ceiling mean the limit was full.
+const _FLOOD_FULL = 1500, _FLOOD_CEILING = 1800;
+
+function _modemFloodChart(c) {
+ const hours = c && c.firewall && c.firewall.hours;
+ const keys = hours ? Object.keys(hours).sort() : [];
+ if (keys.length < 2) return '';
+ const counts = keys.map(k => hours[k].flood || 0);
+ let run = 0;
+ for (let i = counts.length - 2; i >= 0 && counts[i] >= _FLOOD_FULL; i--) run += 1; // the newest hour is still filling
+ const peak = Math.max(...counts);
+ const summary = run >= 2 ? `full for the last ${run} hours` : (peak >= _FLOOD_FULL ? `full at times, peak ${peak.toLocaleString()} an hour`
+ : `peak ${peak.toLocaleString()} an hour`);
+ const w = 1000 / keys.length;
+ const bars = counts.map((n, i) => {
+ const h = Math.min(n, _FLOOD_CEILING) / _FLOOD_CEILING * 40;
+ const tip = `${keys[i].replace('T', ' ')}:00 modem time: ${n.toLocaleString()} dropped`;
+ return `${lt.escHtml(tip)}`;
+ }).join('');
+ const line = (40 - _FLOOD_FULL / _FLOOD_CEILING * 40).toFixed(2);
+ return `
+
+
New incoming connections dropped by the modem's flood limit, per hour
+ ${lt.escHtml(summary)}
+
+
${lt.escHtml(keys[0].replace('T', ' '))}:00
+ limit full (outside connections fail)
+ now
+
`;
+}
+
// A restart from the Restart modem button: in progress, or finished in the last hour
function _modemRestartNote(r) {
if (!r || !r.at) return '';
@@ -553,6 +594,7 @@ function updateModem(data) {
Modem status unavailable: ${lt.escHtml(data.error || 'unknown error')}
Last attempt ${lt.escHtml(data.updated || '-')}