Dawnline 0.13.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions

- "Internet like a home device" starts off on new servers: sending the
  tunnel through the home network costs speed. Both server wizards (the
  first one and "Add server") have the switch, and on it says what it
  costs. Servers that have it on keep it
- With it off, Server → Access says what that means: DNS still goes
  through the router, its proxies and filters see the tunnel only once its
  interface is added to their source interfaces, and sites the router's
  DNS answers with proxy addresses won't open
- With it on, established connections skip the second pass through
  netfilter in Dawnline's network namespace (a software flowtable): about
  12% less router CPU per packet, and about a quarter more speed through a
  proxy on the router. Without kmod-nft-offload the old rules load and the
  service log says so
- Its address at home stays the same when it is turned off and on again;
  it moved down by one each time (.254, .253, .252)
- Less CPU for the same work: the background agent's once-a-second look at
  the tunnels, Status, Health and the portal no longer compile the same
  patterns again for each line, address and device. At idle the agent uses
  about a quarter of the CPU it did; a portal request 5-10 ms less
- On LuCI's Bootstrap themes the admin looks as it does on Outline: cards
  and menus a step above the page, icon tiles that keep their colour,
  Outline's status colours in dark mode. The choices in Settings → Logs &
  history and Updates are LuCI's own controls in every theme
- "Add from devices at home" keeps a device's name readable in a narrow
  window: its ports go under the name
- DESIGN.md describes the portal's look, components and motion, and the
  rules send portal work there first. lint-ucode no longer ends a function
  at a brace inside a template literal
This commit is contained in:
Aemeath committed 2026-10-21 01:42:23 +03:00
1 parent db9657c01c
commit 58492be021
44 files changed
+2269 -235

No files matched your search

@@ -28,6 +28,9 @@ export const OBF_CONF = {
const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh';
/** The packages AmneziaWG comes in (the Components tab installs them). */
const PACKAGES = [ 'kmod-amneziawg', 'amneziawg-tools' ];
// A module constant, compiled once (a literal is compiled each time it runs):
// dump() checks it on every line of `awg show all dump`, every second.
const DIGITS = /^[0-9]+$/;
/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */
function proto_handler() {
@@ -282,7 +285,7 @@ export function obf_errors(o) {
let v = o[k];
if (v == null || v == '')
continue;
if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1])
if (!match(v, DIGITS) || +v < r[0] || +v > r[1])
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
}
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
@@ -375,7 +378,7 @@ export function client_config(m, dev) {
if (!srv)
return null;
let host = core.endpoint_host(m, srv);
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
let ep = index(host, ':') >= 0 && substr(host, 0, 1) != '[' ? `[${host}]` : host;
let allowed = allowed_ips(m, srv, p);
let dns = core.client_dns(m, srv, p);
let mtu = core.device_mtu(srv, dev);
@@ -506,9 +509,10 @@ export function dump(wanted) {
let f = split(line, '\t');
if (length(f) < 5 || !valid_key(f[1]))
continue;
if (valid_key(f[2]) && match(f[3] ?? '', /^[0-9]+$/))
let key2 = valid_key(f[2]);
if (key2 && match(f[3] ?? '', DIGITS))
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
else if (length(f) >= 9 && (f[2] == '(none)' || valid_key(f[2]))) {
else if (length(f) >= 9 && (key2 || f[2] == '(none)')) {
let ep = f[3] == '(none)' ? '' : f[3];
out.peers[f[1]] = {
ifname: f[0],
@@ -654,6 +658,9 @@ export function probes(m, ctx) {
/* ---------- issued configurations ---------- */
const ISSUED = `${DATA_DIR}/issued.json`;
// The lines a fingerprint leaves out. A module constant, compiled once, not
// for each line of each device's configuration.
const DEVICE_OWN = /^(PrivateKey|Jc|Jmin|Jmax) /;
function fnv32(str) {
let h = 2166136261;
@@ -670,7 +677,7 @@ function fnv32(str) {
*/
export function config_fingerprint(m, dev) {
let c = dev ? client_config(m, dev) : null;
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^(PrivateKey|Jc|Jmin|Jmax) /)))) : null;
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, DEVICE_OWN)))) : null;
};
/** Device id → fingerprint of the configuration last shown or downloaded. */
@@ -4,7 +4,7 @@
import { cursor } from 'uci';
import {
valid_name, valid_key, valid_host, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
valid_name, valid_key, valid_host, valid_iface, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
} from 'dawnline.util';
import { _, N_ } from 'dawnline.i18n';
@@ -635,7 +635,7 @@ export function update_person(c, m, id, a) {
c.delete(CONFIG, id, 'home_net');
}
if (type(a.home_nets) == 'array') {
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), valid_iface));
if (length(nets))
c.set(CONFIG, id, 'home_net', nets);
else
@@ -895,7 +895,7 @@ export function wan_forwards(zone, proto) {
c.load('firewall');
let out = [];
c.foreach('firewall', 'redirect', (r) => {
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
if (substr(r['.name'], 0, 9) == 'dawnline_' || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
return;
// fw4's default is "tcp udp".
let protos = split(type(r.proto) == 'array' ? join(' ', r.proto) : r.proto ?? 'tcp udp', /[ ,]+/);
@@ -126,7 +126,7 @@ export function sync(m, dry) {
let stale = [];
c.foreach('firewall', null, (s) => {
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
if (substr(s['.name'], 0, 9) == 'dawnline_' && !want[s['.name']])
push(stale, s['.name']);
});
for (let s in stale) {
@@ -170,6 +170,9 @@ export function drift(m) {
};
const MARK_ALL = 0xffffffff;
// "1000: from all fwmark 0x1 lookup 100", or "fwmark 0x1/0xff". A module
// constant, compiled once, not for each rule.
const MARK_RULE = /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/;
function hx(n) {
return sprintf('0x%x', n);
@@ -184,8 +187,7 @@ export function proxy_diverts() {
let out = [], seen = {};
for (let fam in [ '-4', '-6' ])
for (let line in split(sh_out(`ip ${fam} rule show 2>/dev/null`) ?? '', '\n')) {
// "1000: from all fwmark 0x1 lookup 100", or "fwmark 0x1/0xff".
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/);
let mm = match(line, MARK_RULE);
if (!mm || +mm[1] >= 32766)
continue;
let d = { pref: +mm[1], mark: hex(mm[2]), mask: mm[4] ? hex(mm[4]) : MARK_ALL, table: mm[5] };
@@ -45,19 +45,27 @@ export function needs() {
};
};
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
// A module constant, compiled once: a literal in the loop would be compiled
// again for every socket (0.12 ms each on the WR3000P, some 90 sockets a call).
const UDP_UNCONNECTED = /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /;
/** UDP ports an unconnected socket is bound to (IPv4 and IPv6): nothing else can listen there. */
export function udp_bound() {
let out = {};
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
for (let line in split(readfile(f) ?? '', '\n')) {
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
let m = match(line, /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /);
let m = match(line, UDP_UNCONNECTED);
if (m)
out[hex(m[1])] = true;
}
return map(keys(out), (k) => +k);
};
// netstat's columns and the port of "0.0.0.0:53" / ":::53". Module constants,
// compiled once, not for each socket.
const BLANKS = /[ \t]+/, PORT_SUFFIX = /:([0-9]+)$/;
/**
* Programs on 'tcp' or 'udp' ports, our portal left out: { port: "dnsmasq" }.
* Kernel sockets (a tunnel's) have no name.
@@ -65,10 +73,10 @@ export function udp_bound() {
function port_programs(proto) {
let out = {};
for (let line in split(sh_out(`netstat -ln${proto == 'tcp' ? 't' : 'u'}p 2>/dev/null`) ?? '', '\n')) {
let f = split(trim(line), /[ \t]+/);
let f = split(trim(line), BLANKS);
if (f[0] != proto && f[0] != `${proto}6`)
continue;
let m = match(f[3] ?? '', /:([0-9]+)$/);
let m = match(f[3] ?? '', PORT_SUFFIX);
let owner = split(f[length(f) - 1], '/');
if (!m || !owner[1] || out[m[1]])
continue;
@@ -264,6 +272,9 @@ function endpoint_check(id, title, problem, srv, host, proto_note) {
return check(id, title, w.status, w.text, null, problem);
}
// "1000: from all fwmark 0x1 lookup 100". A module constant, compiled once, not for each rule.
const MARK_RULE = /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/;
/**
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
* Dawnline's (pref < 5205) whose table has a default route of its own sends
@@ -273,7 +284,7 @@ function endpoint_check(id, title, problem, srv, host, proto_note) {
function policy_routing() {
let out = [];
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/);
let mm = match(line, MARK_RULE);
if (!mm || +mm[1] >= 5205)
continue;
let routes = sh_out(`ip -4 route show table ${q(mm[4])} 2>/dev/null`) ?? '';
@@ -124,8 +124,12 @@ export function online(dmp, id, peer) {
return !!(peer && peer.handshake > 0 && time() - peer.handshake < ONLINE_WINDOW);
};
// "203.0.113.7:41821", "[2001:db8::1]:41821". A module constant, compiled once:
// the agent's watcher asks for every device, every second.
const ENDPOINT = /^\[?([^\]]+)\]?:[0-9]+$/;
export function endpoint_ip(ep) {
let m = match(ep ?? '', /^\[?([^\]]+)\]?:[0-9]+$/);
let m = match(ep ?? '', ENDPOINT);
return m ? m[1] : ep;
};
@@ -7,13 +7,24 @@
// └── NAT to a LAN address ┘
//
// The netns is one more device on the LAN bridge with its own address (picked
// from the LAN subnet above the DHCP pool). Replies come back the same way.
// from the LAN subnet above the DHCP pool) and its own MAC (hashed from the
// bridge's), the same each time it is created: the router's neighbour table
// knows the address by that MAC, so a netns created again keeps its address
// instead of seeing it held by another device. Replies come back the same way.
// Home-network destinations keep their direct route; per-person access is
// still enforced on dawn0 before any of this (table inet dawnline).
//
// Clients also use the netns address as DNS: it forwards to the DNS the LAN
// gets from DHCP, from the LAN side, so DNS interception applies as well.
//
// The netns forwards and NATs every packet a second time (conntrack, the
// forward hook): about 40% more CPU per packet on an MT7981. A flowtable on
// its two links (dlx1, dll1) lets established TCP and UDP flows skip that
// work. The netns holds no access rules: who may reach what is judged on the
// tunnel interfaces in the root namespace, which no flowtable here touches.
// Without kernel flowtables (kmod-nft-offload) the loop runs as before,
// slower, and logs it once.
//
// Separately, people with Home-only access get a plain resolver
// (dawnline.resolver). While the netns exists it runs inside it and sends its
// upstream queries back out through the transit link as forwarded traffic —
@@ -41,6 +52,7 @@ const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.la
const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
export const RESOLVER_CONF = resolver.CONF;
const STATE = `${RUN_DIR}/loop.json`;
const NS_RULES = '/var/etc/dawnline-ns.nft';
const WHO = L_('Internet like a home device');
@@ -106,39 +118,64 @@ function used_addresses(dev) {
return used;
}
/** The MAC the netns's LAN link has now; null without the link. */
function our_mac() {
return sh_out(`ip -n ${NS} -j link show ${LAN_NS} 2>/dev/null | jsonfilter -e '@[0].address'`);
}
/** 32-bit FNV-1a of a string, continuing from `h`. */
function fnv1a(s, h) {
for (let i = 0; i < length(s); i++)
h = ((h ^ ord(s, i)) * 16777619) & 0xffffffff;
return h;
}
/**
* A LAN address for the netns: keep the saved one while it is valid and not
* taken by someone else, otherwise the highest free host above the DHCP pool
* (then below it), skipping static leases and anything that answers.
* The MAC for the netns's LAN link, from the bridge's MAC: a locally
* administered unicast address hashed from it, so it is the same every time
* and differs between routers. Not the bridge's MAC with a bit flipped: radios
* and ports often get those.
*/
function pick_address(lan, facts, saved, dev) {
export function lan_mac(bridge) {
let s = lc(trim(bridge ?? ''));
let h1 = fnv1a(`dawnline lan ${s}`, 0x811c9dc5), h2 = fnv1a(s, h1);
let b = [ ((h1 >> 24) & 0xfc) | 0x02, (h1 >> 16) & 0xff, (h1 >> 8) & 0xff, h1 & 0xff, (h2 >> 24) & 0xff, (h2 >> 16) & 0xff ];
return join(':', map(b, (x) => sprintf('%02x', x)));
};
/**
* True when the netns may use a LAN address (a number): a host of the
* network, not the router's, not a static lease, outside the DHCP pool and
* not held by another device in `used` (address → MAC, or true without one).
* An entry with one of the MACs in `mine` is the netns itself, also from
* before it was created again.
*/
export function address_free(ip, lan, facts, used, mine) {
if (ip <= lan.net || ip >= lan.net + lan.size - 1 || ip == lan.ip || index(facts.statics, ip) >= 0)
return false;
if (facts.pool && ip >= facts.pool[0] && ip <= facts.pool[1])
return false;
let u = used[int2ip(ip)];
return u == null || index(mine, u) >= 0;
};
/**
* A LAN address for the netns: keep the saved one while it is free (see
* address_free; `mine` are the netns's MACs), otherwise the highest free host
* above the DHCP pool (then below it) that does not answer.
*/
function pick_address(lan, facts, saved, dev, mine) {
let used = used_addresses(dev);
let mine = our_mac();
let taken = (ip) => {
let s = int2ip(ip);
if (ip == lan.ip || index(facts.statics, ip) >= 0)
return true;
if (facts.pool && ip >= facts.pool[0] && ip <= facts.pool[1])
return true;
let u = used[s];
return u != null && !(mine && u == mine);
};
let sv = ip2int(saved ?? '');
if (sv != null && sv > lan.net && sv < lan.net + lan.size - 1 && !taken(sv))
if (sv != null && address_free(sv, lan, facts, used, mine))
return int2ip(sv);
for (let ip = lan.net + lan.size - 2; ip > lan.net; ip--) {
if (taken(ip))
if (!address_free(ip, lan, facts, used, mine))
continue;
// Last check: nobody answers on it.
sh(`ping -c 1 -W 1 -I ${q(dev)} ${int2ip(ip)}`);
let again = used_addresses(dev)[int2ip(ip)];
if (again != null && !(mine && again == mine))
continue;
return int2ip(ip);
if (address_free(ip, lan, facts, used_addresses(dev), mine))
return int2ip(ip);
}
return null;
}
@@ -271,7 +308,9 @@ export function plan(m) {
return { error: { code: 'no_ipv4', dev } };
let facts = dhcp_facts(d.logical, lan);
let st = settings();
let addr = pick_address(lan, facts, st.lan_address, dev);
let mac = lan_mac(readfile(`/sys/class/net/${dev}/address`));
// The netns's MACs: the one it gets, and the one it has (a random one from an older version).
let addr = pick_address(lan, facts, st.lan_address, dev, [ mac, our_mac() ]);
if (!addr)
return { error: { code: 'no_address', net: `${int2ip(lan.net)}/${lan.prefix}` } };
let last = read_json(STATE, {});
@@ -291,6 +330,7 @@ export function plan(m) {
dev,
gateway: int2ip(lan.ip),
address: addr,
mac,
prefix: lan.prefix,
dns: facts.dns ?? int2ip(lan.ip),
transit: tx,
@@ -303,10 +343,20 @@ export function plan(m) {
/* ---------- apply ---------- */
function ns_rules(p) {
/**
* The netns's nft script as text (nothing is loaded). With `fast`, a
* flowtable on the netns's own two links takes established TCP and UDP flows
* past conntrack and the forward hook here. Only dlx1 and dll1: the root
* namespace's links (dawn0, dlx0) stay out, the guard there sees every packet.
*/
export function ns_rules(p, fast) {
return `table inet dawnline
delete table inet dawnline
table inet dawnline {
table inet dawnline {${fast ? `
flowtable ft {
hook ingress priority 0;
devices = { "${TX_NS}", "${LAN_NS}" };
}` : ''}
chain nat_pre {
type nat hook prerouting priority dstnat; policy accept;
iifname "${TX_NS}" ip daddr ${p.address} meta l4proto { tcp, udp } th dport 53 dnat ip to ${p.dns}:53
@@ -316,7 +366,8 @@ table inet dawnline {
oifname "${LAN_NS}" masquerade
}
chain filter_forward {
type filter hook forward priority filter; policy drop;
type filter hook forward priority filter; policy drop;${fast ? `
ct state established meta l4proto { tcp, udp } flow add @ft` : ''}
ct state established,related accept
iifname "${TX_NS}" oifname "${LAN_NS}" accept
}
@@ -329,6 +380,21 @@ table inet dawnline {
}
}
`;
};
/**
* Load the netns's rules, with the flowtable when the kernel takes it, else
* without (the loop works either way). { fast, slow, err }: slow is why the
* flowtable failed, err why the rules without it failed too.
*/
function load_ns_rules(p) {
ensure_dir('/var/etc');
let load = (fast) => {
writefile(NS_RULES, ns_rules(p, fast));
return run([ `ip netns exec ${NS} nft -f ${NS_RULES}` ])[0];
};
let slow = load(true);
return slow ? { fast: false, slow, err: load(false) } : { fast: true };
}
/** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */
@@ -382,21 +448,27 @@ function tunnel_ifnames() {
return out;
}
/** Remove the netns, links and rules. */
/** Remove the netns, links and rules, and the router's neighbour entry for the netns. */
export function remove(ifnames) {
ifnames ??= tunnel_ifnames();
let last = read_json(STATE, {})?.plan;
// Read while the link is there: the entry is ours when it carries the netns's MAC.
let held = last?.dev ? used_addresses(last.dev)[last.address] : null;
let stale = type(held) == 'string' && index([ last.mac, our_mac() ], held) >= 0;
let cmds = [];
for (let r in current_rules(ifnames))
push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`);
let t = read_json(STATE, {})?.plan?.table;
if (t)
push(cmds, `ip -4 route flush table ${t}`);
if (last?.table)
push(cmds, `ip -4 route flush table ${last.table}`);
if (exists(TX_ROOT))
push(cmds, `ip link del ${TX_ROOT}`);
if (exists(LAN_ROOT))
push(cmds, `ip link del ${LAN_ROOT}`);
if (stat(`/var/run/netns/${NS}`))
push(cmds, `ip netns del ${NS}`);
// Left there, it would hold the address for a MAC nobody has.
if (stale)
push(cmds, `ip -4 neigh del ${q(last.address)} dev ${q(last.dev)}`);
run(cmds);
unlink(STATE);
};
@@ -427,13 +499,18 @@ export function ensure(m, force) {
if (same && healthy && !length(rules))
return p;
// A link made by an older version has a random MAC (its plan had none, so
// this runs once after an update): it gets the stable one.
let remac = exists(LAN_ROOT) && our_mac() != p.mac;
let cmds = [];
if (!stat(`/var/run/netns/${NS}`))
push(cmds, `ip netns add ${NS}`);
if (!exists(TX_ROOT))
push(cmds, `ip link add ${TX_ROOT} type veth peer name ${TX_NS} netns ${NS}`);
if (!exists(LAN_ROOT))
push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} netns ${NS}`);
push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} address ${p.mac} netns ${NS}`);
if (remac)
push(cmds, `ip -n ${NS} link set ${LAN_NS} down`, `ip -n ${NS} link set ${LAN_NS} address ${p.mac}`);
let errs = run(cmds);
cmds = [
`ip addr flush dev ${TX_ROOT}`,
@@ -457,10 +534,13 @@ export function ensure(m, force) {
];
for (let s in p.servers)
push(cmds, `ip -n ${NS} route replace ${q(s.subnet)} via ${q(p.tx_root)} dev ${TX_NS}`);
ensure_dir('/var/etc');
writefile('/var/etc/dawnline-ns.nft', ns_rules(p));
push(cmds, `ip netns exec ${NS} nft -f /var/etc/dawnline-ns.nft`);
// The router knows the address by the old MAC: ask again now, not when the entry expires.
if (remac)
push(cmds, `ip -4 neigh flush to ${p.address} dev ${q(p.dev)}`);
push(errs, ...run(cmds));
let ft = load_ns_rules(p);
if (ft.err)
push(errs, ft.err);
push(errs, ...run(sync_rules(p, ifnames)));
if (length(errs)) {
@@ -472,11 +552,17 @@ export function ensure(m, force) {
return { error: why };
}
ensure_dir(RUN_DIR);
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
write_json(STATE, { applied: time(), plan: p, transit: p.transit, fast: ft.fast }, 0o644);
if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
log(sprintf(L_('is on · traffic enters %s as %s'), p.dev, p.address), 'up');
else if (!healthy)
log(sprintf(L_('was broken - set up again (%s as %s)'), p.dev, p.address), 'repair');
// Once, not again on every apply while the module is still missing.
if (!ft.fast && last.fast !== false)
log(L_('runs without its fast path'), 'info', join('\n', [
L_('Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline.'),
ft.slow,
]));
return p;
};
@@ -163,7 +163,7 @@ export function snapshot(fresh) {
let flags = hex(sysread(dev, 'flags') || '0');
let kind = +(sysread(dev, 'type') || '0');
let master = readlink(`${SYS}/${dev}/master`);
master = master ? replace(master, /^.*\//, '') : null;
master = master ? substr(master, rindex(master, '/') + 1) : null;
let bridge = stat(`${SYS}/${dev}/bridge`) != null;
let wifi = stat(`${SYS}/${dev}/phy80211`) != null || stat(`${SYS}/${dev}/wireless`) != null;
let nets = routes[dev] ? collapse(routes[dev]) : [];
@@ -295,10 +295,13 @@ export function lan_names() {
return out;
};
// A module constant, compiled once: event_hosts runs for every event of the log.
const ANY_IPV4 = /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g;
/** Event addresses that belong to devices at home, with their names ({ ip: name }). */
export function event_hosts(e, names) {
let out = null;
for (let ip in match(e.detail ?? '', /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g) ?? [])
for (let ip in match(e.detail ?? '', ANY_IPV4) ?? [])
if (names[ip[0]])
(out ??= {})[ip[0]] = names[ip[0]];
return out;
@@ -21,11 +21,14 @@ export function name_covers(name, host) {
return substr(name, 0, 2) == '*.' && dot > 0 && substr(host, dot) == substr(name, 1);
};
// A module constant, compiled once, not for each file of the directory.
const FULLCHAIN = /^(.+)\.fullchain\.crt$/;
/** ACME certificates on the router and the names each covers. */
export function acme_certs() {
let out = [];
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
let m = match(f, /^(.+)\.fullchain\.crt$/);
let m = match(f, FULLCHAIN);
if (!m)
continue;
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
@@ -325,7 +325,8 @@ function server_create(a) {
set('detected_wan', snap.wan);
if (snap.lan)
set('detected_lan', snap.lan);
set('lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
// Off unless asked for: the loop through the LAN costs speed (the wizard says how much).
set('lan_like', a.lan_like === true || a.lan_like === 1 || a.lan_like === '1' ? '1' : '0');
set('enabled', '1');
if (a.portal_enabled != null) {
let on = a.portal_enabled === true || a.portal_enabled === 1 || a.portal_enabled === '1';
@@ -44,11 +44,14 @@ function awg_tunnels() {
return out;
}
// A line of /etc/openwrt_release. A module constant, compiled once, not for each line.
const RELEASE_LINE = /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/;
function status(a) {
let m = core.load();
let rel = {};
for (let line in split(readfile('/etc/openwrt_release') ?? '', '\n')) {
let x = match(line, /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/);
let x = match(line, RELEASE_LINE);
if (x)
rel[lc(x[1])] = x[2];
}
@@ -5,7 +5,7 @@
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
import { _ } from 'dawnline.i18n';
export const VERSION = '0.12.1';
export const VERSION = '0.13.0';
/** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline';
@@ -365,8 +365,14 @@ export function slog_restore() {
/* ---------- IPv4 ---------- */
// Module constants, compiled once: a regex literal is compiled again each
// time it runs (rules/backend.md), and these run for every address and every
// network in a list (status, the portal, the agent's checks).
const IPV4 = /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/;
const CIDR = /^([0-9.]+)(\/([0-9]+))?$/;
export function ip2int(ip) {
let m = match(ip, /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/);
let m = match(ip, IPV4);
if (!m)
return null;
let n = 0;
@@ -389,7 +395,7 @@ export function int2ip(n) {
* allowed networks use this; parse_cidr is the stricter one for subnets.
*/
export function cidr_any(s) {
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
let m = match(s ?? '', CIDR);
if (!m)
return null;
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
@@ -432,10 +438,10 @@ export function cloudflare_ip(a) {
/** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */
export function parse_cidr(cidr) {
let m = match(cidr ?? '', /^([0-9.]+)\/([0-9]+)$/);
if (!m)
let m = match(cidr ?? '', CIDR);
if (!m || m[3] == null)
return null;
let ip = ip2int(m[1]), prefix = +m[2];
let ip = ip2int(m[1]), prefix = +m[3];
if (ip == null || prefix < 8 || prefix > 30)
return null;
let size = 1 << (32 - prefix);
@@ -549,8 +555,24 @@ export function name_rule() {
return _('Enter a name: up to 48 characters, without < > " or \\.');
};
// Character sets for checks written without a regex: ucode compiles a regex
// literal each time it runs, and musl's regcomp takes milliseconds for a
// bounded repeat (rules/backend.md). ltrim stops at a NUL byte, so a string
// with one fails these checks (a regex looks only up to it).
const ASCII_ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const B64 = `${ASCII_ALNUM}+/`;
// 32 bytes are 43 base64 characters: the last holds four bits of the key and two zero bits.
const KEY_LAST = 'AEIMQUYcgkosw048';
/**
* A (Amnezia)WireGuard key: 32 bytes in base64, 43 characters and "=", the
* same as /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/ without its 1.7 ms
* compile on the WR3000P: the agent's watcher checks two keys per line of
* `awg show all dump` every second. This takes about 0.03 ms.
*/
export function valid_key(s) {
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
return type(s) == 'string' && length(s) == 44 && substr(s, 43) == '=' &&
index(KEY_LAST, substr(s, 42, 1)) >= 0 && ltrim(substr(s, 0, 42), B64) == '';
};
/** An IPv6 address in its usual spelling (no zone, no brackets). */
@@ -558,10 +580,25 @@ export function is_ip6(s) {
return type(s) == 'string' && match(s, /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/) != null && match(s, /:::/) == null;
};
const LABEL = `${ASCII_ALNUM}-`;
/**
* Dot-separated labels of 1-63 letters, digits and dashes, none starting or
* ending with a dash: the same as
* /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/
* without its 10 ms compile on the WR3000P.
*/
function host_name(s) {
for (let l in split(s, '.'))
if (length(l) < 1 || length(l) > 63 || ltrim(l, LABEL) != '' ||
index(ASCII_ALNUM, substr(l, 0, 1)) < 0 || index(ASCII_ALNUM, substr(l, -1)) < 0)
return false;
return true;
}
/** A host name or an IP address, as a public address or the portal's name may be given. */
export function valid_host(s) {
return type(s) == 'string' && length(s) <= 253 &&
(match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null ||
ip2int(s) != null || is_ip6(s));
return type(s) == 'string' && length(s) <= 253 && (host_name(s) || ip2int(s) != null || is_ip6(s));
};
/** YYYY-MM-DD, and a day that exists (2026-02-30 does not). */
@@ -573,11 +610,18 @@ export function valid_date(s) {
return l.year == +m[1] && l.mon == +m[2] && l.mday == +m[3];
};
// Runs of other characters become one dash. Module constants: host_label and
// tunnel_name run for every device of a status or a portal answer.
const NOT_LC_ALNUM = /[^a-z0-9]+/g, NOT_ALNUM = /[^A-Za-z0-9]+/g;
// Names Windows keeps for devices: no file may be called that, whatever the case.
const WIN_DEVICES = [ 'con', 'prn', 'aux', 'nul', 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',
'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9' ];
/** Turn a display name into a portal slug candidate ("Мама Таня" → "mama-tanya"). */
export function slugify(s) {
let out = lc(translit(trim(`${s ?? ''}`)));
out = replace(out, /[^a-z0-9]+/g, '-');
out = replace(out, /^-+|-+$/g, '');
out = replace(out, NOT_LC_ALNUM, '-');
out = trim(out, '-');
return substr(out, 0, 32) || 'user';
};
@@ -586,8 +630,8 @@ export function slugify(s) {
* "telefon"): at most 40 characters, "device" when nothing is left.
*/
export function host_label(s) {
let l = replace(lc(translit(`${s ?? ''}`)), /[^a-z0-9]+/g, '-');
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 40), /-+$/g, '');
let l = replace(lc(translit(`${s ?? ''}`)), NOT_LC_ALNUM, '-');
l = rtrim(substr(trim(l, '-'), 0, 40), '-');
return l || 'device';
};
@@ -598,9 +642,9 @@ export function host_label(s) {
* refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left.
*/
export function tunnel_name(s) {
let l = replace(translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-');
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, '');
return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline';
let l = replace(translit(`${s ?? ''}`), NOT_ALNUM, '-');
l = rtrim(substr(trim(l, '-'), 0, 15), '-');
return l && index(WIN_DEVICES, lc(l)) < 0 ? l : 'dawnline';
};
/* ---------- time ---------- */
@@ -660,9 +704,21 @@ export function now() {
return time();
};
const IFACE = `${ASCII_ALNUM}_.@-`;
/**
* A netifd interface name (network.interface.<name>, a person's home network):
* 1-32 letters, digits and _ . @ -, the same as /^[A-Za-z0-9_.@-]{1,32}$/
* without its 3 ms compile on the WR3000P (iface_status runs several times for
* the Overview's status, and in the agent's minute checks).
*/
export function valid_iface(s) {
return type(s) == 'string' && length(s) >= 1 && length(s) <= 32 && ltrim(s, IFACE) == '';
};
/** netifd's view of an interface (ubus network.interface.<name> status), or null. */
export function iface_status(ifname) {
if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/))
if (!valid_iface(ifname))
return null;
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
if (!s)