🤞 Sync 2026-10-06 13:52:46

This commit is contained in:
github-actions[bot] committed 2026-10-06 13:52:46 +08:00
1 parent 4d2d69bed9
commit 947eaea2ee
42 files changed
+2681 -1582

No files matched your search

+128 -71
View File
@@ -87,14 +87,43 @@ let mwan3_cfg = null;
let pub6_seen = {};
let pub4_seen = {};
let lit_alias = {};
// Register one public address. The placeholder map is keyed and numbered on
// normalised forms only; when the literal spelling differs from the
// normalised form it is recorded as an alias so free-form text carrying
// that spelling is still replaced.
function register(addr_str) {
if (!addr_str) return;
let lit = split(addr_str, '/')[0];
let norm = norm_addr(addr_str);
if (!norm) return;
let sa = sock.sockaddr(split(addr_str, '/')[0]);
let sa = sock.sockaddr(lit);
if (sa.family == 10 && is_public_v6(norm)) pub6_seen[norm] = 1;
else if (sa.family == 2 && is_public_v4(norm)) pub4_seen[norm] = 1;
else return;
if (lit != norm) lit_alias[lit] = norm;
}
// Sweep a block of free-form text for address literals. Splitting on any
// run of characters that cannot occur inside an address or prefix keeps
// every address-bearing token intact; a token that is not a valid public
// address fails validation inside register() and drops out. A colon-less
// token must be a full dotted quad: the address parser also accepts
// shorthand forms like "1.0", which free-form text produces as ordinary
// decimal fragments, and registering one would alias that fragment to a
// placeholder everywhere in the report.
function scan_text(text) {
if (!text) return;
for (let tok in split(text, /[^0-9a-fA-F:.\/]+/)) {
if (!length(tok)) continue;
if (index(tok, ':') == -1 &&
!match(tok, /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(\/[0-9]+)?$/))
continue;
register(tok);
}
}
for (let n in nb_all) { register(n.dst); }
@@ -110,57 +139,8 @@ if (mwan3_st?.interfaces)
// Register any addresses appearing in the mwan3 UCI config (e.g. track_ip
// values not yet reflected in routes/status).
if (mwan3_cfg)
for (let line in split(mwan3_cfg, '\n'))
for (let tok in split(replace(line, "'", ' '), ' '))
register(trim(tok));
// ---------------------------------------------------------------------------
// Phase 3: build deterministic placeholder map
// Sort addresses so the same address always gets the same placeholder across
// multiple runs (e.g. v3.4 run vs v3.5.1 run).
// ---------------------------------------------------------------------------
let pub6_list = sort(keys(pub6_seen));
let pub4_list = sort(keys(pub4_seen));
let addr_map = {};
for (let i = 0; i < length(pub6_list); i++)
addr_map[pub6_list[i]] = sprintf('PUB6_%d', i + 1);
for (let i = 0; i < length(pub4_list); i++)
addr_map[pub4_list[i]] = sprintf('PUB4_%d', i + 1);
// ---------------------------------------------------------------------------
// Anonymisation helpers
// ---------------------------------------------------------------------------
// Anonymise a single address string (preserves any /prefix-length suffix).
function anon(addr_str) {
if (!addr_str) return addr_str;
let parts = split(addr_str, '/');
let norm = norm_addr(parts[0]);
let ph = norm ? (addr_map[norm] ?? null) : null;
if (ph) return ph + (length(parts) > 1 ? '/' + parts[1] : '');
return addr_str;
}
// Anonymise a block of free-form text (nft output, log lines, etc.).
// Sorted longest-first so longer addresses are replaced before any shorter
// prefix they might share (prevents partial substitutions).
let _sorted_addrs = sort(keys(addr_map), (a, b) => length(b) - length(a));
function anon_text(text) {
if (!text) return '(no output)';
for (let addr in _sorted_addrs) {
let ph = addr_map[addr];
let pos = 0;
while (true) {
let found = index(text, addr, pos);
if (found == -1) break;
text = substr(text, 0, found) + ph + substr(text, found + length(addr));
pos = found + length(ph);
}
}
return text;
}
scan_text(mwan3_cfg);
// Strip elements from user-defined nft sets, replacing with { ... }.
// mwan3 infrastructure sets (names starting with mwan3_) are left intact:
@@ -197,13 +177,102 @@ function strip_set_elements(text) {
return join('\n', out);
}
// Run a shell command and return its anonymised output.
function pcmd(cmd) {
// Run a shell command and return its raw output.
function rcmd(cmd) {
let f = fs.popen(cmd);
if (!f) return '(failed to run: ' + cmd + ')\n';
let out = f.read('all');
f.close();
return anon_text(out || '(no output)\n');
return out || '(no output)\n';
}
// ---------------------------------------------------------------------------
// Detect which table mwan3 is using (v3.4 = inet fw4, v3.5+ = inet mwan3)
// ---------------------------------------------------------------------------
let mwan3_tbl = 'inet mwan3';
{
let f = fs.popen('nft list chain inet mwan3 mwan3_prerouting 2>/dev/null | head -1');
let l = f?.read('line');
f?.close();
if (!l || !length(trim(l))) mwan3_tbl = 'inet fw4';
}
// ---------------------------------------------------------------------------
// Capture the free-form text sections the report prints and sweep them for
// address literals. Some public addresses exist only in this text, e.g. NAT
// map elements derived from no route or interface address, or logged
// addresses no longer present in live state, and are registered here so
// they receive placeholders. Each section is captured exactly once and the
// captured text itself is printed later, so no literal can appear in the
// printed copy without having been swept. The mwan3 table is stripped of
// user-set elements before the sweep so redacted addresses are not
// assigned placeholders.
// ---------------------------------------------------------------------------
let nft_mwan3_txt = strip_set_elements(rcmd(sprintf('nft list table %s 2>/dev/null', mwan3_tbl)));
let fw4_mangle_pre_txt = rcmd('nft list chain inet fw4 mangle_prerouting 2>/dev/null');
let fw4_mangle_out_txt = rcmd('nft list chain inet fw4 mangle_output 2>/dev/null');
let fw4_output_txt = rcmd('nft list chain inet fw4 output 2>/dev/null');
let log_txt = rcmd('logread 2>/dev/null | grep -E "mwan3track\\[|mwan3-hotplug\\[|mwan3-init\\[|mwan3\\[|mwan3rtmon\\[|mwan3-manage-rules\\[|mwan3-create-iface-route\\[" | tail -200');
scan_text(nft_mwan3_txt);
scan_text(fw4_mangle_pre_txt);
scan_text(fw4_mangle_out_txt);
scan_text(fw4_output_txt);
scan_text(log_txt);
// ---------------------------------------------------------------------------
// Phase 3: build deterministic placeholder map
// Sort addresses so the same address always gets the same placeholder across
// multiple runs (e.g. v3.4 run vs v3.5.1 run).
// ---------------------------------------------------------------------------
let pub6_list = sort(keys(pub6_seen));
let pub4_list = sort(keys(pub4_seen));
let addr_map = {};
for (let i = 0; i < length(pub6_list); i++)
addr_map[pub6_list[i]] = sprintf('PUB6_%d', i + 1);
for (let i = 0; i < length(pub4_list); i++)
addr_map[pub4_list[i]] = sprintf('PUB4_%d', i + 1);
// A literal spelling that normalises to a registered address receives the
// registered form's placeholder, so both spellings are replaced in text.
for (let lit, norm in lit_alias)
if (addr_map[norm]) addr_map[lit] = addr_map[norm];
// ---------------------------------------------------------------------------
// Anonymisation helpers
// ---------------------------------------------------------------------------
// Anonymise a single address string (preserves any /prefix-length suffix).
function anon(addr_str) {
if (!addr_str) return addr_str;
let parts = split(addr_str, '/');
let norm = norm_addr(parts[0]);
let ph = norm ? (addr_map[norm] ?? null) : null;
if (ph) return ph + (length(parts) > 1 ? '/' + parts[1] : '');
return addr_str;
}
// Anonymise a block of free-form text (nft output, log lines, etc.).
// Sorted longest-first so longer addresses are replaced before any shorter
// prefix they might share (prevents partial substitutions).
let _sorted_addrs = sort(keys(addr_map), (a, b) => length(b) - length(a));
function anon_text(text) {
if (!text) return '(no output)';
for (let addr in _sorted_addrs) {
let ph = addr_map[addr];
let pos = 0;
while (true) {
let found = index(text, addr, pos);
if (found == -1) break;
text = substr(text, 0, found) + ph + substr(text, found + length(addr));
pos = found + length(ph);
}
}
return text;
}
// ---------------------------------------------------------------------------
@@ -224,18 +293,6 @@ function tbl_label(n) {
return name ? sprintf('%s (%d)', name, n) : sprintf('%d', n);
}
// ---------------------------------------------------------------------------
// Detect which table mwan3 is using (v3.4 = inet fw4, v3.5+ = inet mwan3)
// ---------------------------------------------------------------------------
let mwan3_tbl = 'inet mwan3';
{
let f = fs.popen('nft list chain inet mwan3 mwan3_prerouting 2>/dev/null | head -1');
let l = f?.read('line');
f?.close();
if (!l || !length(trim(l))) mwan3_tbl = 'inet fw4';
}
// ---------------------------------------------------------------------------
// mwan3 version
// ---------------------------------------------------------------------------
@@ -407,20 +464,20 @@ else
// --- full mwan3 nft table ---
printf('=== mwan3 nft table (%s) ===\n', mwan3_tbl);
printf('%s\n', strip_set_elements(pcmd(sprintf('nft list table %s 2>/dev/null', mwan3_tbl))));
printf('%s\n', anon_text(nft_mwan3_txt));
// --- fw4 mangle chains (relevant to mwan3 mark interactions) ---
printf('=== fw4 mangle_prerouting chain ===\n');
printf('%s\n', pcmd('nft list chain inet fw4 mangle_prerouting 2>/dev/null'));
printf('%s\n', anon_text(fw4_mangle_pre_txt));
printf('=== fw4 mangle_output chain ===\n');
printf('%s\n', pcmd('nft list chain inet fw4 mangle_output 2>/dev/null'));
printf('%s\n', anon_text(fw4_mangle_out_txt));
printf('=== fw4 output chain ===\n');
printf('%s\n', pcmd('nft list chain inet fw4 output 2>/dev/null'));
printf('%s\n', anon_text(fw4_output_txt));
// --- recent mwan3 log ---
printf('=== Recent mwan3 Log (last 200 lines) ===\n');
printf('%s\n', pcmd('logread 2>/dev/null | grep -E "mwan3track\\[|mwan3-hotplug\\[|mwan3-init\\[|mwan3\\[" | tail -200'));
printf('%s\n', anon_text(log_txt));
printf('=== End of Report ===\n');
+178 -7
View File
@@ -5,7 +5,8 @@ import * as rtnl from "rtnl";
import * as uloop from "uloop";
import * as uci from "uci";
import * as ubus from "ubus";
import { open, readfile, popen, stat } from "fs";
import { open, readfile, popen, stat, mkdir, rename, unlink } from "fs";
import { log_open, log_verbose, log_msg as mlog, ucibool, is_default_equivalent } from 'mwan3.common';
const RTM_NEWROUTE = rtnl.const.RTM_NEWROUTE;
const RTM_DELROUTE = rtnl.const.RTM_DELROUTE;
@@ -32,6 +33,7 @@ let iface_list = []; // [ { name, family, tid, enabled, has_tracking } ]
let active_chains = {}; // { chain_name: true } cached from nft
let connected_timer = null; // debounce timer for connected set rebuilds
let last_connected_fingerprint = ""; // sorted element list from last populate call
let route_state_timer = null; // debounce timer for ROUTE_STATUS refresh
let ubus_conn;
// ---------------------------------------------------------------------------
@@ -40,7 +42,7 @@ let ubus_conn;
function log_msg(level, msg) {
warn(`mwan3rtmon[${family_name}] ${level}: ${msg}\n`);
mlog(level, `[${family_name}] ${msg}`);
}
// ---------------------------------------------------------------------------
@@ -52,6 +54,10 @@ function load_config() {
let cur = uci.cursor();
cur.load("mwan3");
// Verbose logging gate
log_verbose(ucibool(cur.get("mwan3", "globals", "verbose_logging") ?? "0"));
// MMX mask
mmx_mask = cur.get("mwan3", "globals", "mmx_mask") ?? "0x3F00";
@@ -219,9 +225,17 @@ function nft_exec(cmd) {
return true;
}
// Run a list of nft commands as a single nft -f transaction. The batch
// file is per-family: one mwan3rtmon instance runs per address family
// and each instance is single-threaded, so the family suffix alone
// keeps the two instances' batch files apart without locking. The file
// is removed on every exit path after creation. nft runs through a
// read-mode popen with stderr folded into stdout so the failure log
// carries nft's own error text.
function nft_batch(cmds) {
let tmpfile = "/var/run/mwan3/mwan3rtmon_nft_batch";
let tmpfile = "/var/run/mwan3/mwan3rtmon_nft_batch." + family_name;
let f = open(tmpfile, "w", 0600);
if (!f) {
log_msg("warn", "cannot open nft batch file");
@@ -232,10 +246,13 @@ function nft_batch(cmds) {
f.close();
let p = popen("nft -f " + tmpfile + " 2>&1");
if (!p)
if (!p) {
unlink(tmpfile);
return false;
}
let out = p.read("all");
let rc = p.close();
unlink(tmpfile);
if (rc != 0) {
log_msg("warn", "nft batch failed: " + (out ?? ""));
return false;
@@ -323,6 +340,126 @@ function is_linklocal_route(route) {
match(route.dst, /^169\.254\./) != null));
}
// Does this interface's own routing table hold a usable default route?
//
// This is the datapath truth: the interface's fwmark ip rule looks up
// exactly this table, so an interface whose table N holds no default route
// black-holes the traffic mwan3 marks to it, even when the main table still
// has a default via the same device. This mirrors the predicate the rpcd
// backend uses for has_default and the one mwan3-manage-rules.uc check-route
// uses. 'routes' is a single full route dump for this family (all tables).
function table_has_default(routes, tid, dev) {
for (let r in routes)
if (r.table == tid && is_default_route(r) && r.oif == dev)
return true;
return false;
}
// The interfaces this rtmon instance is responsible for: enabled, tracked,
// of this family, and currently bound to an l3 device. iface_list is built
// by load_config() and already carries name, family, tid, enabled, and
// has_tracking. The device comes from the same ubus network.interface dump
// build_dev_table_map() uses. An interface with no l3_device yet is skipped;
// it gets evaluated later when its device appears and routes change.
function tracked_interfaces() {
let ifaces = [];
if (!ubus_conn)
return ifaces;
let dump = ubus_conn.call("network.interface", "dump");
if (!dump || !dump.interface)
return ifaces;
let dev_by_name = {};
for (let intf in dump.interface)
if (intf.l3_device)
dev_by_name[intf.interface] = intf.l3_device;
for (let iface in iface_list) {
if (iface.family != family_name || !iface.enabled || !iface.has_tracking)
continue;
let dev = dev_by_name[iface.name];
if (dev == null)
continue;
push(ifaces, { name: iface.name, tid: iface.tid, dev: dev });
}
return ifaces;
}
// Write the interface's ROUTE_STATUS file, only when the value changes, and
// log the transition. The write is atomic (temp file + rename within the
// same tmpfs directory) so the tracker never reads a torn value. The
// tracker creates these directories, but rtmon may evaluate an interface
// before its tracker has, so mkdir best-effort first; it fails harmlessly
// if the directory already exists.
function write_route_state(ifname, state) {
let path = MWAN3TRACK_STATUS_DIR + "/" + ifname + "/ROUTE_STATUS";
let cur = trim(readfile(path) ?? "");
if (cur == state)
return;
mkdir(MWAN3TRACK_STATUS_DIR, 0700);
mkdir(MWAN3TRACK_STATUS_DIR + "/" + ifname, 0755);
let tmp = path + ".tmp";
let f = open(tmp, "w", 0644);
if (!f) {
log_msg("warn", "cannot open ROUTE_STATUS for " + ifname);
return;
}
f.write(state + "\n");
f.close();
if (!rename(tmp, path)) {
unlink(tmp);
log_msg("warn", "cannot commit ROUTE_STATUS for " + ifname);
return;
}
// A missing default route is abnormal, not routine failover, so log the
// loss at warn and the return to normal at notice.
log_msg(state == "down" ? "warn" : "notice", ifname + " default route " + state);
}
// Recompute and persist every responsible interface's route state from one
// route dump. The dump spans all tables for this family; table_has_default
// filters to each interface's own table. Called at startup, on SIGHUP, and
// debounced from the route-event handler.
function refresh_route_states() {
let ifaces = tracked_interfaces();
if (length(ifaces) == 0)
return;
let routes = rtnl.request(RTM_GETROUTE, NLM_F_DUMP, { family: family_num }) ?? [];
for (let iface in ifaces)
write_route_state(iface.name,
table_has_default(routes, iface.tid, iface.dev) ? "up" : "down");
}
// Arm the debounced refresh. Bursts of route events (PD renewal, reconnects,
// the boot-time route flood) collapse into a single sweep, exactly as the
// connected-set rebuild is debounced.
function arm_route_state_refresh() {
if (!route_state_timer)
route_state_timer = uloop.timer(DEBOUNCE_MS, () => {
refresh_route_states();
route_state_timer = null;
});
else
route_state_timer.set(DEBOUNCE_MS);
}
// Get all routes from main table (and extra lookup tables) via netlink
function get_all_routes() {
@@ -370,8 +507,18 @@ function populate_connected_set() {
let seen = {};
let elements = [];
// Main-table routes only. get_all_routes() also returns the extra lookup
// tables for the per-interface mirroring, but their routes belong to
// mwan3_custom_v4/v6, which grants the identical bypass and is maintained
// on those tables' own route events. Sweeping them in here as well would
// strand them: extra-table events never arm this rebuild, so a route
// deleted from its table would stay in the connected set indefinitely.
for (let route in routes) {
if (is_cidr_route(route) && !is_default_route(route) && !is_linklocal_route(route) && !seen[route.dst]) {
if (route.table != RT_TABLE_MAIN)
continue;
if (is_cidr_route(route) && !is_default_equivalent(route) && !is_linklocal_route(route) && !seen[route.dst]) {
push(elements, route.dst);
seen[route.dst] = true;
}
@@ -456,7 +603,7 @@ function repopulate_custom_sets() {
if (!extra_table_set[r.table])
continue;
let dst = r.dst;
if (dst == null || is_default_route(r) || is_linklocal_route(r))
if (dst == null || is_default_equivalent(r) || is_linklocal_route(r))
continue;
if (!seen[dst]) {
push(cmds, "add element inet mwan3 " + setname + " { " + dst + " }");
@@ -478,7 +625,7 @@ function repopulate_custom_sets() {
function handle_custom_set_event(route, is_new) {
let dst = route.dst;
if (dst == null || is_default_route(route) || is_linklocal_route(route))
if (dst == null || is_default_equivalent(route) || is_linklocal_route(route))
return;
let setname = (family_num == AF_INET) ? "mwan3_custom_v4" : "mwan3_custom_v6";
@@ -536,6 +683,10 @@ function handle_route_event(event) {
connected_timer.set(DEBOUNCE_MS);
}
// Re-evaluate every interface's default-route state on any routing change.
arm_route_state_refresh();
// -- Update per-interface routing tables --
build_dev_table_map();
@@ -594,6 +745,7 @@ function main() {
// Parse args
family_name = ARGV[0] ?? "ipv4";
log_open("mwan3rtmon");
if (family_name == "ipv6") {
if (stat("/proc/sys/net/ipv6") == null) {
@@ -610,6 +762,7 @@ function main() {
}
load_config();
log_msg("notice", "started");
// Connect to ubus
@@ -653,6 +806,9 @@ function main() {
log_msg("debug", "populating initial per-interface routes");
populate_iface_routes();
log_msg("debug", "initial route-state sweep");
refresh_route_states();
// Signal handlers for clean shutdown
uloop.signal("SIGTERM", () => {
@@ -669,8 +825,23 @@ function main() {
log_msg("debug", "received SIGHUP, reloading config");
load_config();
repopulate_custom_sets();
refresh_route_states();
});
// Slow periodic re-sweep as defense in depth: bounds recovery if a
// route-state change ever arrives without an accompanying main-table
// route event (a coalesced or missed netlink multicast). It is cheap
// and silent when nothing moves, since write_route_state only writes
// on an actual change.
function schedule_periodic_route_sweep() {
uloop.timer(20000, () => {
refresh_route_states();
schedule_periodic_route_sweep();
});
}
schedule_periodic_route_sweep();
log_msg("debug", "entering event loop");
uloop.run();
+22 -2
View File
@@ -299,7 +299,7 @@ main() {
trap config_reload HUP
load_tracking_config
local sleep_time result ping_status loss latency
local sleep_time result ping_status loss latency route_state route_state_prev probe_ips
mwan3_list_track_ips()
{
track_ips="$track_ips $1"
@@ -352,6 +352,7 @@ main() {
local lost=0
local turn=0
local failed_hosts=""
route_state_prev=""
firstconnect
while true; do
@@ -391,7 +392,26 @@ main() {
continue
fi
sleep_time=$interval
for track_ip in $track_ips; do
# An interface can be reachable to its tracking target yet hold no
# usable default route in its own table, in which case mwan3 marks
# traffic to it and the per-interface backstop drops it. mwan3rtmon
# writes the interface's default-route state to ROUTE_STATUS; treat
# "down" as a failed round and skip probing so the existing score
# machinery carries the interface offline, and back online when the
# route returns. An absent file means no route monitor has evaluated
# this interface, so probe exactly as before.
route_state=$(cat "$MWAN3TRACK_STATUS_DIR/$INTERFACE/ROUTE_STATUS" 2>/dev/null)
probe_ips=$track_ips
if [ "$route_state" = "down" ]; then
probe_ips=""
[ "$route_state_prev" != "down" ] && LOG warn "Interface $INTERFACE ($DEVICE) has no usable default route in its table; treating tracking round as failed"
elif [ "$route_state_prev" = "down" ]; then
LOG notice "Interface $INTERFACE ($DEVICE) default route restored"
fi
route_state_prev=$route_state
for track_ip in $probe_ips; do
if [ $host_up_count -lt $reliability ]; then
case "$track_method" in
ping)
+65 -7
View File
@@ -75,6 +75,16 @@ function parse_elem_val(v) {
return null;
}
// Allowlist for nft set elements written back to the kernel: IPv4 and IPv6
// addresses, CIDR prefixes and hyphen-written ranges only, which is exactly
// what the apply path emits. These values are interpolated into an nft add
// element command line built with popen, so anything carrying a character
// outside this class is dropped before it can break out of the element list.
function valid_nft_element(v) {
return match(v, /^[0-9A-Fa-f:.\/-]+$/) != null;
}
function count_nftset_elements(setname) {
if (!match(setname, /^[a-zA-Z0-9_-]+$/))
return 0;
@@ -216,6 +226,14 @@ function get_table_routes(table_id) {
}
function nslookup_resolve(host, type) {
// Reject any host outside the hostname character class before it is
// interpolated into the /bin/sh -c command line below. This is the single
// chokepoint for both resolve_host and the nftset_resolve domain path,
// whose UCI-supplied domain values are otherwise unvalidated.
if (!match(host, /^[a-zA-Z0-9._-]+$/))
return [];
const p = popen(sprintf('/bin/busybox nslookup -type=%s %s 127.0.0.1 2>/dev/null', type, host), 'r');
if (!p) return [];
const raw = p.read('all');
@@ -233,7 +251,6 @@ function nslookup_resolve(host, type) {
function routing_health() {
const uci = cursor();
const mmx_mask = int(uci.get('mwan3', 'globals', 'mmx_mask')) || 0x3F00;
let bitcnt = 0;
for (let m = mmx_mask; m; m >>= 1) bitcnt += m & 1;
@@ -250,34 +267,47 @@ function routing_health() {
UNREACH_BASE = 3000;
}
const SRC_BASE = UNREACH_BASE + iface_max + 1;
// Build ordered interface list with 1-based index (same ordering mwan3 uses)
const iface_order = [];
const iface_index = {};
const iface_family = {};
uci.foreach('mwan3', 'interface', intf => {
push(iface_order, intf['.name']);
iface_index[intf['.name']] = length(iface_order);
iface_family[intf['.name']] = intf['family'] || 'ipv4';
});
// Fetch all ip rules and index by priority for O(1) lookup
const all_rules = get_ip_rules();
const rule_by_priority = {};
const v4_rule_by_priority = {};
for (let rule in all_rules) {
if (rule?.priority != null)
if (rule?.priority != null) {
rule_by_priority[rule.priority] = rule;
if (rule.family == 2)
v4_rule_by_priority[rule.priority] = rule;
}
}
// Pre-build the set of priorities that correspond to current UCI interfaces
const valid_priorities = {};
for (let ifname in iface_order) {
const id = iface_index[ifname];
valid_priorities[IIF_BASE + id] = true;
valid_priorities[FWMARK_BASE + id] = true;
valid_priorities[UNREACH_BASE + id] = true;
valid_priorities[UNREACH_BASE + iface_max + 1 + id] = true;
}
valid_priorities[FWMARK_BASE + mmdefault - 2] = true;
valid_priorities[FWMARK_BASE + mmdefault - 1] = true;
// Per-interface health report
const result = {};
for (let ifname in iface_order) {
const id = iface_index[ifname];
@@ -319,17 +349,38 @@ function routing_health() {
})),
},
};
// The source band is IPv4-only, so test presence against the IPv4
// rule index alone. A device holds one source rule per global IPv4
// address, all sharing this priority, so a populated slot means the
// band exists for this interface, not that every address is covered.
if (iface_family[ifname] == 'ipv4') {
result[ifname].src_rule = {
present: v4_rule_by_priority[SRC_BASE + id] != null,
priority: SRC_BASE + id,
};
}
}
// Stale rules: priorities in mwan3 ranges but not matching any current UCI interface
const stale = [];
for (let rule in all_rules) {
const p = rule?.priority;
if (p == null) continue;
// The iif and fwmark windows are mmdefault wide (the fwmark band
// carries the global blackhole and unreachable rules above
// iface_max). The unreachable band holds only ids 1..iface_max;
// the slot above it is unused and the source band follows at
// iface_max + 1 + id.
const in_iif_range = (p > IIF_BASE && p <= IIF_BASE + mmdefault);
const in_fwmark_range = (p > FWMARK_BASE && p <= FWMARK_BASE + mmdefault);
const in_unreach_range = (p > UNREACH_BASE && p <= UNREACH_BASE + mmdefault);
if ((in_iif_range || in_fwmark_range || in_unreach_range) && !valid_priorities[p])
const in_unreach_range = (p > UNREACH_BASE && p <= UNREACH_BASE + iface_max);
const in_src_range = (p > UNREACH_BASE + iface_max + 1 && p <= UNREACH_BASE + 2 * iface_max + 1);
if ((in_iif_range || in_fwmark_range || in_unreach_range || in_src_range) && !valid_priorities[p])
push(stale, { priority: p });
}
@@ -339,7 +390,7 @@ function routing_health() {
interfaces: result,
stale_rules: stale,
mwan3_active: mwan3_active,
rule_bases: { iif: IIF_BASE, fwmark: FWMARK_BASE, unreach: UNREACH_BASE },
rule_bases: { iif: IIF_BASE, fwmark: FWMARK_BASE, unreach: UNREACH_BASE, src: SRC_BASE },
};
}
@@ -391,12 +442,14 @@ function get_policies(version) {
const family_filter = (version == '6') ? 'ipv6' : 'ipv4';
// Build interface family map: iface_name -> 'ipv4'/'ipv6'
const iface_family = {};
uci.foreach('mwan3', 'interface', intf => {
iface_family[intf['.name']] = intf['family'] || 'ipv4';
});
// Build member info map: member_name -> { interface, metric, weight }
const member_info = {};
uci.foreach('mwan3', 'member', m => {
member_info[m['.name']] = {
@@ -415,6 +468,7 @@ function get_policies(version) {
if (type(use_members) != 'array') use_members = [use_members];
// Collect members matching the requested address family
const by_metric = {};
for (let mname in use_members) {
const m = member_info[mname];
@@ -431,6 +485,7 @@ function get_policies(version) {
if (!length(keys(by_metric))) return;
// Find the lowest metric with at least one online member
const sorted_metrics = sort(keys(by_metric), (a, b) => int(a) - int(b));
let active_metric = null;
for (let metric in sorted_metrics) {
@@ -444,6 +499,7 @@ function get_policies(version) {
}
// Sum weights of online members at the active metric for percent calculation
let total_weight = 0;
if (active_metric != null) {
for (let m in by_metric[active_metric]) {
@@ -498,10 +554,12 @@ function interfaces_status(request) {
'packetloss': get_int(ifname, sprintf('LOSS_%s', ip)),
});
}
// Derive check_quality from LATENCY file content rather than UCI.
// UCI may be stale if check_quality was changed without restarting mwan3track.
// mwan3track only writes LATENCY_* files when check_quality=1, so file
// presence with content is the authoritative indicator of actual state.
let check_quality = false;
for (let tip in track_ips) {
const lat = get_str_raw(ifname, sprintf('LATENCY_%s', tip.ip));
@@ -694,7 +752,7 @@ const methods = {
if (type(entries) != 'array') entries = [entries];
for (let e in entries) {
const ev = ltrim(rtrim(e, ' \t\r\n'), ' \t\r\n');
if (length(ev) > 0) push(elements, ev);
if (length(ev) > 0 && valid_nft_element(ev)) push(elements, ev);
}
if (cfg.loadfile) {
const content = readfile(cfg.loadfile);
@@ -703,7 +761,7 @@ const methods = {
const ci = index(line, '#');
if (ci >= 0) line = substr(line, 0, ci);
line = ltrim(rtrim(line, ' \t\r\n'), ' \t\r\n');
if (length(line) > 0) push(elements, line);
if (length(line) > 0 && valid_nft_element(line)) push(elements, line);
}
}
}
@@ -0,0 +1,107 @@
'use strict';
// common.uc: the shared mwan3 ucode library, the ucode analogue of common.sh.
// Each shared ucode routine is defined here so it lives, and is tested, in one
// place.
import { openlog, syslog, LOG_PID, LOG_DAEMON } from 'log';
// ---- Logging ---------------------------------------------------------------
//
// All mwan3 ucode logs through these functions so the sink, tag format and
// verbose gate live in one place. Output goes to syslog, the same destination
// logger(1) reaches, so it appears in logread regardless of how procd handles
// the process stderr.
let verbose = false;
// Map the level names mwan3 uses (the shell's warn/error vocabulary and the
// canonical syslog names) onto the exact tokens parse_priority() accepts. It
// rejects "warn" and "error", so an unmapped name would be dropped; an unknown
// level falls back to notice so a mislabelled message still logs.
const PRIO = {
emerg: "emerg", alert: "alert", crit: "crit",
err: "err", error: "err",
warn: "warning", warning: "warning",
notice: "notice", info: "info", debug: "debug",
};
// Open the syslog connection with the given identity. LOG_PID appends the pid
// so the tag reads ident[pid], matching the shell's "${SCRIPTNAME}[$$]"
// convention. Facility daemon suits these long-running and service-invoked
// components.
function log_open(ident) {
openlog(ident, LOG_PID, LOG_DAEMON);
}
// Set the verbose gate. The caller reads mwan3.globals.verbose_logging and
// pushes the parsed bool here; debug is suppressed unless verbose, exactly as
// common.sh:LOG() gates the debug facility behind MWAN3_VERBOSE_LOGGING.
function log_verbose(enable) {
verbose = enable;
}
// Emit one message. debug is dropped unless verbose; every other level always
// logs. Message content is passed as a %s argument so it is never treated as a
// format string.
function log_msg(level, msg) {
if (level == "debug" && !verbose)
return;
syslog(PRIO[level] ?? "notice", "%s", msg);
}
// ---- Config helpers --------------------------------------------------------
// Parse a UCI bool the way the shell's config_get_bool does: 1/on/true/yes/
// enabled are true, everything else is false. Kept here so every ucode
// consumer interprets a UCI bool identically to the shell. It reads no config
// itself, so it does not couple the module to uci.
function ucibool(val) {
switch (val) {
case 'yes':
case 'on':
case 'true':
case 'enabled':
return true;
default:
return !!int(val);
}
}
// ---- Route classification --------------------------------------------------
// The width classifier for the bypass sweeps: a route is default-equivalent
// when its destination is absent (a literal default) or its prefix is wide
// enough that it can only exist as a component of an in-substance default
// route - /2 or wider for IPv4, /3 or wider for IPv6, which covers the
// split-half pairs VPN clients install and the 2000::/3 global-unicast
// aggregate. Each route is judged alone, so a half-installed pair is still
// excluded. The family comes from iptoarr, the inet_pton wrapper, so no
// address text is hand-parsed; a destination it cannot parse is not
// default-equivalent. The strict literal-default predicate the mirroring and
// route-state paths use is deliberately not widened and lives on beside this.
function is_default_equivalent(route) {
let dst = route.dst;
if (dst == null)
return true;
let slash = index(dst, "/");
if (slash < 0)
return false;
let a = iptoarr(substr(dst, 0, slash));
if (a == null)
return false;
return +substr(dst, slash + 1) <= (length(a) == 16 ? 3 : 2);
}
// ---- Exports ---------------------------------------------------------------
// The module's public interface. Declared as an export list rather than inline
// on each function, which this ucode build does not accept.
export { log_open, log_verbose, log_msg, ucibool, is_default_equivalent };