LuCI admin (people, devices, limits, disguise, health, updates, backups) and a personal self-service portal, built as ipk (OpenWrt 24.10) and apk (OpenWrt 25.12) with the OpenWrt SDK. Successor of openwrt-liminal. - install.sh: checks the router, installs AmneziaWG for its firmware, then the release package verified against sha256sums.txt - CI: Prettier, types, tests, committed bundles, ShellCheck, ucode checks; tagged releases build both packages and publish them - Web bundles minified with esbuild (JS and CSS) - README with framed screenshots
This commit is contained in:
commit
a3910f8b97
105 files changed
+22278
No files matched your search
+125
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/ucode
|
||||
// Dawnline command line: `dawnline help`.
|
||||
'use strict';
|
||||
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as view from 'dawnline.view';
|
||||
import * as ops from 'dawnline.ops';
|
||||
import { VERSION } from 'dawnline.util';
|
||||
|
||||
const args = ARGV;
|
||||
const cmd = args[0] ?? 'help';
|
||||
|
||||
function out(v) {
|
||||
print(type(v) == 'string' ? v + '\n' : sprintf('%.J\n', v));
|
||||
}
|
||||
|
||||
function opt(name, dflt) {
|
||||
for (let i = 1; i < length(args); i++)
|
||||
if (args[i] == `--${name}`)
|
||||
return args[i + 1];
|
||||
return dflt;
|
||||
}
|
||||
|
||||
function help() {
|
||||
out(`Dawnline ${VERSION}
|
||||
|
||||
Usage: dawnline <command>
|
||||
|
||||
apply Reconcile router configuration and runtime state
|
||||
sync Push devices and access rules to the tunnel
|
||||
status People and devices with live state (JSON)
|
||||
health Run health checks (JSON)
|
||||
person add <name> [--slug s] [--access lan|internet|both] [--devices n]
|
||||
[--expires YYYY-MM-DD] [--quota GB]
|
||||
person link <slug> Print the personal portal link
|
||||
person rm <slug> Remove a person and their devices
|
||||
device add <slug> <name> [--kind phone|computer|tablet|router]
|
||||
device conf <id> Print a device configuration
|
||||
device rm <id> Remove a device
|
||||
backup Create a backup in /etc/dawnline/backups
|
||||
portal-cert Print the certificate and key the portal uses
|
||||
portal-http-port Print the plain-HTTP port when an IP is among the portal addresses
|
||||
teardown Remove everything Dawnline created on the router
|
||||
version`);
|
||||
}
|
||||
|
||||
function commit(c) {
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
}
|
||||
|
||||
try {
|
||||
if (cmd == 'apply')
|
||||
out(apply.apply());
|
||||
else if (cmd == 'sync')
|
||||
out(apply.sync());
|
||||
else if (cmd == 'status') {
|
||||
let m = core.load(), u = core.load_usage(), d = live.dump(), st = view.states(m, u);
|
||||
out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })));
|
||||
}
|
||||
else if (cmd == 'health')
|
||||
out(ops.health());
|
||||
else if (cmd == 'person' && args[1] == 'add') {
|
||||
let c = core.open_cursor(), m = core.load(c);
|
||||
let id = core.create_person(c, m, {
|
||||
name: args[2], slug: opt('slug'), access: opt('access', 'internet'),
|
||||
device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'),
|
||||
});
|
||||
commit(c);
|
||||
let m2 = core.load();
|
||||
out(core.portal_url(m2, m2.people[id]) ?? id);
|
||||
}
|
||||
else if (cmd == 'person' && args[1] == 'link') {
|
||||
let m = core.load();
|
||||
let p = m.people[args[2]] ?? die('Unknown person.');
|
||||
out(core.portal_url(m, p) ?? 'Set settings.portal_host first.');
|
||||
}
|
||||
else if (cmd == 'person' && args[1] == 'rm') {
|
||||
let c = core.open_cursor(), m = core.load(c);
|
||||
core.delete_person(c, m, args[2]);
|
||||
commit(c);
|
||||
apply.sync();
|
||||
}
|
||||
else if (cmd == 'device' && args[1] == 'add') {
|
||||
let c = core.open_cursor(), m = core.load(c);
|
||||
let id = core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin' });
|
||||
commit(c);
|
||||
apply.sync();
|
||||
out(id);
|
||||
}
|
||||
else if (cmd == 'device' && args[1] == 'conf') {
|
||||
let m = core.load();
|
||||
let d = m.devices[args[2]] ?? die('Unknown device.');
|
||||
print(core.client_config(m, d).conf);
|
||||
}
|
||||
else if (cmd == 'device' && args[1] == 'rm') {
|
||||
let c = core.open_cursor(), m = core.load(c);
|
||||
core.delete_device(c, m, args[2]);
|
||||
commit(c);
|
||||
apply.sync();
|
||||
}
|
||||
else if (cmd == 'backup')
|
||||
out(ops.backup_create(opt('reason')));
|
||||
else if (cmd == 'portal-cert') {
|
||||
let c = ops.portal_cert(core.load().settings);
|
||||
out(`${c.cert} ${c.key}`);
|
||||
}
|
||||
else if (cmd == 'portal-http-port') {
|
||||
let m = core.load();
|
||||
if (core.portal_http(m))
|
||||
out(`${core.portal_http_port(m)}`);
|
||||
}
|
||||
else if (cmd == 'teardown')
|
||||
apply.teardown();
|
||||
else if (cmd == 'version')
|
||||
out(VERSION);
|
||||
else
|
||||
help();
|
||||
}
|
||||
catch (e) {
|
||||
warn(`dawnline: ${e.message}\n`);
|
||||
exit(1);
|
||||
}
|
||||
+334
@@ -0,0 +1,334 @@
|
||||
#!/usr/bin/ucode
|
||||
// Dawnline agent (procd instance). Every minute it:
|
||||
// * folds AmneziaWG counters into usage (tmpfs; flushed to flash hourly)
|
||||
// * saves the activity log to flash as often as Settings says (or never)
|
||||
// * keeps the "like a home device" path and the Home-only resolver up
|
||||
// * logs connects, disconnects and roaming
|
||||
// * enforces end dates, quotas, schedules and pauses (peers + nft sets)
|
||||
// * watches the tunnel interfaces
|
||||
'use strict';
|
||||
|
||||
import * as uloop from 'uloop';
|
||||
import { readfile, stat, unlink } from 'fs';
|
||||
import { read_json, write_json, ensure_dir, sh_out, q, DATA_DIR, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as ops from 'dawnline.ops';
|
||||
import * as geo from 'dawnline.geo';
|
||||
|
||||
const TICK = 60 * 1000;
|
||||
const FLUSH_EVERY = 3600;
|
||||
const LOG_FLUSH = { '10min': 600, hourly: 3600 };
|
||||
const RESYNC_EVERY = 600;
|
||||
|
||||
let usage = live.load_usage();
|
||||
let last_states = null;
|
||||
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
|
||||
// swallow connects that happened in between.
|
||||
let presence = read_json(`${RUN_DIR}/presence.json`, {});
|
||||
let last_online = presence.online ?? {};
|
||||
let last_endpoint = presence.endpoint ?? {};
|
||||
let offline_ticks = {};
|
||||
let iface_down = {};
|
||||
let last_flush = time();
|
||||
let last_log_flush = time();
|
||||
let last_net = null;
|
||||
let rate_prev = null;
|
||||
|
||||
/**
|
||||
* Throughput per server for the Overview's "Speed now": bytes per second
|
||||
* over the last minute, newest 30 points, kept in tmpfs only.
|
||||
*/
|
||||
function record_rate(m) {
|
||||
let ts = time();
|
||||
let now = {};
|
||||
for (let pid, p in m.people) {
|
||||
let t = usage.people?.[pid]?.total;
|
||||
if (!t)
|
||||
continue;
|
||||
now[p.server] ??= [ 0, 0 ];
|
||||
now[p.server][0] += t[0];
|
||||
now[p.server][1] += t[1];
|
||||
}
|
||||
let hist = read_json(`${RUN_DIR}/rate.json`, {});
|
||||
// Per person: the last 15 points (People list, person page).
|
||||
let people = read_json(`${RUN_DIR}/rate_people.json`, {});
|
||||
if (type(people) != 'object')
|
||||
people = {};
|
||||
if (rate_prev) {
|
||||
let dt = ts - rate_prev.ts;
|
||||
if (dt > 0 && dt < 600) {
|
||||
for (let s, v in now) {
|
||||
let p = rate_prev.v[s] ?? v;
|
||||
push(hist[s] ??= [], [ ts, int(max(0, v[0] - p[0]) / dt), int(max(0, v[1] - p[1]) / dt) ]);
|
||||
while (length(hist[s]) > 30)
|
||||
shift(hist[s]);
|
||||
}
|
||||
for (let pid in keys(m.people)) {
|
||||
let t = usage.people?.[pid]?.total, p = rate_prev.p?.[pid];
|
||||
if (!t || !p)
|
||||
continue;
|
||||
if (type(people[pid]?.[0]) != 'array')
|
||||
people[pid] = [];
|
||||
push(people[pid], [ ts, int(max(0, t[0] - p[0]) / dt), int(max(0, t[1] - p[1]) / dt) ]);
|
||||
while (length(people[pid]) > 15)
|
||||
shift(people[pid]);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let s in keys(hist))
|
||||
if (!m.servers[s])
|
||||
delete hist[s];
|
||||
for (let pid in keys(people))
|
||||
if (!m.people[pid])
|
||||
delete people[pid];
|
||||
let totals = {};
|
||||
for (let pid in keys(m.people))
|
||||
if (usage.people?.[pid]?.total)
|
||||
totals[pid] = [ ...usage.people[pid].total ];
|
||||
rate_prev = { ts, v: now, p: totals };
|
||||
write_json(`${RUN_DIR}/rate.json`, hist, 0o644);
|
||||
write_json(`${RUN_DIR}/rate_people.json`, people, 0o644);
|
||||
}
|
||||
let last_sync = 0;
|
||||
let cert_mtime = null;
|
||||
|
||||
const REASON = {
|
||||
paused: 'paused by admin', paused_all: 'everyone paused', expired: 'end date reached',
|
||||
quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', active: 'active',
|
||||
};
|
||||
|
||||
function check_people(m, states, events) {
|
||||
let ts = time();
|
||||
for (let id, p in m.people) {
|
||||
let st = states[id], prev = last_states?.[id];
|
||||
if (prev != null && prev != st)
|
||||
push(events, { type: st == 'active' ? 'resumed' : 'paused', person: id, detail: REASON[st] ?? st });
|
||||
// "Remove their devices" when the end date passes.
|
||||
if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices)) {
|
||||
let c = core.open_cursor();
|
||||
let mm = core.load(c);
|
||||
for (let d in mm.people[id]?.devices ?? [])
|
||||
core.delete_device(c, mm, d);
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
push(events, { type: 'devices_removed', person: id, detail: 'end date reached' });
|
||||
last_sync = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let last_home = 0;
|
||||
|
||||
/** Locate new client addresses for the admin map (a couple per minute). */
|
||||
function check_geo(m) {
|
||||
if (!m.settings.geo_enabled)
|
||||
return;
|
||||
let cache = geo.load();
|
||||
let ips = [];
|
||||
for (let id, rec in usage.devices)
|
||||
for (let ip in keys(rec.ips ?? {}))
|
||||
push(ips, ip);
|
||||
let changed = geo.resolve(m.settings, cache, ips, 2);
|
||||
if (time() - last_home > 3600) {
|
||||
last_home = time();
|
||||
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
|
||||
changed = geo.resolve_home(m.settings, cache, wan) || changed;
|
||||
}
|
||||
if (changed)
|
||||
geo.save(cache);
|
||||
}
|
||||
|
||||
function place_of(ip) {
|
||||
let pl = geo.place(geo.load(), ip);
|
||||
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
|
||||
}
|
||||
|
||||
function check_devices(m, lv, events) {
|
||||
for (let id, d in lv) {
|
||||
let dev = m.devices[id];
|
||||
let was = last_online[id];
|
||||
// A device we have never seen before that is online now counts as a connect.
|
||||
if (was == null && d.online && d.present)
|
||||
was = false;
|
||||
// Debounce: a device has to look offline on two ticks in a row before
|
||||
// a disconnect is logged (handshakes are renewed only every 2-3 min).
|
||||
if (was && !d.online) {
|
||||
offline_ticks[id] = (offline_ticks[id] ?? 0) + 1;
|
||||
if (offline_ticks[id] < 2)
|
||||
continue;
|
||||
}
|
||||
else
|
||||
delete offline_ticks[id];
|
||||
if (was != null && was != d.online) {
|
||||
if (d.online)
|
||||
push(events, { type: 'connect', person: dev.person, device: id, detail: d.endpoint, where: place_of(d.endpoint) });
|
||||
else
|
||||
push(events, { type: 'disconnect', person: dev.person, device: id });
|
||||
}
|
||||
else if (d.online && last_endpoint[id] && d.endpoint && last_endpoint[id] != d.endpoint)
|
||||
push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${d.endpoint}` });
|
||||
last_online[id] = d.online;
|
||||
if (d.endpoint)
|
||||
last_endpoint[id] = d.endpoint;
|
||||
}
|
||||
for (let id in keys(last_online))
|
||||
if (!m.devices[id]) {
|
||||
delete last_online[id];
|
||||
delete last_endpoint[id];
|
||||
}
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/presence.json`, { online: last_online, endpoint: last_endpoint }, 0o600);
|
||||
}
|
||||
|
||||
function check_servers(m, dmp, events) {
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.enabled || !srv.private_key)
|
||||
continue;
|
||||
let up = dmp.ifaces[srv.ifname] != null;
|
||||
if (!up) {
|
||||
iface_down[id] = (iface_down[id] ?? 0) + 1;
|
||||
if (iface_down[id] == 2) {
|
||||
push(events, { type: 'server_down', server: id, detail: srv.ifname });
|
||||
}
|
||||
}
|
||||
else {
|
||||
if ((iface_down[id] ?? 0) >= 2) {
|
||||
push(events, { type: 'server_up', server: id, detail: srv.ifname });
|
||||
}
|
||||
iface_down[id] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function check_cert(m) {
|
||||
if (!m.settings.portal_enabled)
|
||||
return;
|
||||
let c = ops.portal_cert(m.settings);
|
||||
let mt = stat(c.cert)?.mtime;
|
||||
if (cert_mtime != null && mt != null && mt != cert_mtime)
|
||||
system('/etc/init.d/dawnline reload >/dev/null 2>&1 &');
|
||||
cert_mtime = mt;
|
||||
}
|
||||
|
||||
let last_backup_day = null;
|
||||
|
||||
function nightly_backup() {
|
||||
let t = localtime();
|
||||
if (t.hour != 3 || last_backup_day == t.mday)
|
||||
return;
|
||||
last_backup_day = t.mday;
|
||||
let sum = sh_out('md5sum /etc/config/dawnline | cut -d" " -f1');
|
||||
let st = read_json(`${DATA_DIR}/backup-state.json`, {});
|
||||
if (sum && sum != st.auto) {
|
||||
try {
|
||||
ops.backup_create('auto');
|
||||
write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600);
|
||||
}
|
||||
catch (e) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Traffic history resets requested from LuCI (rpcd cannot touch the
|
||||
* counters this process holds in memory). Applied, then saved to flash.
|
||||
*/
|
||||
function check_usage_reset(m) {
|
||||
let path = `${RUN_DIR}/usage.reset`;
|
||||
let req = read_json(path, null);
|
||||
if (req == null)
|
||||
return false;
|
||||
unlink(path);
|
||||
for (let r in (type(req) == 'array' ? req : [ req ])) {
|
||||
live.reset_usage(usage, m, r.scope, r.id);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function tick() {
|
||||
// A restore or import drops the live counters; start over from flash.
|
||||
if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
|
||||
usage = live.load_usage();
|
||||
let m = core.load();
|
||||
let reset = check_usage_reset(m);
|
||||
let pol = live.policy(m.settings.retention);
|
||||
let dmp = live.dump();
|
||||
let lv = live.collect(m, usage, dmp);
|
||||
try {
|
||||
record_rate(m);
|
||||
}
|
||||
catch (e) {}
|
||||
let states = apply.states_for(m, usage);
|
||||
let events = [];
|
||||
|
||||
check_devices(m, lv, events);
|
||||
check_people(m, states, events);
|
||||
check_servers(m, dmp, events);
|
||||
|
||||
let changed = last_states == null || sprintf('%J', states) != sprintf('%J', last_states);
|
||||
if (changed || time() - last_sync > RESYNC_EVERY) {
|
||||
apply.sync(m, usage);
|
||||
last_sync = time();
|
||||
}
|
||||
last_states = states;
|
||||
|
||||
live.add_events(events, pol);
|
||||
|
||||
let persist = reset || time() - last_flush >= FLUSH_EVERY;
|
||||
live.save_usage(usage, persist);
|
||||
if (persist)
|
||||
last_flush = time();
|
||||
if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) {
|
||||
live.persist_events(pol);
|
||||
last_log_flush = time();
|
||||
}
|
||||
try {
|
||||
apply.sync_loop(m, usage);
|
||||
// The router's network changed under us: re-derive everything.
|
||||
let sig = apply.net_signature(m);
|
||||
if (last_net != null && sig != last_net) {
|
||||
system(`logger -t dawnline-agent 'network changed, re-applying'`);
|
||||
apply.apply();
|
||||
sig = apply.net_signature(core.load());
|
||||
}
|
||||
last_net = sig;
|
||||
}
|
||||
catch (e) {
|
||||
system(`logger -t dawnline-agent ${q('like-home: ' + e.message)}`);
|
||||
}
|
||||
check_cert(m);
|
||||
nightly_backup();
|
||||
try {
|
||||
check_geo(m);
|
||||
}
|
||||
catch (e) {
|
||||
system(`logger -t dawnline-agent ${q('geo: ' + e.message)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function shutdown() {
|
||||
live.save_usage(usage, true);
|
||||
live.persist_events();
|
||||
}
|
||||
|
||||
uloop.init();
|
||||
|
||||
let timer;
|
||||
timer = uloop.timer(1000, function() {
|
||||
try {
|
||||
tick();
|
||||
}
|
||||
catch (e) {
|
||||
system(`logger -t dawnline-agent ${q('tick failed: ' + e.message)}`);
|
||||
}
|
||||
timer.set(TICK);
|
||||
});
|
||||
|
||||
if (type(uloop.signal) == 'function') {
|
||||
uloop.signal('TERM', () => { shutdown(); uloop.end(); });
|
||||
uloop.signal('INT', () => { shutdown(); uloop.end(); });
|
||||
}
|
||||
|
||||
uloop.run();
|
||||
shutdown();
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
# Dawnline: run the Home-only resolver where its config says (inside the
|
||||
# dawnline netns while it exists, otherwise on the router itself).
|
||||
CONF=/var/etc/dawnline-dns.conf
|
||||
[ -f "$CONF" ] || exit 1
|
||||
if head -n1 "$CONF" | grep -q '^# mode=ns' && [ -e /var/run/netns/dawnline ]; then
|
||||
exec ip netns exec dawnline /usr/sbin/dnsmasq -k -C "$CONF"
|
||||
fi
|
||||
exec /usr/sbin/dnsmasq -k -C "$CONF"
|
||||
+521
@@ -0,0 +1,521 @@
|
||||
#!/usr/bin/ucode
|
||||
// Dawnline background update worker, started detached by luci.dawnline.
|
||||
//
|
||||
// updater check
|
||||
// updater install app|amneziawg[:slava|grey[:ru]]|pkgs:<name,…>|all
|
||||
//
|
||||
// Progress: /var/run/dawnline/update-job.json; check results:
|
||||
// /var/run/dawnline/update-check.json. The Updates tab polls both.
|
||||
'use strict';
|
||||
|
||||
import * as fs from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { connect } from 'ubus';
|
||||
import { VERSION, REPO } from 'dawnline.util';
|
||||
|
||||
const STATE_DIR = '/var/run/dawnline';
|
||||
const JOB_FILE = `${STATE_DIR}/update-job.json`;
|
||||
const CHECK_FILE = `${STATE_DIR}/update-check.json`;
|
||||
const WORK_DIR = '/tmp/dawnline-update';
|
||||
// Builds per OpenWrt release (tag = firmware version); the kernel module must match the firmware.
|
||||
// Which AmneziaWG a build carries (2.0 or 3.1) is read from the package, per firmware.
|
||||
const AWG_SOURCES = {
|
||||
slava: { repo: 'Slava-Shchipunov/awg-openwrt', label: 'Slava-Shchipunov' },
|
||||
grey: { repo: '2Grey/awg-openwrt', label: '2Grey' },
|
||||
};
|
||||
const AWG_PKGS = [ 'kmod-amneziawg', 'amneziawg-tools', 'luci-proto-amneziawg' ];
|
||||
const AWG_RU = 'luci-i18n-amneziawg-ru';
|
||||
// OpenWrt packages Dawnline runs on (the Updates tab groups and names them).
|
||||
// What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the
|
||||
// stock system): the home-like link, and HTTPS plus certificates for the personal portal.
|
||||
const SYS_PKGS = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ];
|
||||
// Packages released together with each of the above, updated as a set so OpenSSL never ends up
|
||||
// half old and half new.
|
||||
const PKG_FAMILY = [
|
||||
[ /^ip-full$/, /^ip-/ ],
|
||||
[ /^(libustream-openssl|openssl-util)$/, /^(libustream-openssl|libopenssl|openssl-util$)/ ],
|
||||
[ /^(acme|luci-app-acme$)/, /^acme/ ],
|
||||
];
|
||||
|
||||
function family(p) {
|
||||
for (let f in PKG_FAMILY)
|
||||
if (match(p, f[0]))
|
||||
return f[1];
|
||||
return null;
|
||||
}
|
||||
|
||||
let job = {
|
||||
action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null,
|
||||
phase: '', log: [], error: null, result: null,
|
||||
};
|
||||
|
||||
function save() {
|
||||
fs.writefile(`${JOB_FILE}.tmp`, sprintf('%J', job));
|
||||
fs.rename(`${JOB_FILE}.tmp`, JOB_FILE);
|
||||
}
|
||||
|
||||
function log(msg) {
|
||||
let t = localtime();
|
||||
push(job.log, sprintf('%02d:%02d:%02d %s', t.hour, t.min, t.sec, msg));
|
||||
if (length(job.log) > 300)
|
||||
splice(job.log, 0, length(job.log) - 300);
|
||||
save();
|
||||
}
|
||||
|
||||
function phase(p) {
|
||||
job.phase = p;
|
||||
log(p);
|
||||
}
|
||||
|
||||
function q(s) {
|
||||
return "'" + replace(`${s ?? ''}`, "'", "'\\''") + "'";
|
||||
}
|
||||
|
||||
function run(cmd) {
|
||||
let p = fs.popen(cmd + ' 2>&1', 'r');
|
||||
if (!p)
|
||||
return { code: 127, out: '' };
|
||||
let out = p.read('all') ?? '';
|
||||
return { code: p.close(), out };
|
||||
}
|
||||
|
||||
function run_logged(cmd) {
|
||||
let r = run(cmd);
|
||||
for (let line in split(trim(r.out), '\n'))
|
||||
if (length(trim(line)))
|
||||
log(` ${line}`);
|
||||
return r;
|
||||
}
|
||||
|
||||
function repo() {
|
||||
return REPO;
|
||||
}
|
||||
|
||||
function have_curl() {
|
||||
return fs.access('/usr/bin/curl', 'x');
|
||||
}
|
||||
|
||||
function download(url, dest) {
|
||||
let r = have_curl()
|
||||
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 2 -o ${q(dest)} ${q(url)}`)
|
||||
: run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(url)}`);
|
||||
return r.code == 0 && (fs.stat(dest)?.size ?? 0) > 0;
|
||||
}
|
||||
|
||||
/** Latest release tag; the /releases/latest redirect avoids API rate limits. */
|
||||
function latest_tag(rp) {
|
||||
if (have_curl()) {
|
||||
let r = run(`curl -sI --connect-timeout 15 --max-time 30 -o /dev/null -w '%{redirect_url}' ${q('https://github.com/' + rp + '/releases/latest')}`);
|
||||
let m = match(trim(r.out), /\/releases\/tag\/([^\/?#]+)$/);
|
||||
if (m)
|
||||
return m[1];
|
||||
}
|
||||
let r = run(`uclient-fetch -q -T 20 -O - ${q('https://api.github.com/repos/' + rp + '/releases/latest')}`);
|
||||
try {
|
||||
return json(r.out)?.tag_name;
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function version_cmp(a, b) {
|
||||
let pa = split(replace(`${a}`, /^v/, ''), /[.~+-]/), pb = split(replace(`${b}`, /^v/, ''), /[.~+-]/);
|
||||
for (let i = 0; i < length(pa) || i < length(pb); i++) {
|
||||
let x = pa[i] ?? '0', y = pb[i] ?? '0';
|
||||
if (match(x, /^[0-9]+$/) && match(y, /^[0-9]+$/)) {
|
||||
if (int(x) != int(y))
|
||||
return int(x) < int(y) ? -1 : 1;
|
||||
}
|
||||
else if (x != y)
|
||||
return x < y ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function is_apk() {
|
||||
return fs.access('/usr/bin/apk', 'x');
|
||||
}
|
||||
|
||||
function pkg_version(name) {
|
||||
let esc = replace(name, /[.+]/g, '\\$&');
|
||||
if (is_apk()) {
|
||||
let m = match(run(`apk list --installed ${q(name)}`).out, regexp(`^${esc}-([^ ]+) `));
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
// Libraries carry their ABI in the name (libustream-openssl20201210).
|
||||
let re = regexp(`^${esc}([0-9]+)? - (.+)$`), found = null;
|
||||
for (let line in split(run('opkg list-installed').out, '\n')) {
|
||||
let m = match(trim(line), re);
|
||||
if (m && (found == null || m[1] == null))
|
||||
found = m;
|
||||
}
|
||||
return found ? trim(found[2]) : null;
|
||||
}
|
||||
|
||||
function pkg_file_version(path) {
|
||||
if (match(path, /\.ipk$/)) {
|
||||
let o = run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out;
|
||||
return match(o, /(^|\n)Version: *([^\n]+)/)?.[2];
|
||||
}
|
||||
return match(run(`apk adbdump ${q(path)}`).out, /\n *version: *([^\n]+)/)?.[1];
|
||||
}
|
||||
|
||||
function workdir() {
|
||||
run(`rm -rf ${WORK_DIR}`);
|
||||
fs.mkdir(WORK_DIR, 0o700);
|
||||
}
|
||||
|
||||
/* ---------- Dawnline itself ---------- */
|
||||
|
||||
function check_app() {
|
||||
let rp = repo();
|
||||
let tag = latest_tag(rp);
|
||||
if (!tag)
|
||||
return { installed: VERSION, latest: null, update: false, note: `No published release in ${rp}` };
|
||||
let latest = replace(tag, /^v/, '');
|
||||
return { installed: VERSION, latest, tag, repo: rp, update: version_cmp(VERSION, latest) < 0 };
|
||||
}
|
||||
|
||||
function install_app() {
|
||||
let c = check_app();
|
||||
if (!c.latest)
|
||||
die(c.note);
|
||||
if (!c.update) {
|
||||
log('Dawnline is up to date');
|
||||
return { installed: VERSION };
|
||||
}
|
||||
// Releases carry luci-app-dawnline-<version>.ipk and .apk plus sha256sums.txt.
|
||||
let asset = `luci-app-dawnline-${c.latest}.${is_apk() ? 'apk' : 'ipk'}`;
|
||||
let base = `https://github.com/${c.repo}/releases/download/${c.tag}`;
|
||||
workdir();
|
||||
phase(`Downloading ${asset}`);
|
||||
let f = `${WORK_DIR}/${asset}`, sums = `${WORK_DIR}/sha256sums.txt`;
|
||||
if (!download(`${base}/${asset}`, f))
|
||||
die(`Download failed: ${asset}`);
|
||||
phase('Verifying package');
|
||||
if (!download(`${base}/sha256sums.txt`, sums))
|
||||
die('The release has no sha256sums.txt');
|
||||
let want = null;
|
||||
for (let line in split(fs.readfile(sums) ?? '', '\n')) {
|
||||
let m = match(trim(line), /^([0-9a-f]{64})[ \t]+\*?(\S+)$/);
|
||||
if (m && m[2] == asset)
|
||||
want = m[1];
|
||||
}
|
||||
let got = match(run(`sha256sum ${q(f)}`).out, /^([0-9a-f]{64})/)?.[1];
|
||||
if (!want || got != want)
|
||||
die(`Checksum mismatch for ${asset}`);
|
||||
phase('Backing up configuration');
|
||||
run('/usr/bin/dawnline backup --reason pre-update');
|
||||
phase('Installing package');
|
||||
if (run_logged(is_apk() ? `apk add --allow-untrusted ${q(f)}` : `opkg install ${q(f)}`).code != 0)
|
||||
die('Installation failed');
|
||||
run('rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null');
|
||||
// Restart after this job has saved its final state.
|
||||
run('( sleep 3; /etc/init.d/rpcd reload; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
|
||||
return { installed: c.latest };
|
||||
}
|
||||
|
||||
/* ---------- AmneziaWG ---------- */
|
||||
|
||||
function awg_release() {
|
||||
let u = connect();
|
||||
let b = u?.call('system', 'board') ?? {};
|
||||
u?.disconnect();
|
||||
let rel = b.release ?? {};
|
||||
let target = split(rel.target ?? '', '/');
|
||||
let arch = rel.arch ?? trim(run("sed -n \"s/^DISTRIB_ARCH='\\(.*\\)'/\\1/p\" /etc/openwrt_release").out);
|
||||
if (!rel.version || length(target) != 2 || !arch)
|
||||
return null;
|
||||
return {
|
||||
tag: `v${rel.version}`,
|
||||
postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`,
|
||||
ext: is_apk() ? 'apk' : 'ipk',
|
||||
};
|
||||
}
|
||||
|
||||
function awg_download(r, name, rp) {
|
||||
let file = `${name}${r.postfix}.${r.ext}`;
|
||||
let dest = `${WORK_DIR}/${replace(rp, '/', '_')}_${file}`;
|
||||
return download(`https://github.com/${rp}/releases/download/${r.tag}/${file}`, dest) ? dest : null;
|
||||
}
|
||||
|
||||
/** When the build for this firmware was published (best effort). */
|
||||
function release_date(rp, tag) {
|
||||
let r = run(`uclient-fetch -q -T 20 -O - ${q(`https://api.github.com/repos/${rp}/releases/tags/${tag}`)}`);
|
||||
try {
|
||||
return json(r.out)?.published_at ?? null;
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** AmneziaWG generation of a tools version: 3.x packages carry 3.1, older ones (1.0.x) 2.0. */
|
||||
function awg_gen(version) {
|
||||
return version == null ? null : match(version, /^3\./) ? '3.1' : '2.0';
|
||||
}
|
||||
|
||||
/** The newest tag of the same OpenWrt series (24.10.x) in a repository, if newer than ours. */
|
||||
function newer_series_tag(rp, tag) {
|
||||
let r = run(`uclient-fetch -q -T 20 -O - ${q(`https://api.github.com/repos/${rp}/releases?per_page=30`)}`);
|
||||
let series = match(tag, /^v([0-9]+\.[0-9]+)\./)?.[1];
|
||||
let best = null;
|
||||
try {
|
||||
for (let x in json(r.out) ?? []) {
|
||||
let t = x.tag_name;
|
||||
if (series && match(t, regexp(`^v${replace(series, '.', '\\.')}\\.`)) && version_cmp(t, tag) > 0 && (!best || version_cmp(t, best) > 0))
|
||||
best = t;
|
||||
}
|
||||
}
|
||||
catch (e) {}
|
||||
return best;
|
||||
}
|
||||
|
||||
function awg_installed() {
|
||||
let r = {};
|
||||
for (let p in AWG_PKGS)
|
||||
r[p] = pkg_version(p);
|
||||
return r;
|
||||
}
|
||||
|
||||
function check_awg() {
|
||||
let installed = awg_installed();
|
||||
let ru = pkg_version(AWG_RU) != null;
|
||||
let cur = installed['amneziawg-tools'];
|
||||
let r = awg_release();
|
||||
if (!r)
|
||||
return { installed: cur, gen: awg_gen(cur), packages: installed, current: null, ru, sources: {}, update: false, note: 'Cannot detect the firmware target' };
|
||||
workdir();
|
||||
let sources = {};
|
||||
for (let id, src in AWG_SOURCES) {
|
||||
let f = awg_download(r, 'amneziawg-tools', src.repo);
|
||||
let v = f ? pkg_file_version(f) : null;
|
||||
let s2 = { label: src.label, repo: src.repo, tag: r.tag, version: v, gen: awg_gen(v), date: f ? release_date(src.repo, r.tag) : null };
|
||||
// A newer firmware may already get 3.1 from this source.
|
||||
if (s2.gen != '3.1') {
|
||||
let nt = newer_series_tag(src.repo, r.tag);
|
||||
if (nt) {
|
||||
let nf = awg_download({ ...r, tag: nt, postfix: replace(r.postfix, r.tag, nt) }, 'amneziawg-tools', src.repo);
|
||||
let nv = nf ? pkg_file_version(nf) : null;
|
||||
if (awg_gen(nv) == '3.1')
|
||||
s2.newer = { tag: nt, gen: '3.1' };
|
||||
}
|
||||
}
|
||||
sources[id] = s2;
|
||||
}
|
||||
// The installed build: the source whose package matches, else the main one.
|
||||
let current = null;
|
||||
for (let id, x in sources)
|
||||
if (!current && cur && x.version == cur)
|
||||
current = id;
|
||||
current ??= cur ? 'slava' : null;
|
||||
let mine = current ? sources[current] : null;
|
||||
return { installed: cur, gen: awg_gen(cur), packages: installed, current, ru, release: r.tag, sources,
|
||||
latest: mine?.version ?? null,
|
||||
update: cur == null || (mine?.version != null && version_cmp(cur, mine.version) < 0),
|
||||
note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(r.tag, 1)} yet` : null };
|
||||
}
|
||||
|
||||
function install_awg(arg) {
|
||||
let parts = split(arg ?? '', ':');
|
||||
let id = parts[0] || 'slava';
|
||||
let src = AWG_SOURCES[id];
|
||||
if (!src)
|
||||
die(`Unknown AmneziaWG build ${id}`);
|
||||
let want_ru = parts[1] == 'ru';
|
||||
let r = awg_release();
|
||||
if (!r)
|
||||
die('Cannot detect the firmware target');
|
||||
let before = awg_installed();
|
||||
workdir();
|
||||
let files = [];
|
||||
for (let p in [ ...AWG_PKGS, ...(want_ru ? [ AWG_RU ] : []) ]) {
|
||||
phase(`Downloading ${p} from ${src.repo}`);
|
||||
let f = awg_download(r, p, src.repo);
|
||||
if (!f)
|
||||
die(`No ${p} build for OpenWrt ${substr(r.tag, 1)} in ${src.repo}`);
|
||||
push(files, f);
|
||||
}
|
||||
phase('Refreshing package lists');
|
||||
run_logged(is_apk() ? 'apk update' : 'opkg update');
|
||||
phase(`Installing the ${src.label} build`);
|
||||
let cmd = is_apk()
|
||||
? `apk add --allow-untrusted ${join(' ', map(files, q))}`
|
||||
: `opkg install --force-reinstall --force-downgrade ${join(' ', map(files, q))}`;
|
||||
if (run_logged(cmd).code != 0)
|
||||
die('Package installation failed');
|
||||
if (!want_ru && pkg_version(AWG_RU))
|
||||
run_logged(is_apk() ? `apk del ${AWG_RU}` : `opkg remove ${AWG_RU}`);
|
||||
let after = awg_installed();
|
||||
if (before['kmod-amneziawg'] && before['kmod-amneziawg'] != after['kmod-amneziawg']) {
|
||||
// New kernel module: every AmneziaWG interface must be re-created.
|
||||
let ifaces = [];
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
c.foreach('network', 'interface', (s) => {
|
||||
if (s.proto == 'amneziawg' && s.disabled != '1')
|
||||
push(ifaces, s['.name']);
|
||||
});
|
||||
phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`);
|
||||
for (let i in ifaces)
|
||||
run(`ifdown ${q(i)}`);
|
||||
run('rmmod amneziawg');
|
||||
run_logged('modprobe amneziawg');
|
||||
for (let i in ifaces)
|
||||
run(`ifup ${q(i)}`);
|
||||
}
|
||||
run('rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null');
|
||||
return { build: id, before, after };
|
||||
}
|
||||
|
||||
/* ---------- OpenWrt packages Dawnline uses ---------- */
|
||||
|
||||
// Installed packages with a newer version in the feeds: { name: latest }.
|
||||
function upgradable(refresh) {
|
||||
if (refresh) {
|
||||
phase('Refreshing package lists');
|
||||
run(is_apk() ? 'apk update' : 'opkg update');
|
||||
}
|
||||
let up = {};
|
||||
if (is_apk()) {
|
||||
for (let line in split(run('apk version -l "<"').out, '\n')) {
|
||||
let m = match(line, /^(\S+?)-([0-9][^ ]*)\s+<\s+(\S+)/);
|
||||
if (m)
|
||||
up[m[1]] = m[3];
|
||||
}
|
||||
}
|
||||
else
|
||||
for (let line in split(run('opkg list-upgradable').out, '\n')) {
|
||||
let m = match(line, /^(\S+) - (\S+) - (\S+)/);
|
||||
if (m)
|
||||
up[m[1]] = m[3];
|
||||
}
|
||||
return up;
|
||||
}
|
||||
|
||||
// The packages to update for these names: each one plus its upgradable family.
|
||||
function with_family(names, up) {
|
||||
let set = {};
|
||||
for (let n in names) {
|
||||
if (up[n])
|
||||
set[n] = true;
|
||||
let f = family(n);
|
||||
if (f)
|
||||
for (let u in keys(up))
|
||||
if (match(u, f))
|
||||
set[u] = true;
|
||||
}
|
||||
return sort(keys(set));
|
||||
}
|
||||
|
||||
function check_pkgs(refresh) {
|
||||
let up = upgradable(refresh ?? true);
|
||||
let res = {}, all = {};
|
||||
for (let p in SYS_PKGS) {
|
||||
let v = pkg_version(p);
|
||||
let set = v ? with_family([ p ], up) : [];
|
||||
res[p] = { installed: v, latest: v && up[p] ? up[p] : null, with: filter(set, (x) => x != p) };
|
||||
for (let x in set)
|
||||
all[x] = true;
|
||||
}
|
||||
return { pkgs: res, updates: length(keys(all)) };
|
||||
}
|
||||
|
||||
// Before install_pkgs: ucode resolves a name at the point it is used.
|
||||
function save_check(res, at) {
|
||||
fs.writefile(CHECK_FILE, sprintf('%J', { time: at ?? time(), components: res }));
|
||||
}
|
||||
|
||||
function install_pkgs(arg) {
|
||||
let names = filter(split(arg ?? '', ','), (x) => x != '');
|
||||
for (let n in names)
|
||||
if (index(SYS_PKGS, n) < 0)
|
||||
die(`${n} is not a package Dawnline manages`);
|
||||
if (!length(names))
|
||||
die('Nothing to install');
|
||||
phase('Refreshing package lists');
|
||||
run_logged(is_apk() ? 'apk update' : 'opkg update');
|
||||
let missing = filter(names, (n) => pkg_version(n) == null);
|
||||
let have = with_family(filter(names, (n) => pkg_version(n) != null), upgradable(false));
|
||||
if (length(have)) {
|
||||
phase(`Updating ${join(', ', have)}`);
|
||||
if (run_logged(is_apk() ? `apk upgrade ${join(' ', map(have, q))}` : `opkg upgrade ${join(' ', map(have, q))}`).code != 0)
|
||||
die('Update failed');
|
||||
}
|
||||
if (length(missing)) {
|
||||
phase(`Installing ${join(', ', missing)}`);
|
||||
if (run_logged(is_apk() ? `apk add ${join(' ', map(missing, q))}` : `opkg install ${join(' ', map(missing, q))}`).code != 0)
|
||||
die('Installation failed');
|
||||
}
|
||||
// Show the new state right away instead of the check from before the update.
|
||||
try {
|
||||
let c = json(fs.readfile(CHECK_FILE) ?? '{}') ?? {};
|
||||
c.components ??= {};
|
||||
c.components.packages = check_pkgs(false);
|
||||
save_check(c.components, c.time);
|
||||
}
|
||||
catch (e) {
|
||||
log(`Could not refresh the package check: ${e.message}`);
|
||||
}
|
||||
// The portal's HTTPS runs in uhttpd. Restart after this job saved its state.
|
||||
let touched = [ ...names, ...have ];
|
||||
// A missing piece arrived: set up what waited for it (the portal, the home-like link).
|
||||
if (length(missing) && length(filter(missing, (n) => match(n, /^(openssl-util|libustream|ip-full|kmod-veth)/))))
|
||||
run('( sleep 3; /usr/bin/dawnline apply; /etc/init.d/uhttpd restart; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
|
||||
else if (length(filter(touched, (n) => match(n, /^(libustream|libopenssl)/))))
|
||||
run('( sleep 3; /etc/init.d/uhttpd restart; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
|
||||
return { updated: have, installed: missing };
|
||||
}
|
||||
|
||||
/* ---------- main ---------- */
|
||||
|
||||
const CHECKS = { app: check_app, amneziawg: check_awg, packages: check_pkgs };
|
||||
const INSTALLS = { app: install_app, amneziawg: install_awg, pkgs: install_pkgs };
|
||||
|
||||
|
||||
if (!fs.access(STATE_DIR))
|
||||
fs.mkdir(STATE_DIR, 0o755);
|
||||
save();
|
||||
|
||||
try {
|
||||
if (job.action == 'check') {
|
||||
let res = {};
|
||||
for (let name, fn in CHECKS) {
|
||||
phase(`Checking ${name}`);
|
||||
try {
|
||||
res[name] = fn();
|
||||
}
|
||||
catch (e) {
|
||||
res[name] = { error: e.message };
|
||||
}
|
||||
}
|
||||
save_check(res);
|
||||
job.result = res;
|
||||
}
|
||||
else if (job.action == 'install') {
|
||||
let what = job.component == 'all' ? [ 'amneziawg', 'app' ] : [ job.component ];
|
||||
job.result = {};
|
||||
for (let w in what) {
|
||||
let i = index(w, ':');
|
||||
let name = i < 0 ? w : substr(w, 0, i), arg = i < 0 ? null : substr(w, i + 1);
|
||||
if (!INSTALLS[name])
|
||||
die(`Unknown component ${name}`);
|
||||
phase(`Updating ${name}`);
|
||||
job.result[name] = INSTALLS[name](arg);
|
||||
}
|
||||
}
|
||||
else
|
||||
die('Usage: updater check | install app|amneziawg[:build[:ru]]|pkgs:<names>|all');
|
||||
job.state = 'done';
|
||||
phase('Finished');
|
||||
}
|
||||
catch (e) {
|
||||
job.state = 'failed';
|
||||
job.error = e.message;
|
||||
log(`Error: ${e.message}`);
|
||||
}
|
||||
|
||||
run(`rm -rf ${WORK_DIR}`);
|
||||
job.finished = time();
|
||||
save();
|
||||
@@ -0,0 +1,3 @@
|
||||
Geist and Geist Mono are licensed under the SIL Open Font License, Version 1.1.
|
||||
Copyright (c) 2023 Vercel, in collaboration with basement.studio.
|
||||
https://github.com/vercel/geist-font/blob/main/OFL.txt
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><style>.t{fill:#0a0a0a}.g{fill:#fff}@media (prefers-color-scheme:dark){.t{fill:#fff}.g{fill:#0a0a0a}}</style><rect class="t" width="64" height="64" rx="16"/><path class="g" d="M14 38a18 18 0 0 1 36 0z"/><rect class="g" x="12" y="43" width="40" height="4" rx="2" opacity=".5"/></svg>
|
||||
|
After Width: | Height: | Size: 343 B |
@@ -0,0 +1 @@
|
||||
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.pill{display:inline-flex;align-items:center;height:22px;padding:0 9px;border-radius:999px;font-size:12px;font-weight:500;background:var(--soft);color:var(--muted)}.pill.ok{background:var(--ok-wash);color:var(--ok)}.pill.warn{background:var(--warn-wash);color:var(--warn)}.pill.bad{background:var(--bad-wash);color:var(--bad)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);mLine truncated
|
||||
@@ -0,0 +1,6 @@
|
||||
"use strict";(()=>{var tt=Object.create;var $e=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var at=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty;var st=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ot=(n,e,a,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let v of rt(e))!it.call(n,v)&&v!==a&&$e(n,v,{get:()=>e[v],enumerable:!(o=nt(e,v))||o.enumerable});return n};var lt=(n,e,a)=>(a=n!=null?tt(at(n)):{},ot(e||!n||!n.__esModule?$e(a,"default",{value:n,enumerable:!0}):a,n));var Ue=st((Oe,Ke)=>{"use strict";var Ie=(function(){var n=function(M,k){var w=236,b=17,l=M,m=a[k],i=null,r=0,y=null,f=[],g={},T=function(c,u){r=l*4+17,i=(function(s){for(var d=new Array(s),h=0;h<s;h+=1){d[h]=new Array(s);for(var x=0;x<s;x+=1)d[h][x]=null}return d})(r),E(0,0),E(r-7,0),E(0,r-7),q(),I(),Q(c,u),l>=7&&z(c),y==null&&(y=Xe(l,m,f)),W(y,u)},E=function(c,u){for(var s=-1;s<=7;s+=1)if(!(c+s<=-1||r<=c+s))for(var d=-1;d<=7;d+=1)u+d<=-1||r<=u+d||(0<=s&&s<=6&&(d==0||d==6)||0<=d&&d<=6&&(s==0||s==6)||2<=s&&s<=4&&2<=d&&d<=4?i[c+s][u+d]=!0:i[c+s][u+d]=!1)},P=function(){for(var c=0,u=0,s=0;s<8;s+=1){T(!0,s);var d=v.getLostPoint(g);(s==0||c>d)&&(c=d,u=s)}return u},I=function(){for(var c=8;c<r-8;c+=1)i[c][6]==null&&(i[c][6]=c%2==0);for(var u=8;u<r-8;u+=1)i[6][u]==null&&(i[6][u]=u%2==0)},q=function(){for(var c=v.getPatternPosition(l),u=0;u<c.length;u+=1)for(var s=0;s<c.length;s+=1){var d=c[u],h=c[s];if(i[d][h]==null)for(var x=-2;x<=2;x+=1)for(var C=-2;C<=2;C+=1)x==-2||x==2||C==-2||C==2||x==0&&C==0?i[d+x][h+C]=!0:i[d+x][h+C]=!1}},z=function(c){for(var u=v.getBCHTypeNumber(l),s=0;s<18;s+=1){var d=!c&&(u>>s&1)==1;i[Math.floor(s/3)][s%3+r-8-3]=d}for(var s=0;s<18;s+=1){var d=!c&&(u>>s&1)==1;i[s%3+r-8-3][Math.floor(s/3)]=d}},Q=function(c,u){for(var s=m<<3|u,d=v.getBCHTypeInfo(s),h=0;h<15;h+=1){var x=!c&&(d>>h&1)==1;h<6?i[h][8]=x:h<8?i[h+1][8]=x:i[r-15+h][8]=x}for(var h=0;h<15;h+=1){var x=!c&&(d>>h&1)==1;h<8?i[8][r-h-1]=x:h<9?i[8][15-h-1+1]=x:i[8][15-h-1]=x}i[r-8][8]=!c},W=function(c,u){for(var s=-1,d=r-1,h=7,x=0,C=v.getMaskFunction(u),A=r-1;A>0;A-=2)for(A==6&&(A-=1);;){for(var S=0;S<2;S+=1)if(i[d][A-S]==null){var K=!1;x<c.length&&(K=(c[x]>>>h&1)==1);var L=C(d,A-S);L&&(K=!K),i[d][A-S]=K,h-=1,h==-1&&(x+=1,h=7)}if(d+=s,d<0||r<=d){d-=s,s=-s;break}}},re=function(c,u){for(var s=0,d=0,h=0,x=new Array(u.length),C=new Array(u.length),A=0;A<u.length;A+=1){var S=u[A].dataCount,K=u[A].totalCount-S;d=Math.max(d,S),h=Math.max(h,K),x[A]=new Array(S);for(var L=0;L<x[A].length;L+=1)x[A][L]=255&c.getBuffer()[L+s];s+=S;var Y=v.getErrorCorrectPolynomial(K),j=_(x[A],Y.getLength()-1),Ee=j.mod(Y);C[A]=new Array(Y.getLength()-1);for(var L=0;L<C[A].length;L+=1){var Be=L+Ee.getLength()-C[A].length;C[A][L]=Be>=0?Ee.getAt(Be):0}}for(var De=0,L=0;L<u.length;L+=1)De+=u[L].totalCount;for(var me=new Array(De),ce=0,L=0;L<d;L+=1)for(var A=0;A<u.length;A+=1)L<x[A].length&&(me[ce]=x[A][L],ce+=1);for(var L=0;L<h;L+=1)for(var A=0;A<u.length;A+=1)L<C[A].length&&(me[ce]=C[A][L],ce+=1);return me},Xe=function(c,u,s){for(var d=$.getRSBlocks(c,u),h=B(),x=0;x<s.length;x+=1){var C=s[x];h.put(C.getMode(),4),h.put(C.getLength(),v.getLengthInBits(C.getMode(),c)),C.write(h)}for(var A=0,x=0;x<d.length;x+=1)A+=d[x].dataCount;if(h.getLengthInBits()>A*8)throw"code length overflow. ("+h.getLengthInBits()+">"+A*8+")";for(h.getLengthInBits()+4<=A*8&&h.put(0,4);h.getLengthInBits()%8!=0;)h.putBit(!1);for(;!(h.getLengthInBits()>=A*8||(h.put(w,8),h.getLengthInBits()>=A*8));)h.put(b,8);return re(h,d)};g.addData=function(c,u){u=u||"Byte";var s=null;switch(u){case"Numeric":s=D(c);break;case"Alphanumeric":s=F(c);break;case"Byte":s=J(c);break;case"Kanji":s=U(c);break;default:throw"mode:"+u}f.push(s),y=null},g.isDark=function(c,u){if(c<0||r<=c||u<0||r<=u)throw c+","+u;return i[c][u]},g.getModuleCount=function(){return r},g.make=function(){if(l<1){for(var c=1;c<40;c++){for(var u=$.getRSBlocks(c,m),s=B(),d=0;d<f.length;d++){var h=f[d];s.put(h.getMode(),4),s.put(h.getLength(),v.getLengthInBits(h.getMode(),c)),h.write(s)}for(var x=0,d=0;d<u.length;d++)x+=u[d].dataCount;if(s.getLengthInBits()<=x*8)break}l=c}T(!1,P())},g.createTableTag=function(c,u){c=c||2,u=typeof u=="undefined"?c*4:u;var s="";s+='<table style="',s+=" border-width: 0px; border-style: none;",s+=" border-collapse: collapse;",s+=" padding: 0px; margin: "+u+"px;",s+='">',s+="<tbody>";for(var d=0;d<g.getModuleCount();d+=1){s+="<tr>";for(var h=0;h<g.getModuleCount();h+=1)s+='<td style="',s+=" border-width: 0px; border-style: none;",s+=" border-collapse: collapse;",s+=" padding: 0px; margin: 0px;",s+=" width: "+c+"px;",s+=" height: "+c+"px;",s+=" background-color: ",s+=g.isDark(d,h)?"#000000":"#ffffff",s+=";",s+='"/>';s+="</tr>"}return s+="</tbody>",s+="</table>",s},g.createSvgTag=function(c,u,s,d){var h={};typeof arguments[0]=="object"&&(h=arguments[0],c=h.cellSize,u=h.margin,s=h.alt,d=h.title),c=c||2,u=typeof u=="undefined"?c*4:u,s=typeof s=="string"?{text:s}:s||{},s.text=s.text||nLine truncated
|
||||
`}return s%2&&c>0?j.substring(0,j.length-s-1)+Array(s+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(c,u){if(c=c||1,c<2)return et(u);c-=1,u=typeof u=="undefined"?c*2:u;var s=g.getModuleCount()*c+u*2,d=u,h=s-u,x,C,A,S,K=Array(c+1).join("██"),L=Array(c+1).join(" "),Y="",j="";for(x=0;x<s;x+=1){for(A=Math.floor((x-d)/c),j="",C=0;C<s;C+=1)S=1,d<=C&&C<h&&d<=x&&x<h&&g.isDark(A,Math.floor((C-d)/c))&&(S=0),j+=S?K:L;for(A=0;A<c;A+=1)Y+=j+`
|
||||
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(c,u){u=u||2;for(var s=g.getModuleCount(),d=0;d<s;d++)for(var h=0;h<s;h++)c.fillStyle=g.isDark(d,h)?"black":"white",c.fillRect(d*u,h*u,u,u)},g};n.stringToBytesFuncs={default:function(M){for(var k=[],w=0;w<M.length;w+=1){var b=M.charCodeAt(w);k.push(b&255)}return k}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(M,k){var w=(function(){for(var l=H(M),m=function(){var I=l.read();if(I==-1)throw"eof";return I},i=0,r={};;){var y=l.read();if(y==-1)break;var f=m(),g=m(),T=m(),E=String.fromCharCode(y<<8|f),P=g<<8|T;r[E]=P,i+=1}if(i!=k)throw i+" != "+k;return r})(),b=63;return function(l){for(var m=[],i=0;i<l.length;i+=1){var r=l.charCodeAt(i);if(r<128)m.push(r);else{var y=w[l.charAt(i)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(b)}}return m}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},a={L:1,M:0,Q:3,H:2},o={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},v=(function(){var M=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],k=1335,w=7973,b=21522,l={},m=function(i){for(var r=0;i!=0;)r+=1,i>>>=1;return r};return l.getBCHTypeInfo=function(i){for(var r=i<<10;m(r)-m(k)>=0;)r^=k<<m(r)-m(k);return(i<<10|r)^b},l.getBCHTypeNumber=function(i){for(var r=i<<12;m(r)-m(w)>=0;)r^=w<<m(r)-m(w);return i<<12|r},l.getPatternPosition=function(i){return M[i-1]},l.getMaskFunction=function(i){switch(i){case o.PATTERN000:return function(r,y){return(r+y)%2==0};case o.PATTERN001:return function(r,y){return r%2==0};case o.PATTERN010:return function(r,y){return y%3==0};case o.PATTERN011:return function(r,y){return(r+y)%3==0};case o.PATTERN100:return function(r,y){return(Math.floor(r/2)+Math.floor(y/3))%2==0};case o.PATTERN101:return function(r,y){return r*y%2+r*y%3==0};case o.PATTERN110:return function(r,y){return(r*y%2+r*y%3)%2==0};case o.PATTERN111:return function(r,y){return(r*y%3+(r+y)%2)%2==0};default:throw"bad maskPattern:"+i}},l.getErrorCorrectPolynomial=function(i){for(var r=_([1],0),y=0;y<i;y+=1)r=r.multiply(_([1,p.gexp(y)],0));return r},l.getLengthInBits=function(i,r){if(1<=r&&r<10)switch(i){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+i}else if(r<27)switch(i){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+i}else if(r<41)switch(i){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+i}else throw"type:"+r},l.getLostPoint=function(i){for(var r=i.getModuleCount(),y=0,f=0;f<r;f+=1)for(var g=0;g<r;g+=1){for(var T=0,E=i.isDark(f,g),P=-1;P<=1;P+=1)if(!(f+P<0||r<=f+P))for(var I=-1;I<=1;I+=1)g+I<0||r<=g+I||P==0&&I==0||E==i.isDark(f+P,g+I)&&(T+=1);T>5&&(y+=3+T-5)}for(var f=0;f<r-1;f+=1)for(var g=0;g<r-1;g+=1){var q=0;i.isDark(f,g)&&(q+=1),i.isDark(f+1,g)&&(q+=1),i.isDark(f,g+1)&&(q+=1),i.isDark(f+1,g+1)&&(q+=1),(q==0||q==4)&&(y+=3)}for(var f=0;f<r;f+=1)for(var g=0;g<r-6;g+=1)i.isDark(f,g)&&!i.isDark(f,g+1)&&i.isDark(f,g+2)&&i.isDark(f,g+3)&&i.isDark(f,g+4)&&!i.isDark(f,g+5)&&i.isDark(f,g+6)&&(y+=40);for(var g=0;g<r;g+=1)for(var f=0;f<r-6;f+=1)i.isDark(f,g)&&!i.isDark(f+1,g)&&i.isDark(f+2,g)&&i.isDark(f+3,g)&&i.isDark(f+4,g)&&!i.isDark(f+5,g)&&i.isDark(f+6,g)&&(y+=40);for(var z=0,g=0;g<r;g+=1)for(var f=0;f<r;f+=1)i.isDark(f,g)&&(z+=1);var Q=Math.abs(100*z/r/r-50)/5;return y+=Q*10,y},l})(),p=(function(){for(var M=new Array(256),k=new Array(256),w=0;w<8;w+=1)M[w]=1<<w;for(var w=8;w<256;w+=1)M[w]=M[w-4]^M[w-5]^M[w-6]^M[w-8];for(var w=0;w<255;w+=1)k[M[w]]=w;var b={};return b.glog=function(l){if(l<1)throw"glog("+l+")";return k[l]},b.gexp=function(l){for(;l<0;)l+=255;for(;l>=256;)l-=255;return M[l]},b})();function _(M,k){if(typeof M.length=="undefined")throw M.length+"/"+k;var w=(function(){for(var l=0;l<M.length&&M[l]==0;)l+=1;for(var m=new Array(M.length-l+k),i=0;i<M.length-l;i+=1)m[i]=M[i+l];return m})(),b={};return b.getAt=function(l){return w[l]},b.getLength=function(){return w.length},b.multiply=function(l){for(var m=new Array(b.getLength()+l.getLength()-1),i=0;i<b.getLength();i+=1)for(var r=0;r<l.getLength();r+=1)m[i+r]^=p.gexp(p.glog(b.getAt(i))+p.glog(l.getAt(r)));return _(m,0)},b.mod=function(l){if(b.getLen
Line truncated
|
||||
`),hostName:p,mtu:a.mtu,persistent_keep_alive:a.persistent_keep_alive,port:Number(a.port),psk_key:a.psk_key,server_pub_key:a.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(_),port:String(a.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:p};return a.dns[0]&&($.dns1=a.dns[0]),a.dns[1]&&($.dns2=a.dns[1]),$}function vt(n){let e="";for(let a=0;a<n.length;a+=32768)e+=String.fromCharCode(...n.subarray(a,a+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pt(n){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let a=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(a).arrayBuffer()),v=new Uint8Array(4+o.length);return new DataView(v.buffer).setUint32(0,n.length,!1),v.set(o,4),v}catch{return null}}async function xe(n,e,a=!0){let o=new TextEncoder().encode(JSON.stringify(ht(n,e))),v=a?await pt(o):null;return`vpn://${vt(v!=null?v:o)}`}function t(n,e={},...a){let o=document.createElement(n);for(let[p,_]of Object.entries(e))_==null||_===!1||(p.startsWith("on")&&typeof _=="function"?o.addEventListener(p.slice(2),_):p==="class"?o.className=String(_):_===!0?o.setAttribute(p,""):o.setAttribute(p,String(_)));let v=p=>{p==null||p===!1||(Array.isArray(p)?p.forEach(v):o.appendChild(typeof p=="string"?document.createTextNode(p):p))};return a.forEach(v),o}function O(n){let e=t("span",{class:"ic"});return e.innerHTML=He(n,"ic-svg"),e}var gt='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>',Ce=document.getElementById("app"),Ye,de=(Ye=Ce.dataset.base)!=null?Ye:"",mt=Ce.dataset.title||"Dawnline",ke=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),R=null,Fe=0,yt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(de)?de.slice(1):"",Ae=class extends Error{constructor(a,o){super(o);this.status=a}};async function oe(n,e){var v;let a=await fetch(`${de}/api/${n}`,{method:e===void 0?"GET":"POST",credentials:"omit",headers:e===void 0?{}:{"Content-Type":"application/json"},body:e===void 0?void 0:JSON.stringify(e),cache:"no-store"}),o=null;try{o=await a.json()}catch{}if(!a.ok)throw new Ae(a.status,(v=o==null?void 0:o.error)!=null?v:`Request failed (${a.status})`);return o}function se(n,e=!1){let a=t("div",{class:`toast${e?" bad":""}`,role:"status"},n);document.body.appendChild(a),requestAnimationFrame(()=>a.classList.add("show")),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>a.remove(),300)},2600)}async function ve(n,e="Copied"){try{await navigator.clipboard.writeText(n)}catch{let a=t("textarea",{class:"offscreen"},n);document.body.appendChild(a),a.select(),document.execCommand("copy"),a.remove()}se(e)}function je(n,e){let a=URL.createObjectURL(new Blob([e],{type:"application/octet-stream"})),o=t("a",{href:a,download:n,class:"offscreen"});document.body.appendChild(o),o.click(),setTimeout(()=>{URL.revokeObjectURL(a),o.remove()},1e3)}var Z=null;function ze(n,e){let a=o=>{Z!=null||(Z=document.body.appendChild(t("div",{class:"tip"}))),Z.replaceChildren(...e().map((v,p)=>t("div",{class:p?"muted":"tip-title"},v))),Z.style.display="",Z.style.left=`${o.clientX}px`,Z.style.top=`${o.clientY-10}px`};n.addEventListener("mouseenter",a),n.addEventListener("mousemove",a),n.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function wt(n){let e=Math.max(1,...n),a=t("div",{class:"spark"});return n.forEach((o,v)=>{let p=t("i",{class:o?"":"zero"});p.style.height=`${Math.max(8,o/e*100)}%`;let _=n.length-1-v,$=new Date(Date.now()-_*864e5);ze(p,()=>[_===0?"Today":_===1?"Yesterday":$.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ee(o)]),a.appendChild(p)}),a}var ie=null,le=null;function te(n=!1){if(!ie)return;let e=ie;if(ie=null,document.body.classList.remove("locked"),le==null||le(),le=null,n){e.remove();return}e.classList.remove("open"),setTimeout(()=>e.remove(),250)}function pe(n,e,...a){let o=!!ie;te(!0);let v=t("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":n},t("div",{class:"grab"}),t("div",{class:"sheet-head"},t("div",{class:"stack"},t("h2",{},n),e?t("span",{class:"muted s"},e):null),t("button",{class:"icon-btn","aria-label":"Close",onclick:()=>te()},O("x"))),t("div",{class:"sheet-body"},...a)),p=t("div",{class:"sheet",onclick:_=>{_.target===p&&te()}},v);return document.body.appendChild(p),document.body.classList.add("locked"),o?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open")),ie=p,v}document.addEventListener("keydown",n=>{n.key==="Escape"&&(he(),te())});var X=null;function he(){X==null||X.remove(),X=null}document.addEventListener("click",n=>{X&&!X.contains(n.target)&&he()});function bt(n,e){he();let a=t("
Line truncated
|
||||
`).flatMap((p,_)=>_?[`
|
||||
`,Ve(p,e)]:[Ve(p,e)])),v=t("button",{class:"btn small",onclick:p=>{p.preventDefault(),e=!e,v.replaceChildren(O(e?"x":"key"),t("span",{},e?"Hide key":"Show key")),o()}},O("key"),t("span",{},"Show key"));return o(),t("div",{class:"pane"},t("div",{class:"filecard"},t("span",{class:"filecard-ic"},".conf"),t("span",{class:"stack"},t("span",{class:"mono ellipsis"},n.filename),t("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),t("button",{class:"btn primary",onclick:()=>je(n.filename,n.conf)},O("download"),t("span",{},"Download"))),t("details",{class:"confbox"},t("summary",{},O("chevron"),t("span",{},"Configuration"),t("span",{class:"grow"}),v,t("button",{class:"btn small",onclick:p=>{p.preventDefault(),ve(n.conf,"Configuration copied")}},O("copy"),t("span",{},"Copy"))),a))}async function fe(n,e,a){let o=a!=null?a:await Te(n);if(!o)return;let v=await xe(o,`${o.server} · ${o.name}`),p=ke(),_={app:()=>t("div",{class:"pane"},t("a",{class:"btn primary block big",href:v},O("open"),t("span",{},"Open in AmneziaVPN")),t("ol",{class:"steps"},t("li",{},"No AmneziaVPN yet? ",t("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),t("li",{},"Tap ",t("b",{},"Open in AmneziaVPN")," and confirm the import."),t("li",{},"Turn the connection on — this page shows ",t("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=t("div",{class:"qr"});return H.innerHTML=qe(o.conf),t("div",{class:"pane center"},H,t("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>t("div",{class:"pane"},t("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),t("div",{class:"keybox"},t("span",{class:"mono"},v),t("button",{class:"btn small",onclick:()=>ve(v,"Key copied")},"Copy")),t("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Et(o)},$=p?["app","qr","key","file"]:["qr","key","file"],B={app:"Open in app",qr:"QR code",key:"Key",file:"File"},D=t("div",{class:"tab-body"}),F=t("div",{class:"tabs",role:"tablist"}),J=H=>{F.querySelectorAll("button").forEach(ne=>ne.classList.toggle("on",ne.dataset.id===H)),D.replaceChildren(_[H]())};for(let H of $)F.appendChild(t("button",{role:"tab","data-id":H,onclick:()=>J(H)},B[H]));J(e&&$.includes(e)?e:$[0]);let U=t("div",{class:"waiting"}),N=H=>{H!=null&&H.online?U.replaceChildren(t("i",{class:"dot ok"}),t("span",{class:"ok"},`${n.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(t("i",{class:"dot"}),t("span",{class:"muted"},`Last connected ${ye(H.handshake)}`)):U.replaceChildren(t("i",{class:"dot warn pulse"}),t("span",{class:"muted"},"Waiting for the first connection…"))};N(n);let G=window.setInterval(async()=>{try{let H=await oe("state");R=H,N(H.person.devices.find(ne=>ne.id===n.id))}catch{}},5e3);pe(n.handshake?`Connect ${n.name}`:`${n.name} is ready`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",F,D,U),le=()=>{clearInterval(G),R&&ge(R)}}function Bt(n){let e=t("input",{type:"text",value:n.name,maxlength:48,"aria-label":"Device name"});pe(`Rename ${n.name}`,null,t("form",{class:"stack gap",onsubmit:async a=>{a.preventDefault();try{R=(await oe(`devices/${n.id}`,{action:"rename",name:e.value})).state,te(),ge(R),se("Renamed")}catch(o){se(o.message,!0)}}},e,t("button",{class:"btn primary block",type:"submit"},"Save"))),setTimeout(()=>e.select(),50)}function Dt(n){pe(`Remove ${n.name}?`,null,t("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),t("div",{class:"row gap"},t("button",{class:"btn block",onclick:()=>te()},"Cancel"),t("button",{class:"btn danger-solid block",onclick:async()=>{try{R=(await oe(`devices/${n.id}`,{action:"delete"})).state,te(),ge(R),se("Device removed")}catch(e){se(e.message,!0)}}},"Remove")))}var V=navigator.userAgent,Qe=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function Me(){return Qe||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var $t=[[/^SM-S93/,"Galaxy S25"],[/^SM-S92/,"Galaxy S24"],[/^SM-S91/,"Galaxy S23"],[/^SM-S90/,"Galaxy S22"],[/^SM-G99/,"Galaxy S21"],[/^SM-F9/,"Galaxy Z Fold"],[/^SM-F7/,"Galaxy Z Flip"],[/^SM-A5/,"Galaxy A5x"],[/^SM-A3/,"Galaxy A3x"],[/^SM-X/,"Galaxy Tab"]],_e="",Pt=(async()=>{var e;let n=navigator.userAgentData;if(!n||!/Android/.test(V))return"";try{let a=((e=(await n.getHighEntropyValues(["model"])).model)!=null?e:"").trim();if(!a||a==="K")return"";let o=$t.find(([v])=>v.test(a));_e=o?`${o[1]} (${a})`:/^SM-/.test(a)?`Galaxy ${a}`:a}catch{}return _e})();function St(n){return/iPhone/.test(V)?"iPhone":Qe?"iPad":/Android/.test(V)?_e||(n==="tablet"?"Android tablet":"Android phone"):/CrOS/.test(V)?"Chromebook":/Mac OS X/.test(V)?"Mac":/Windows/.test(V)?"Windows PC":/Linux/.test(V)?"Linux PC":ue[n]}function Rt(){if(!R)return;let n=Me(),e=new Set(R.person.devices.map(B=>B
Line truncated
|
||||
+344
@@ -0,0 +1,344 @@
|
||||
#!/usr/bin/ucode
|
||||
// Dawnline personal portal (CGI behind a dedicated uhttpd instance).
|
||||
//
|
||||
// GET /<code> the app shell (<code> = three words, the personal link)
|
||||
// GET /<code>/assets/<file> its script, styles, fonts
|
||||
// GET /<code>/api/state
|
||||
// POST /<code>/api/devices { name, kind, public_key? }
|
||||
// GET /<code>/api/devices/<id>/config
|
||||
// POST /<code>/api/devices/<id> { action: rename|delete, name? }
|
||||
//
|
||||
// The personal link is the key: every request carries its code, there are
|
||||
// no sessions. Without a valid code every path answers the same bare 404 —
|
||||
// the root, a person's link, the API and the assets alike — so nothing tells
|
||||
// a scanner there is a portal here. Wrong codes are rate-limited per IP
|
||||
// (blocked addresses get the same 404 even with the right code).
|
||||
// Regenerating the code in LuCI locks the old link out at once. POST bodies
|
||||
// must be JSON from the same origin; Referrer-Policy keeps the code out of
|
||||
// other sites' logs.
|
||||
//
|
||||
// The portal can only manage the person's own devices within their limit.
|
||||
'use strict';
|
||||
|
||||
import { stdin, stat, unlink, readfile } from 'fs';
|
||||
import {
|
||||
read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, VERSION, RUN_DIR, DATA_DIR
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as view from 'dawnline.view';
|
||||
|
||||
const RATE = `${RUN_DIR}/portal-rate.json`;
|
||||
const ASSETS = '/usr/share/dawnline/portal/assets';
|
||||
const TYPES = { js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml', woff2: 'font/woff2' };
|
||||
const FAIL_LIMIT = 8;
|
||||
const FAIL_WINDOW = 900;
|
||||
|
||||
const SECURITY_HEADERS = {
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
'X-Frame-Options': 'DENY',
|
||||
'Cache-Control': 'no-store',
|
||||
'Strict-Transport-Security': 'max-age=31536000',
|
||||
};
|
||||
|
||||
function headers(status, extra) {
|
||||
let h = `Status: ${status}\r\n`;
|
||||
for (let k, v in { ...SECURITY_HEADERS, ...(extra ?? {}) })
|
||||
h += `${k}: ${v}\r\n`;
|
||||
print(h + '\r\n');
|
||||
}
|
||||
|
||||
function send_json(status, obj, extra) {
|
||||
headers(status, { 'Content-Type': 'application/json', ...(extra ?? {}) });
|
||||
print(sprintf('%J', obj));
|
||||
exit(0);
|
||||
}
|
||||
|
||||
function fail(status, msg) {
|
||||
send_json(status, { error: msg });
|
||||
}
|
||||
|
||||
function html_escape(s) {
|
||||
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
||||
}
|
||||
|
||||
function page(status, base, title, code) {
|
||||
// The build's time joins the version so every update busts the hour-long asset cache.
|
||||
let q = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
|
||||
headers(status, {
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
|
||||
"connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
|
||||
});
|
||||
print(`<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>${html_escape(title)}</title>
|
||||
<link rel="icon" href="${base}/assets/icon.svg${q}" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="${base}/assets/portal.css${q}">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" data-base="${html_escape(base ?? '')}" data-title="${html_escape(title)}"></div>
|
||||
<script src="${base}/assets/portal.js${q}" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
`);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/* ---------- request ---------- */
|
||||
|
||||
const method = getenv('REQUEST_METHOD') ?? 'GET';
|
||||
const uri = getenv('REQUEST_URI') ?? '/';
|
||||
// Behind a Cloudflare-proxied hostname every request comes from Cloudflare,
|
||||
// and uhttpd does not hand CF-Connecting-IP to CGI: all those visitors share
|
||||
// one bucket with a higher limit (three-word codes can't be guessed anyway).
|
||||
const peer = getenv('REMOTE_ADDR') ?? '';
|
||||
const via_cf = cloudflare_ip(peer);
|
||||
const ip = via_cf ? 'cloudflare' : peer;
|
||||
const fail_limit = via_cf ? FAIL_LIMIT * 25 : FAIL_LIMIT;
|
||||
const qpos = index(uri, '?');
|
||||
const path = qpos >= 0 ? substr(uri, 0, qpos) : uri;
|
||||
const query = qpos >= 0 ? substr(uri, qpos + 1) : '';
|
||||
const segs = filter(split(path, '/'), (s) => s != '');
|
||||
|
||||
function query_param(name) {
|
||||
for (let kv in split(query, '&')) {
|
||||
let eq = index(kv, '=');
|
||||
if (eq > 0 && substr(kv, 0, eq) == name)
|
||||
return substr(kv, eq + 1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function body() {
|
||||
let len = +(getenv('CONTENT_LENGTH') ?? 0);
|
||||
if (len <= 0)
|
||||
return {};
|
||||
if (len > 8192)
|
||||
fail('413 Payload Too Large', 'Request too large.');
|
||||
let raw = stdin.read(len);
|
||||
try {
|
||||
let j = json(raw);
|
||||
return type(j) == 'object' ? j : {};
|
||||
}
|
||||
catch (e) {
|
||||
fail('400 Bad Request', 'Invalid JSON.');
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- rate limiting ---------- */
|
||||
|
||||
function rate_state() {
|
||||
let st = read_json(RATE, {});
|
||||
let now = time();
|
||||
for (let k, v in st)
|
||||
if (now - v.first > FAIL_WINDOW)
|
||||
delete st[k];
|
||||
return st;
|
||||
}
|
||||
|
||||
function rate_blocked() {
|
||||
let v = rate_state()[ip];
|
||||
return v != null && v.count >= fail_limit;
|
||||
}
|
||||
|
||||
function rate_fail() {
|
||||
let l = lock('portal-rate');
|
||||
let st = rate_state();
|
||||
let v = st[ip] ?? { first: time(), count: 0 };
|
||||
v.count++;
|
||||
st[ip] = v;
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(RATE, st, 0o600);
|
||||
unlock(l);
|
||||
if (v.count == fail_limit)
|
||||
live.add_event({ type: 'portal_blocked', detail: ip });
|
||||
}
|
||||
|
||||
// Older versions kept sign-in sessions on flash; they mean nothing now.
|
||||
if (stat(`${DATA_DIR}/sessions.json`))
|
||||
unlink(`${DATA_DIR}/sessions.json`);
|
||||
|
||||
/* ---------- routing ---------- */
|
||||
|
||||
let m = core.load();
|
||||
const redirect = m.settings.portal_redirect;
|
||||
|
||||
/**
|
||||
* The one answer for anything without a valid code: a bare 404, or the redirect from Settings.
|
||||
* Files and LuCI's own paths always get the 404: at home this script is LuCI's error page, and a
|
||||
* missing script must not turn into someone's website.
|
||||
*/
|
||||
function not_found() {
|
||||
let parts = split(split(uri, '?')[0], '/');
|
||||
let file = match(uri, /^\/(luci-static|cgi-bin|ubus)(\/|$)/) || match(parts[length(parts) - 1], /\./);
|
||||
if (redirect && !file) {
|
||||
headers('302 Found', { 'Location': redirect, 'Cache-Control': 'no-store', 'Content-Type': 'text/plain' });
|
||||
print('Moved\n');
|
||||
}
|
||||
else {
|
||||
headers('404 Not Found', { 'Content-Type': 'text/plain' });
|
||||
print('Not found\n');
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
|
||||
const title = m.settings.portal_title || 'Dawnline';
|
||||
// Plain HTTP only for an IP address chosen in Settings (no certificate exists
|
||||
// for it); names, and LuCI's web server at home, stay HTTPS-only.
|
||||
if (getenv('HTTPS') != 'on') {
|
||||
let h = getenv('HTTP_HOST') ?? '';
|
||||
h = match(h, /^\[/) ? h : split(h, ':')[0];
|
||||
if (ip2int(h) == null || index(core.portal_hosts(m), h) < 0)
|
||||
not_found();
|
||||
}
|
||||
// The link is /<word-code>[/assets/…|/api/…]: the code is the address.
|
||||
if (length(segs) < 1 || !match(segs[0], core.WORD_CODE))
|
||||
not_found();
|
||||
const code = segs[0];
|
||||
const base = `/${code}`;
|
||||
const rest = slice(segs, 1);
|
||||
let person = null;
|
||||
for (let id, p in m.people)
|
||||
if (p.code == code)
|
||||
person = p;
|
||||
|
||||
// A wrong code or a blocked address: indistinguishable from a path that does
|
||||
// not exist. Only well-formed guesses count towards the limit.
|
||||
if (rate_blocked())
|
||||
not_found();
|
||||
if (person == null) {
|
||||
rate_fail();
|
||||
not_found();
|
||||
}
|
||||
|
||||
const person_id = person.id;
|
||||
|
||||
// The app shell; it reads the code from its own URL and sends it along.
|
||||
if (length(rest) == 0 && method == 'GET')
|
||||
page('200 OK', base, title, code);
|
||||
|
||||
// Script, styles, icon and fonts (kept outside the web root).
|
||||
if (rest[0] == 'assets' && length(rest) == 2 && method == 'GET') {
|
||||
let name = rest[1];
|
||||
let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2)$/)?.[1];
|
||||
let data = ext ? readfile(`${ASSETS}/${name}`) : null;
|
||||
if (data == null)
|
||||
not_found();
|
||||
headers('200 OK', { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=3600' });
|
||||
print(data);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
if (rest[0] != 'api')
|
||||
not_found();
|
||||
|
||||
// CSRF: only same-origin JSON requests (uhttpd passes no custom headers to
|
||||
// CGI; a cross-site page cannot send application/json without CORS, and it
|
||||
// would need the code anyway).
|
||||
if (method == 'POST') {
|
||||
let origin = getenv('HTTP_ORIGIN');
|
||||
if (!match(getenv('CONTENT_TYPE') ?? '', /^application\/json/) ||
|
||||
(origin != null && origin != `${getenv('HTTPS') == 'on' ? 'https' : 'http'}://${getenv('HTTP_HOST')}`))
|
||||
fail('403 Forbidden', 'Cross-site request refused.');
|
||||
}
|
||||
else if (method != 'GET')
|
||||
fail('405 Method Not Allowed', 'Method not allowed.');
|
||||
|
||||
const api = slice(rest, 1);
|
||||
|
||||
function state() {
|
||||
let usage = core.load_usage();
|
||||
let dmp = live.dump();
|
||||
let v = view.person_view(m, person, usage, dmp, view.states(m, usage));
|
||||
let srv = m.servers[person.server];
|
||||
return {
|
||||
title,
|
||||
person: v,
|
||||
server: { name: srv?.name, endpoint: core.endpoint_host(m, srv) },
|
||||
can_add: length(person.devices) < person.device_limit,
|
||||
kinds: core.KINDS,
|
||||
version: VERSION,
|
||||
};
|
||||
}
|
||||
|
||||
function own_device(id) {
|
||||
let d = m.devices[id];
|
||||
if (!d || d.person != person.id)
|
||||
fail('404 Not Found', 'Device not found.');
|
||||
return d;
|
||||
}
|
||||
|
||||
if (api[0] == 'state' && method == 'GET')
|
||||
send_json('200 OK', state());
|
||||
|
||||
if (api[0] == 'devices' && length(api) == 1 && method == 'POST') {
|
||||
let b = body();
|
||||
let l = lock('config');
|
||||
let id;
|
||||
try {
|
||||
let c = core.open_cursor();
|
||||
m = core.load(c);
|
||||
person = m.people[person_id];
|
||||
id = core.create_device(c, m, person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key || null });
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
}
|
||||
catch (e) {
|
||||
unlock(l);
|
||||
fail('400 Bad Request', e.message);
|
||||
}
|
||||
unlock(l);
|
||||
apply.sync();
|
||||
m = core.load();
|
||||
person = m.people[person_id];
|
||||
live.add_event({ type: 'device_added', person: person.id, device: id, detail: `${m.devices[id].name} (portal)` });
|
||||
core.mark_issued(m, id);
|
||||
send_json('200 OK', { id, config: core.client_config(m, m.devices[id]), state: state() });
|
||||
}
|
||||
|
||||
if (api[0] == 'devices' && length(api) == 3 && api[2] == 'config' && method == 'GET') {
|
||||
let d = own_device(api[1]);
|
||||
core.mark_issued(m, d.id);
|
||||
send_json('200 OK', core.client_config(m, d));
|
||||
}
|
||||
|
||||
if (api[0] == 'devices' && length(api) == 2 && method == 'POST') {
|
||||
own_device(api[1]);
|
||||
let b = body();
|
||||
let l = lock('config');
|
||||
try {
|
||||
let c = core.open_cursor();
|
||||
m = core.load(c);
|
||||
if (b.action == 'rename')
|
||||
core.rename_device(c, m, api[1], b.name);
|
||||
else if (b.action == 'delete') {
|
||||
let d = m.devices[api[1]];
|
||||
core.delete_device(c, m, api[1]);
|
||||
live.add_event({ type: 'device_removed', person: person.id, device: api[1], detail: `${d.name} (portal)` });
|
||||
}
|
||||
else
|
||||
die('Unknown action.');
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
}
|
||||
catch (e) {
|
||||
unlock(l);
|
||||
fail('400 Bad Request', e.message);
|
||||
}
|
||||
unlock(l);
|
||||
if (b.action == 'delete')
|
||||
apply.sync();
|
||||
m = core.load();
|
||||
person = m.people[person_id];
|
||||
send_json('200 OK', { ok: true, state: state() });
|
||||
}
|
||||
|
||||
fail('404 Not Found', 'Not found.');
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"admin/network/dawnline": {
|
||||
"title": "Dawnline",
|
||||
"order": 65,
|
||||
"action": {
|
||||
"type": "alias",
|
||||
"path": "admin/network/dawnline/server"
|
||||
},
|
||||
"depends": {
|
||||
"acl": [
|
||||
"luci-app-dawnline"
|
||||
],
|
||||
"uci": {
|
||||
"dawnline": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/overview": {
|
||||
"action": {
|
||||
"type": "view",
|
||||
"path": "dawnline/server"
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/people": {
|
||||
"action": {
|
||||
"type": "view",
|
||||
"path": "dawnline/people"
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/activity": {
|
||||
"title": "Activity",
|
||||
"order": 25,
|
||||
"action": {
|
||||
"type": "view",
|
||||
"path": "dawnline/activity"
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/person": {
|
||||
"action": {
|
||||
"type": "view",
|
||||
"path": "dawnline/person"
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/server": {
|
||||
"title": "Servers",
|
||||
"order": 10,
|
||||
"action": {
|
||||
"type": "view",
|
||||
"path": "dawnline/server"
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/health": {
|
||||
"title": "Health",
|
||||
"order": 40,
|
||||
"action": {
|
||||
"type": "view",
|
||||
"path": "dawnline/health"
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/settings": {
|
||||
"title": "Settings",
|
||||
"order": 60,
|
||||
"action": {
|
||||
"type": "view",
|
||||
"path": "dawnline/settings"
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/updates": {
|
||||
"title": "Updates",
|
||||
"order": 70,
|
||||
"action": {
|
||||
"type": "view",
|
||||
"path": "dawnline/updates"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"luci-app-dawnline": {
|
||||
"description": "Grant access to Dawnline",
|
||||
"read": {
|
||||
"ubus": {
|
||||
"luci.dawnline": [
|
||||
"status",
|
||||
"setup_defaults",
|
||||
"health",
|
||||
"backup_list",
|
||||
"updates_status",
|
||||
"person_usage",
|
||||
"settings_get",
|
||||
"interfaces",
|
||||
"events"
|
||||
]
|
||||
},
|
||||
"uci": [
|
||||
"dawnline",
|
||||
"network",
|
||||
"firewall"
|
||||
]
|
||||
},
|
||||
"write": {
|
||||
"ubus": {
|
||||
"luci.dawnline": [
|
||||
"*"
|
||||
]
|
||||
},
|
||||
"uci": [
|
||||
"dawnline"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,621 @@
|
||||
// Dawnline — reconciliation. Turns /etc/config/dawnline into router state:
|
||||
// * network interfaces (proto amneziawg), peers applied live with `awg syncconf`
|
||||
// * firewall zones, forwardings and WAN rules (named sections dawnline_*)
|
||||
// * nft table `inet dawnline` enforcing each person's access
|
||||
// * hostnames in /tmp/hosts/dawnline
|
||||
// * the "like a home device" path and the Home-only resolver (dawnline.loop)
|
||||
// Only objects created by Dawnline are ever modified.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { readfile, writefile, stat, unlink } from 'fs';
|
||||
import {
|
||||
q, sh, sh_out, sh_bg, ensure_dir, write_file, write_json, read_json, parse_cidr, int2ip, uniq,
|
||||
lock, unlock, RUN_DIR
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
|
||||
const HOSTS_FILE = '/tmp/hosts/dawnline';
|
||||
/*
|
||||
* Our own answers leave by the main table: the portal's (TCP) and each
|
||||
* tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule) may mark
|
||||
* the router's own traffic to internet addresses and divert it locally, which
|
||||
* swallows replies to outside clients. These rules sit before such fwmark
|
||||
* rules and only match our listening ports.
|
||||
*/
|
||||
const PREF_REPLY = 90;
|
||||
|
||||
function log(msg) {
|
||||
system(`logger -t dawnline ${q(msg)}`);
|
||||
}
|
||||
|
||||
/* ---------- helpers ---------- */
|
||||
|
||||
/** Set an option only when it differs; returns true if something changed. */
|
||||
function put(c, conf, sec, opt, val) {
|
||||
let cur = c.get(conf, sec, opt);
|
||||
if (val == null || val == '' || (type(val) == 'array' && !length(val))) {
|
||||
if (cur != null) {
|
||||
c.delete(conf, sec, opt);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (type(val) == 'array') {
|
||||
if (type(cur) == 'array' && join('\n', cur) == join('\n', val))
|
||||
return false;
|
||||
}
|
||||
else if (cur == `${val}`)
|
||||
return false;
|
||||
c.set(conf, sec, opt, type(val) == 'array' ? val : `${val}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
function ensure_section(c, conf, sec, stype) {
|
||||
if (c.get(conf, sec) == stype)
|
||||
return false;
|
||||
if (c.get(conf, sec) != null)
|
||||
c.delete(conf, sec);
|
||||
c.set(conf, sec, stype);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* After committing a config ourselves (and applying it), record its new
|
||||
* checksum so a later `reload_config` does not treat it as changed and
|
||||
* restart unrelated services that reload on any network change.
|
||||
*/
|
||||
function ack_config(confs) {
|
||||
let md5f = '/var/run/config.md5';
|
||||
if (!stat(md5f))
|
||||
return;
|
||||
let lines = split(trim(readfile(md5f) ?? ''), '\n');
|
||||
for (let conf in confs) {
|
||||
let path = `/var/run/config.check/${conf}`;
|
||||
let sum = sh_out(`uci show ${q(conf)} | md5sum | cut -d' ' -f1`);
|
||||
if (!sum)
|
||||
continue;
|
||||
let found = false;
|
||||
for (let i = 0; i < length(lines); i++)
|
||||
if (substr(lines[i], -length(path) - 2) == ` ${path}`) {
|
||||
lines[i] = `${sum} ${path}`;
|
||||
found = true;
|
||||
}
|
||||
if (!found)
|
||||
push(lines, `${sum} ${path}`);
|
||||
}
|
||||
writefile(md5f, join('\n', lines) + '\n');
|
||||
}
|
||||
|
||||
/* ---------- network ---------- */
|
||||
|
||||
function sync_network(m) {
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
let changed = false, touched = [];
|
||||
let want = {};
|
||||
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.private_key)
|
||||
continue;
|
||||
let ifn = srv.ifname;
|
||||
want[ifn] = true;
|
||||
let addr = core.server_address(srv);
|
||||
let pc = parse_cidr(srv.subnet);
|
||||
let before = changed;
|
||||
changed = ensure_section(c, 'network', ifn, 'interface') || changed;
|
||||
changed = put(c, 'network', ifn, 'proto', 'amneziawg') || changed;
|
||||
changed = put(c, 'network', ifn, 'private_key', srv.private_key) || changed;
|
||||
changed = put(c, 'network', ifn, 'listen_port', srv.port) || changed;
|
||||
changed = put(c, 'network', ifn, 'addresses', [ `${addr}/${pc.prefix}` ]) || changed;
|
||||
changed = put(c, 'network', ifn, 'mtu', srv.mtu) || changed;
|
||||
changed = put(c, 'network', ifn, 'disabled', srv.enabled ? null : '1') || changed;
|
||||
changed = put(c, 'network', ifn, 'auto', srv.enabled ? null : '0') || changed;
|
||||
changed = put(c, 'network', ifn, '_dawnline', id) || changed;
|
||||
for (let k in core.OBF_KEYS)
|
||||
changed = put(c, 'network', ifn, `awg_${k}`, srv.obf[k]) || changed;
|
||||
if (changed != before)
|
||||
push(touched, ifn);
|
||||
}
|
||||
|
||||
// Remove interfaces Dawnline created for servers that no longer exist.
|
||||
let stale = [];
|
||||
c.foreach('network', 'interface', (s) => {
|
||||
if (s._dawnline && !want[s['.name']])
|
||||
push(stale, s['.name']);
|
||||
});
|
||||
for (let ifn in stale) {
|
||||
system(`ifdown ${q(ifn)} 2>/dev/null`);
|
||||
c.delete('network', ifn);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
c.commit('network');
|
||||
ack_config([ 'network' ]);
|
||||
system('ubus call network reload');
|
||||
for (let ifn in touched)
|
||||
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
|
||||
system(`ifup ${q(ifn)}`);
|
||||
log(`network updated (${join(', ', touched) || 'removed ' + join(', ', stale)})`);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/* ---------- firewall ---------- */
|
||||
|
||||
const LOOP_ZONE = 'dl_loop';
|
||||
|
||||
function sync_firewall(m) {
|
||||
let c = cursor();
|
||||
c.load('firewall');
|
||||
let changed = false, want = {};
|
||||
|
||||
let sec = (name, stype, opts) => {
|
||||
want[name] = true;
|
||||
changed = ensure_section(c, 'firewall', name, stype) || changed;
|
||||
for (let k, v in opts)
|
||||
changed = put(c, 'firewall', name, k, v) || changed;
|
||||
};
|
||||
|
||||
let snap = net.snapshot(true);
|
||||
let portal_zone = null, want_loop = false;
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.private_key)
|
||||
continue;
|
||||
let z = `dawnline_${id}`;
|
||||
let sn = net.server_net(srv, snap);
|
||||
portal_zone ??= sn.wan.zone;
|
||||
sec(`${z}_zone`, 'zone', {
|
||||
name: srv.ifname, network: [ srv.ifname ],
|
||||
input: 'ACCEPT', output: 'ACCEPT', forward: 'REJECT',
|
||||
});
|
||||
// Access per person is enforced by the inet dawnline table; the zone
|
||||
// only needs to be allowed to reach each home-network zone and WAN.
|
||||
for (let i, zone in sn.zones)
|
||||
if (zone != sn.wan.zone && zone != srv.ifname)
|
||||
sec(i == 0 ? `${z}_lan` : `${z}_lan_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`, 'forwarding', { src: srv.ifname, dest: zone });
|
||||
sec(`${z}_wan`, 'forwarding', { src: srv.ifname, dest: sn.wan.zone });
|
||||
if (srv.lan_like) {
|
||||
sec(`${z}_loop`, 'forwarding', { src: srv.ifname, dest: LOOP_ZONE });
|
||||
want_loop = true;
|
||||
}
|
||||
sec(`${z}_port`, 'rule', {
|
||||
name: `Dawnline-${srv.ifname}`, src: sn.wan.zone, proto: 'udp',
|
||||
dest_port: srv.port, target: 'ACCEPT', enabled: srv.enabled ? null : '0',
|
||||
});
|
||||
}
|
||||
|
||||
// The link into the netns that re-enters the router from the LAN.
|
||||
if (want_loop) {
|
||||
sec('dawnline_loop', 'zone', {
|
||||
name: LOOP_ZONE, device: [ net.INTERNAL.transit ],
|
||||
input: 'REJECT', output: 'ACCEPT', forward: 'REJECT',
|
||||
});
|
||||
// The Home-only resolver in the netns reaches its upstream DNS this way.
|
||||
sec('dawnline_loop_wan', 'forwarding', { src: LOOP_ZONE, dest: portal_zone ?? 'wan' });
|
||||
}
|
||||
|
||||
if (m.settings.portal_enabled) {
|
||||
let wan = portal_zone ?? 'wan';
|
||||
sec('dawnline_portal', 'rule', {
|
||||
name: 'Dawnline-Portal', src: wan, proto: 'tcp',
|
||||
dest_port: m.settings.portal_port, target: 'ACCEPT',
|
||||
});
|
||||
// IP addresses in links: plain HTTP next to the HTTPS port, and 80 forwarded to it.
|
||||
if (core.portal_http(m)) {
|
||||
sec('dawnline_portal_http', 'rule', {
|
||||
name: 'Dawnline-Portal-HTTP', src: wan, proto: 'tcp',
|
||||
dest_port: core.portal_http_port(m), target: 'ACCEPT',
|
||||
});
|
||||
if (core.portal_http_public(m) == 80)
|
||||
sec('dawnline_portal_80', 'redirect', {
|
||||
name: 'Dawnline-Portal-80', src: wan, proto: 'tcp',
|
||||
src_dport: 80, dest_port: core.portal_http_port(m), target: 'DNAT',
|
||||
});
|
||||
}
|
||||
// Links use 443: from outside it lands on the portal (LuCI stays closed there).
|
||||
if (core.portal_public_port(m) == 443 && m.settings.portal_port != 443)
|
||||
sec('dawnline_portal_443', 'redirect', {
|
||||
name: 'Dawnline-Portal-443', src: wan, proto: 'tcp',
|
||||
src_dport: 443, dest_port: m.settings.portal_port, target: 'DNAT',
|
||||
});
|
||||
}
|
||||
|
||||
let stale = [];
|
||||
c.foreach('firewall', null, (s) => {
|
||||
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
|
||||
push(stale, s['.name']);
|
||||
});
|
||||
for (let s in stale) {
|
||||
c.delete('firewall', s);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
c.commit('firewall');
|
||||
ack_config([ 'firewall' ]);
|
||||
system('fw4 -q reload');
|
||||
log('firewall updated');
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/* ---------- nft access table ---------- */
|
||||
|
||||
const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
|
||||
|
||||
/** Per-person runtime membership: which tunnel addresses may reach what. */
|
||||
export function access_sets(m, usage, states) {
|
||||
let sets = { lan_ok: [], inet_ok: [], svc_ok: [], dns_real: [] };
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (!p || d.disabled || !d.address || states[p.id] != 'active')
|
||||
continue;
|
||||
// Plain DNS for whoever's internet does not go through the router.
|
||||
// Home names: the plain resolver (their internet does not use the tunnel).
|
||||
if (p.access == 'lan' && p.dns_mode == 'home')
|
||||
push(sets.dns_real, d.address);
|
||||
if (p.access == 'internet' || p.access == 'both')
|
||||
push(sets.inet_ok, d.address);
|
||||
if (p.access == 'both' || (p.access == 'lan' && !length(p.services)))
|
||||
push(sets.lan_ok, d.address);
|
||||
else if (p.access == 'lan')
|
||||
for (let sid in p.services) {
|
||||
let s = m.services[sid];
|
||||
if (!s || !s.address)
|
||||
continue;
|
||||
for (let port in s.ports)
|
||||
if (match(port, /^[0-9]+$/))
|
||||
push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`);
|
||||
}
|
||||
}
|
||||
return sets;
|
||||
};
|
||||
|
||||
function set_elems(arr) {
|
||||
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
|
||||
}
|
||||
|
||||
function nft_table(m, sets) {
|
||||
let ifs = [], lan = [];
|
||||
let dns_addr = loop.client_dns();
|
||||
let rt = loop.resolver_target();
|
||||
let snap = net.snapshot();
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key) {
|
||||
push(ifs, `"${srv.ifname}"`);
|
||||
push(lan, ...net.server_net(srv, snap).nets);
|
||||
}
|
||||
lan = net.collapse(lan);
|
||||
let t = [];
|
||||
push(t, 'table inet dawnline {');
|
||||
push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`);
|
||||
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
|
||||
push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`);
|
||||
push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`);
|
||||
push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`);
|
||||
push(t, ' chain pre {');
|
||||
// Ahead of mangle-priority hooks (transparent proxies mark at -150).
|
||||
push(t, ' type filter hook prerouting priority -160; policy accept;');
|
||||
if (length(ifs))
|
||||
push(t, ` iifname { ${join(', ', ifs)} } jump guard`);
|
||||
push(t, ' }');
|
||||
push(t, ' chain guard {');
|
||||
push(t, ' meta nfproto ipv6 drop');
|
||||
push(t, ' ct state established,related accept');
|
||||
push(t, ' icmp type echo-request fib daddr type local accept');
|
||||
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
|
||||
push(t, ' fib daddr type local ip saddr @lan_ok accept');
|
||||
push(t, ' fib daddr type local counter drop');
|
||||
if (dns_addr)
|
||||
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
|
||||
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
|
||||
push(t, ' ip daddr @lan_nets ip saddr @lan_ok accept');
|
||||
push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept');
|
||||
push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`);
|
||||
push(t, ' ip saddr @inet_ok accept');
|
||||
push(t, ' counter drop');
|
||||
push(t, ' }');
|
||||
// Devices ask the tunnel address; send each query where it belongs.
|
||||
let to_resolver = rt.mode == 'ns' ? `dnat ip to ${rt.address}:53` : `redirect to :${rt.port}`;
|
||||
let lan_dns = loop.lan_dns();
|
||||
push(t, ' chain dns {');
|
||||
push(t, ' type nat hook prerouting priority dstnat - 5; policy accept;');
|
||||
if (length(ifs))
|
||||
// Home names (and no LAN DNS at all): the plain resolver, whatever address was asked.
|
||||
push(t, ` iifname { ${join(', ', ifs)} } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 ${to_resolver}`);
|
||||
for (let id, srv in m.servers) {
|
||||
let a = srv.private_key ? core.server_address(srv) : null;
|
||||
if (!a)
|
||||
continue;
|
||||
// Everyone else: the LAN's DNS, through the netns (from the LAN side) when internet goes that way.
|
||||
let target = srv.lan_like && dns_addr ? `dnat ip to ${dns_addr}:53` : lan_dns ? `dnat ip to ${lan_dns}:53` : to_resolver;
|
||||
push(t, ` iifname "${srv.ifname}" ip daddr ${a} meta l4proto { tcp, udp } th dport 53 ${target}`);
|
||||
}
|
||||
push(t, ' }');
|
||||
push(t, '}');
|
||||
return join('\n', t) + '\n';
|
||||
}
|
||||
|
||||
function nft_load(script) {
|
||||
ensure_dir(RUN_DIR);
|
||||
let f = `${RUN_DIR}/nft.rules`;
|
||||
writefile(f, script);
|
||||
let r = sh(`nft -f ${f}`);
|
||||
if (r.code != 0)
|
||||
log(`nft failed: ${trim(r.out)}`);
|
||||
return r.code == 0;
|
||||
}
|
||||
|
||||
/** Full table rebuild (structure changes: servers, LAN subnets). */
|
||||
export function rebuild_nft(m, sets) {
|
||||
let s = 'table inet dawnline\ndelete table inet dawnline\n' + nft_table(m, sets);
|
||||
return nft_load(s);
|
||||
};
|
||||
|
||||
/** Atomically replace set contents only. */
|
||||
export function update_sets(sets) {
|
||||
let s = '';
|
||||
for (let name in [ 'lan_ok', 'inet_ok', 'svc_ok', 'dns_real' ]) {
|
||||
s += `flush set inet dawnline ${name}\n`;
|
||||
if (length(sets[name]))
|
||||
s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`;
|
||||
}
|
||||
return nft_load(s);
|
||||
};
|
||||
|
||||
export function remove_nft() {
|
||||
system('nft delete table inet dawnline 2>/dev/null');
|
||||
};
|
||||
|
||||
/* ---------- AmneziaWG peers ---------- */
|
||||
|
||||
/** Push the peer list of every server to the kernel without restarting it. */
|
||||
export function sync_peers(m, states) {
|
||||
ensure_dir(RUN_DIR);
|
||||
let res = {};
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.private_key || !srv.enabled)
|
||||
continue;
|
||||
if (system(`awg show ${q(srv.ifname)} public-key >/dev/null 2>&1`) != 0) {
|
||||
res[id] = 'down';
|
||||
continue;
|
||||
}
|
||||
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
|
||||
for (let did, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !d.public_key || !d.address)
|
||||
continue;
|
||||
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
|
||||
if (d.preshared_key)
|
||||
push(lines, `PresharedKey = ${d.preshared_key}`);
|
||||
push(lines, `AllowedIPs = ${d.address}/32`, '');
|
||||
}
|
||||
let f = `${RUN_DIR}/${srv.ifname}.conf`;
|
||||
write_file(f, join('\n', lines));
|
||||
let r = sh(`awg syncconf ${q(srv.ifname)} ${f}`);
|
||||
unlink(f);
|
||||
res[id] = r.code == 0 ? 'ok' : trim(r.out);
|
||||
if (r.code != 0)
|
||||
log(`awg syncconf ${srv.ifname}: ${trim(r.out)}`);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
/* ---------- hostnames ---------- */
|
||||
|
||||
function host_label(s) {
|
||||
let l = replace(lc(s), /[^a-z0-9]+/g, '-');
|
||||
l = replace(l, /^-+|-+$/g, '');
|
||||
return substr(l, 0, 40) || 'device';
|
||||
}
|
||||
|
||||
export function sync_hosts(m) {
|
||||
let lines = [];
|
||||
if (m.settings.hostnames)
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (p && d.address)
|
||||
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`);
|
||||
}
|
||||
let ls = loop.status();
|
||||
if (ls.active)
|
||||
push(lines, `${ls.address} dawnline.${m.settings.domain}`);
|
||||
let body = length(lines) ? join('\n', lines) + '\n' : '';
|
||||
// dnsmasq runs as its own user; rpcd's umask would leave the file 0600.
|
||||
let readable = ((stat(HOSTS_FILE)?.perm?.other_read) ?? false);
|
||||
if ((readfile(HOSTS_FILE) ?? '') == body && (body == '' || readable))
|
||||
return false;
|
||||
ensure_dir('/tmp/hosts');
|
||||
if (body == '')
|
||||
unlink(HOSTS_FILE);
|
||||
else {
|
||||
writefile(HOSTS_FILE, body);
|
||||
system(`chmod 644 ${HOSTS_FILE}`);
|
||||
}
|
||||
system('killall -HUP dnsmasq 2>/dev/null');
|
||||
return true;
|
||||
};
|
||||
|
||||
/* ---------- entry points ---------- */
|
||||
|
||||
export function states_for(m, usage) {
|
||||
let st = {};
|
||||
for (let id, p in m.people)
|
||||
st[id] = core.person_state(m, p, usage);
|
||||
return st;
|
||||
};
|
||||
|
||||
/** Runtime sync: peers + access sets + hostnames. Cheap; safe to call often. */
|
||||
export function sync(m, usage) {
|
||||
m ??= core.load();
|
||||
usage ??= core.load_usage();
|
||||
let states = states_for(m, usage);
|
||||
let l = lock('apply');
|
||||
let peers = sync_peers(m, states);
|
||||
let sets = access_sets(m, usage, states);
|
||||
if (!update_sets(sets))
|
||||
rebuild_nft(m, sets);
|
||||
sync_hosts(m);
|
||||
unlock(l);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/states.json`, states, 0o644);
|
||||
return { peers, states };
|
||||
};
|
||||
|
||||
/**
|
||||
* Everything on the router that Dawnline's state is derived from: WAN and
|
||||
* LAN, the home networks and zones of each server, the netns address and the
|
||||
* LAN's DNS. The agent re-applies when it changes (LAN renumbered, interface
|
||||
* added, bridge recreated, DHCP DNS changed, ...).
|
||||
*/
|
||||
export function net_signature(m) {
|
||||
let snap = net.snapshot(true);
|
||||
let srvs = {};
|
||||
for (let id, srv in m.servers)
|
||||
srvs[id] = net.server_net(srv, snap);
|
||||
let lan = snap.devices[snap.lan];
|
||||
return sprintf('%J', { wan: snap.wan, lan: snap.lan, addrs: lan?.addrs, servers: srvs, dns: loop.lan_dns(), loop: loop.client_dns() });
|
||||
};
|
||||
|
||||
const PORTAL_CGI = '/usr/share/dawnline/portal/www/cgi-bin/portal';
|
||||
const LAN_CGI = '/www/cgi-bin/dawnline-portal';
|
||||
const LAN_CGI_URL = '/cgi-bin/dawnline-portal';
|
||||
|
||||
/*
|
||||
* At home the portal's hostname usually points at the router itself, where
|
||||
* LuCI's web server owns 443. Paths it does not know (the portal's) go to the
|
||||
* portal CGI through its error page, so the same link works inside and out.
|
||||
*/
|
||||
function sync_uhttpd(m) {
|
||||
let want = m.settings.portal_enabled && core.portal_public_port(m) == 443 && m.settings.portal_port != 443;
|
||||
let c = cursor();
|
||||
c.load('uhttpd');
|
||||
let cur = c.get('uhttpd', 'main', 'error_page');
|
||||
let changed = false;
|
||||
if (want) {
|
||||
if (!stat(LAN_CGI))
|
||||
system(`ln -sf ${PORTAL_CGI} ${LAN_CGI}`);
|
||||
if (cur == null && c.get('uhttpd', 'main')) {
|
||||
c.set('uhttpd', 'main', 'error_page', LAN_CGI_URL);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (cur == LAN_CGI_URL) {
|
||||
c.delete('uhttpd', 'main', 'error_page');
|
||||
changed = true;
|
||||
}
|
||||
if (stat(LAN_CGI))
|
||||
unlink(LAN_CGI);
|
||||
}
|
||||
if (changed) {
|
||||
c.commit('uhttpd');
|
||||
system('/etc/init.d/uhttpd reload >/dev/null 2>&1');
|
||||
log(want ? 'portal answers on 443 at home too' : 'portal removed from the LuCI web server');
|
||||
}
|
||||
}
|
||||
|
||||
/** One `ipproto <p> sport <port> lookup main` rule per listening port and family. */
|
||||
function sync_reply_routes(m) {
|
||||
let want = [];
|
||||
if (m.settings.portal_enabled) {
|
||||
push(want, `tcp ${+m.settings.portal_port}`);
|
||||
if (core.portal_http(m))
|
||||
push(want, `tcp ${core.portal_http_port(m)}`);
|
||||
}
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key && srv.enabled && +srv.port)
|
||||
push(want, `udp ${+srv.port}`);
|
||||
want = uniq(want);
|
||||
for (let fam in [ '-4', '-6' ]) {
|
||||
let have = [];
|
||||
for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) {
|
||||
let mm = match(line, /ipproto (tcp|udp) sport (\d+) lookup main/);
|
||||
if (mm)
|
||||
push(have, `${mm[1]} ${mm[2]}`);
|
||||
}
|
||||
for (let h in have)
|
||||
if (index(want, h) < 0)
|
||||
sh(`ip ${fam} rule del priority ${PREF_REPLY} ipproto ${split(h, ' ')[0]} sport ${split(h, ' ')[1]} lookup main 2>/dev/null`);
|
||||
for (let w in want)
|
||||
if (index(have, w) < 0)
|
||||
sh(`ip ${fam} rule add priority ${PREF_REPLY} ipproto ${split(w, ' ')[0]} sport ${split(w, ' ')[1]} lookup main`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the "like a home device" path and the resolver in step (agent tick).
|
||||
* Cheap when nothing changed; rebuilds the access table when the netns
|
||||
* address appears, moves or goes away (the guard allows DNS to it).
|
||||
*/
|
||||
export function sync_loop(m, usage, force) {
|
||||
m ??= core.load();
|
||||
let before = `${loop.client_dns()} ${loop.resolver_target().mode}`;
|
||||
let p = loop.ensure(m, force);
|
||||
loop.sync_resolver(m);
|
||||
sync_reply_routes(m);
|
||||
if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before) {
|
||||
usage ??= core.load_usage();
|
||||
rebuild_nft(m, access_sets(m, usage, states_for(m, usage)));
|
||||
sync_hosts(m);
|
||||
}
|
||||
return p;
|
||||
};
|
||||
|
||||
/** Every personal code is a word code; older random ones are replaced (their links stop working). */
|
||||
function ensure_word_codes() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let changed = false;
|
||||
c.foreach('dawnline', 'person', (s) => {
|
||||
if (s.code != null && !match(s.code, core.WORD_CODE)) {
|
||||
c.set('dawnline', s['.name'], 'code', core.new_code());
|
||||
c.delete('dawnline', s['.name'], 'words');
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if (changed) {
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
log('personal links moved to word codes');
|
||||
}
|
||||
}
|
||||
|
||||
/** Full reconcile: router configuration + runtime state. */
|
||||
export function apply(opts) {
|
||||
opts ??= {};
|
||||
ensure_word_codes();
|
||||
let m = core.load();
|
||||
let usage = core.load_usage();
|
||||
let l = lock('reconcile');
|
||||
let net = sync_network(m);
|
||||
let fw = sync_firewall(m);
|
||||
sync_uhttpd(m);
|
||||
let lp = loop.ensure(m, true);
|
||||
loop.sync_resolver(m);
|
||||
sync_reply_routes(m);
|
||||
let states = states_for(m, usage);
|
||||
rebuild_nft(m, access_sets(m, usage, states));
|
||||
unlock(l);
|
||||
let r = sync(m, usage);
|
||||
return { network: net, firewall: fw, like_home: lp.error ? { error: lp.error } : !lp.off, peers: r.peers };
|
||||
};
|
||||
|
||||
/** Remove everything Dawnline created (used by the uninstaller). */
|
||||
export function teardown() {
|
||||
let m = core.load();
|
||||
loop.remove();
|
||||
unlink(loop.RESOLVER.conf);
|
||||
m.servers = {};
|
||||
m.settings.portal_enabled = false;
|
||||
sync_network(m);
|
||||
sync_firewall(m);
|
||||
sync_uhttpd(m);
|
||||
sync_reply_routes(m);
|
||||
remove_nft();
|
||||
unlink(HOSTS_FILE);
|
||||
system('killall -HUP dnsmasq 2>/dev/null');
|
||||
};
|
||||
@@ -0,0 +1,937 @@
|
||||
// Dawnline — data model: reads /etc/config/dawnline, validates and mutates it,
|
||||
// allocates addresses, generates keys and renders client configurations.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { readfile } from 'fs';
|
||||
import {
|
||||
q, sh, sh_out, valid_name, valid_key, valid_host, valid_date, slugify,
|
||||
parse_cidr, cidr_str, cidr_overlaps, int2ip, ip2int, in_cidr, rand_token, rand_hex, rand_int, rand_bytes,
|
||||
date_end, month_key, read_json, write_json, ensure_dir, lock, unlock, DATA_DIR, RUN_DIR, uniq
|
||||
} from 'dawnline.util';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
|
||||
export const CONFIG = 'dawnline';
|
||||
export const ACCESS = [ 'lan', 'internet', 'both' ];
|
||||
export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ];
|
||||
export const OBF_KEYS = [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4', 'h1', 'h2', 'h3', 'h4', 'i1', 'i2', 'i3', 'i4', 'i5',
|
||||
// AmneziaWG 3.x
|
||||
'header_protection_key', 'content_padding_addition', 'rekey_after_time', 'rekey_timeout', 'reject_after_time',
|
||||
'keepalive_timeout', 'max_handshake_attempts', 'random_trailers', 'disable_cookies' ];
|
||||
|
||||
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
|
||||
export const OBF_CONF = {
|
||||
jc: 'Jc', jmin: 'Jmin', jmax: 'Jmax', s1: 'S1', s2: 'S2', s3: 'S3', s4: 'S4',
|
||||
h1: 'H1', h2: 'H2', h3: 'H3', h4: 'H4', i1: 'I1', i2: 'I2', i3: 'I3', i4: 'I4', i5: 'I5',
|
||||
header_protection_key: 'HeaderProtectionKey', content_padding_addition: 'ContentPaddingAddition',
|
||||
rekey_after_time: 'RekeyAfterTime', rekey_timeout: 'RekeyTimeout', reject_after_time: 'RejectAfterTime',
|
||||
keepalive_timeout: 'KeepaliveTimeout', max_handshake_attempts: 'MaxHandshakeAttempts',
|
||||
random_trailers: 'RandomTrailers', disable_cookies: 'DisableCookies',
|
||||
};
|
||||
|
||||
function toint(v, dflt) {
|
||||
if (v == null || v == '')
|
||||
return dflt;
|
||||
let n = +v;
|
||||
return n != n ? dflt : int(n);
|
||||
}
|
||||
|
||||
function num(v, dflt) {
|
||||
if (v == null || v == '')
|
||||
return dflt;
|
||||
let n = +v;
|
||||
return n != n ? dflt : n;
|
||||
}
|
||||
|
||||
function bool(v, dflt) {
|
||||
if (v == null || v == '')
|
||||
return dflt;
|
||||
return v == '1' || v == 'true' || v == 'yes' || v == 'on';
|
||||
}
|
||||
|
||||
function list(v) {
|
||||
if (v == null)
|
||||
return [];
|
||||
return type(v) == 'array' ? v : split(trim(v), /[[:space:],]+/);
|
||||
}
|
||||
|
||||
/* ---------- load ---------- */
|
||||
|
||||
export function open_cursor() {
|
||||
let c = cursor();
|
||||
c.load(CONFIG);
|
||||
return c;
|
||||
};
|
||||
|
||||
export function load(c) {
|
||||
c ??= open_cursor();
|
||||
let s = c.get_all(CONFIG, 'settings') ?? {};
|
||||
let m = {
|
||||
settings: {
|
||||
portal_enabled: bool(s.portal_enabled, false),
|
||||
portal_port: toint(s.portal_port, 8443),
|
||||
// Also answer on 443 from the internet (mobile networks often drop TLS on other ports).
|
||||
portal_443: bool(s.portal_443, true),
|
||||
portal_host: s.portal_host ?? '',
|
||||
// More addresses for the same links (the main one is portal_host).
|
||||
portal_alt: filter(type(s.portal_alt) == 'array' ? s.portal_alt : s.portal_alt ? [ s.portal_alt ] : [], (x) => x != ''),
|
||||
portal_cert: s.portal_cert ?? '',
|
||||
portal_key: s.portal_key ?? '',
|
||||
portal_title: s.portal_title ?? 'Dawnline',
|
||||
// Where unknown portal links go instead of a bare 404 (empty = 404).
|
||||
portal_redirect: s.portal_redirect ?? '',
|
||||
paused_all: bool(s.paused_all, false),
|
||||
default_device_limit: toint(s.default_device_limit, 3),
|
||||
geo_enabled: bool(s.geo_enabled, true),
|
||||
geo_provider: s.geo_provider == 'ipapi.co' ? 'ipapi.co' : 'ipwho.is',
|
||||
hostnames: bool(s.hostnames, true),
|
||||
domain: s.domain ?? 'lan',
|
||||
log_connections: bool(s.log_connections, true),
|
||||
// Second DNS for "home names" devices, used by the device when the tunnel is down.
|
||||
home_dns_fallback: s.home_dns_fallback == 'none' ? '' : (s.home_dns_fallback ?? '1.1.1.1'),
|
||||
// Raw retention values; dawnline.live policy() interprets them.
|
||||
retention: {
|
||||
log_keep_days: s.log_keep_days, log_max: s.log_max, log_category: s.log_category,
|
||||
log_connections: s.log_connections, log_persist: s.log_persist,
|
||||
usage_keep_days: s.usage_keep_days, usage_keep_months: s.usage_keep_months,
|
||||
},
|
||||
},
|
||||
servers: {},
|
||||
people: {},
|
||||
devices: {},
|
||||
services: {},
|
||||
};
|
||||
|
||||
c.foreach(CONFIG, 'server', (r) => {
|
||||
let id = r['.name'];
|
||||
let srv = {
|
||||
id,
|
||||
name: r.name ?? id,
|
||||
ifname: r.ifname ?? id,
|
||||
port: toint(r.port, 51820),
|
||||
subnet: r.subnet ?? '',
|
||||
endpoint: r.endpoint ?? '',
|
||||
mtu: toint(r.mtu, 1380),
|
||||
dns: list(r.dns),
|
||||
keepalive: toint(r.keepalive, 25),
|
||||
private_key: r.private_key ?? '',
|
||||
public_key: r.public_key ?? '',
|
||||
preset: r.preset ?? 'standard',
|
||||
lan_zone: r.lan_zone ?? 'lan',
|
||||
wan_zone: r.wan_zone ?? 'wan',
|
||||
auto_wan: bool(r.auto_wan, true),
|
||||
wan_device: r.wan_device ?? '',
|
||||
auto_lan: bool(r.auto_lan, true),
|
||||
lan_devices: list(r.lan_device),
|
||||
detected_wan: r.detected_wan ?? '',
|
||||
detected_lan: r.detected_lan ?? '',
|
||||
lan_like: bool(r.lan_like, true),
|
||||
enabled: bool(r.enabled, true),
|
||||
obf: {},
|
||||
};
|
||||
for (let k in OBF_KEYS)
|
||||
if (r[k] != null && r[k] != '')
|
||||
srv.obf[k] = `${r[k]}`;
|
||||
m.servers[id] = srv;
|
||||
});
|
||||
|
||||
c.foreach(CONFIG, 'person', (r) => {
|
||||
let id = r['.name'];
|
||||
m.people[id] = {
|
||||
id,
|
||||
server: r.server ?? '',
|
||||
name: r.name ?? id,
|
||||
access: index(ACCESS, r.access) >= 0 ? r.access : 'internet',
|
||||
device_limit: toint(r.device_limit, m.settings.default_device_limit),
|
||||
code: r.code ?? '',
|
||||
expires: r.expires ?? '',
|
||||
quota_gb: num(r.quota_gb, 0),
|
||||
quota_period: r.quota_period == 'total' ? 'total' : 'month',
|
||||
paused: bool(r.paused, false),
|
||||
hours: r.hours ?? '',
|
||||
expire_action: index([ 'pause', 'notify', 'remove' ], r.expire_action) >= 0 ? r.expire_action : 'pause',
|
||||
// Home-only access: keep the device's own DNS, or use home names (Dawnline's resolver).
|
||||
dns_mode: r.dns_mode == 'home' ? 'home' : 'device',
|
||||
expire_warn: toint(r.expire_warn, 3),
|
||||
bonus_gb: num(r.bonus_gb, 0),
|
||||
bonus_month: r.bonus_month ?? '',
|
||||
services: list(r.service),
|
||||
note: r.note ?? '',
|
||||
created: toint(r.created, 0),
|
||||
devices: [],
|
||||
};
|
||||
});
|
||||
|
||||
c.foreach(CONFIG, 'device', (r) => {
|
||||
let id = r['.name'];
|
||||
let d = {
|
||||
id,
|
||||
person: r.person ?? '',
|
||||
name: r.name ?? id,
|
||||
kind: index(KINDS, r.kind) >= 0 ? r.kind : 'other',
|
||||
address: r.address ?? '',
|
||||
public_key: r.public_key ?? '',
|
||||
private_key: r.private_key ?? '',
|
||||
preshared_key: r.preshared_key ?? '',
|
||||
created: toint(r.created, 0),
|
||||
created_by: r.created_by ?? 'admin',
|
||||
disabled: bool(r.disabled, false),
|
||||
};
|
||||
m.devices[id] = d;
|
||||
if (m.people[d.person])
|
||||
push(m.people[d.person].devices, id);
|
||||
});
|
||||
|
||||
c.foreach(CONFIG, 'service', (r) => {
|
||||
let id = r['.name'];
|
||||
m.services[id] = {
|
||||
id,
|
||||
name: r.name ?? id,
|
||||
address: r.address ?? '',
|
||||
ports: list(r.port),
|
||||
};
|
||||
});
|
||||
|
||||
return m;
|
||||
};
|
||||
|
||||
/* ---------- derived state ---------- */
|
||||
|
||||
/** Parse "07:00-23:00" → [startMin, endMin] or null. */
|
||||
export function parse_hours(s) {
|
||||
let m = match(s ?? '', /^([0-9]{1,2}):([0-9]{2})-([0-9]{1,2}):([0-9]{2})$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let a = +m[1] * 60 + +m[2], b = +m[3] * 60 + +m[4];
|
||||
if (a >= 1440 || b > 1440 || a == b)
|
||||
return null;
|
||||
return [ a, b ];
|
||||
};
|
||||
|
||||
function within_hours(h, ts) {
|
||||
let t = localtime(ts);
|
||||
let cur = t.hour * 60 + t.min;
|
||||
return h[0] < h[1] ? (cur >= h[0] && cur < h[1]) : (cur >= h[0] || cur < h[1]);
|
||||
}
|
||||
|
||||
/** Bytes used in the person's quota period. */
|
||||
export function person_usage(p, usage) {
|
||||
let u = usage?.people?.[p.id];
|
||||
if (!u)
|
||||
return 0;
|
||||
if (p.quota_period == 'total')
|
||||
return (u.total?.[0] ?? 0) + (u.total?.[1] ?? 0);
|
||||
let mm = u.months?.[month_key()];
|
||||
return mm ? mm[0] + mm[1] : 0;
|
||||
};
|
||||
|
||||
/** Quota in bytes for the current period (base + this month's bonus), 0 = unlimited. */
|
||||
export function person_quota(p) {
|
||||
if (!(p.quota_gb > 0))
|
||||
return 0;
|
||||
let gb = p.quota_gb;
|
||||
if (p.bonus_gb > 0 && p.bonus_month == month_key())
|
||||
gb += p.bonus_gb;
|
||||
return gb * 1073741824;
|
||||
};
|
||||
|
||||
export function person_expired(p, ts) {
|
||||
if (p.expires == '')
|
||||
return false;
|
||||
let end = date_end(p.expires);
|
||||
return end != null && (ts ?? time()) > end;
|
||||
};
|
||||
|
||||
/**
|
||||
* Effective state of a person: 'active', or why they are off:
|
||||
* 'paused' (admin), 'paused_all', 'expired', 'quota', 'hours', 'no_server'.
|
||||
*/
|
||||
export function person_state(m, p, usage, ts) {
|
||||
ts ??= time();
|
||||
let srv = m.servers[p.server];
|
||||
if (!srv || !srv.enabled)
|
||||
return 'no_server';
|
||||
if (p.paused)
|
||||
return 'paused';
|
||||
if (m.settings.paused_all)
|
||||
return 'paused_all';
|
||||
// "notify" keeps access after the end date (shown in Overview and People).
|
||||
if (person_expired(p, ts) && p.expire_action != 'notify')
|
||||
return 'expired';
|
||||
let quota = person_quota(p);
|
||||
if (quota > 0 && person_usage(p, usage) >= quota)
|
||||
return 'quota';
|
||||
let h = parse_hours(p.hours);
|
||||
if (h && !within_hours(h, ts))
|
||||
return 'hours';
|
||||
return 'active';
|
||||
};
|
||||
|
||||
export function load_usage() {
|
||||
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} });
|
||||
};
|
||||
|
||||
/* ---------- keys ---------- */
|
||||
|
||||
export function genkey() {
|
||||
return sh_out('awg genkey');
|
||||
};
|
||||
|
||||
export function pubkey(priv) {
|
||||
if (!valid_key(priv))
|
||||
return null;
|
||||
return sh_out(`printf %s ${q(priv)} | awg pubkey`);
|
||||
};
|
||||
|
||||
export function genpsk() {
|
||||
return sh_out('awg genpsk');
|
||||
};
|
||||
|
||||
/* ---------- networks ---------- */
|
||||
|
||||
/** IPv4 subnets of the router's LAN zone (from netifd), as CIDR strings. */
|
||||
/** Router address inside the server subnet (first host). */
|
||||
export function server_address(srv) {
|
||||
let c = parse_cidr(srv.subnet);
|
||||
return c ? int2ip(c.first) : null;
|
||||
};
|
||||
|
||||
export function alloc_address(m, srv) {
|
||||
let c = parse_cidr(srv.subnet);
|
||||
if (!c)
|
||||
return null;
|
||||
let used = {};
|
||||
used[c.first] = true;
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (p && p.server == srv.id) {
|
||||
let n = ip2int(d.address);
|
||||
if (n != null)
|
||||
used[n] = true;
|
||||
}
|
||||
}
|
||||
for (let n = c.first + 1; n <= c.last; n++)
|
||||
if (!used[n])
|
||||
return int2ip(n);
|
||||
return null;
|
||||
};
|
||||
|
||||
/* ---------- obfuscation ---------- */
|
||||
|
||||
const OBF_SPEC = { jc: [ 0, 10 ], jmin: [ 64, 1024 ], jmax: [ 64, 1024 ], s1: [ 0, 64 ], s2: [ 0, 64 ], s3: [ 0, 64 ], s4: [ 0, 32 ] };
|
||||
|
||||
function rand_h(used) {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
let v = rand_int(5, 2147483647);
|
||||
if (!used[v]) {
|
||||
used[v] = true;
|
||||
return `${v}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the installed AmneziaWG can do, from the netifd protocol script (the
|
||||
* options it passes on) and the `awg` tool (the keys it accepts):
|
||||
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
|
||||
* v3 — header protection, trailers, padding, timing (AWG 3.1)
|
||||
*/
|
||||
export function awg_caps() {
|
||||
let script = readfile('/lib/netifd/proto/amneziawg.sh') ?? '';
|
||||
let tool = sh_out("grep -a -o -m1 'HeaderProtectionKey' /usr/bin/awg 2>/dev/null") ?? '';
|
||||
let v2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0;
|
||||
let v3 = v2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
|
||||
return { v2, v3 };
|
||||
};
|
||||
|
||||
/** First junk packet shaped like a DNS answer (AmneziaVPN's own default for 3.1). */
|
||||
const DNS_MIMIC = '<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>';
|
||||
|
||||
/**
|
||||
* Generate obfuscation parameters for a method:
|
||||
* off plain WireGuard-compatible packets
|
||||
* standard junk packets and random headers (any AmneziaWG client)
|
||||
* strong more and larger junk (any AmneziaWG client)
|
||||
* max AmneziaWG 3.1: protected headers, random trailers, padding,
|
||||
* jittered timers and a DNS-like first packet — the values
|
||||
* AmneziaVPN itself uses for 3.1 servers
|
||||
*/
|
||||
export function obf_preset(name) {
|
||||
if (name == 'max')
|
||||
return {
|
||||
jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50',
|
||||
s1: '12', s2: '12', s3: '12', s4: '12',
|
||||
h1: '1', h2: '2', h3: '3', h4: '4',
|
||||
i1: DNS_MIMIC,
|
||||
header_protection_key: genkey(),
|
||||
content_padding_addition: '10-100',
|
||||
rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180',
|
||||
keepalive_timeout: '5-15', max_handshake_attempts: '15-20',
|
||||
random_trailers: 'on', disable_cookies: 'on',
|
||||
};
|
||||
if (name == 'off')
|
||||
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
|
||||
let strong = name == 'strong';
|
||||
let o = {};
|
||||
o.jc = `${strong ? rand_int(6, 10) : rand_int(3, 6)}`;
|
||||
let jmin = rand_int(64, strong ? 128 : 96);
|
||||
o.jmin = `${jmin}`;
|
||||
o.jmax = `${jmin + rand_int(strong ? 200 : 32, strong ? 600 : 160)}`;
|
||||
let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
|
||||
while (s1 + 56 == s2)
|
||||
s2 = rand_int(15, 64);
|
||||
o.s1 = `${s1}`;
|
||||
o.s2 = `${s2}`;
|
||||
let used = {};
|
||||
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
|
||||
o[k] = rand_h(used);
|
||||
return o;
|
||||
};
|
||||
|
||||
export function obf_errors(o) {
|
||||
let errs = [];
|
||||
for (let k, r in OBF_SPEC) {
|
||||
let v = o[k];
|
||||
if (v == null || v == '')
|
||||
continue;
|
||||
if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1]) {
|
||||
if (!(v == '0' && (k == 'jmin' || k == 'jmax')))
|
||||
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
|
||||
}
|
||||
}
|
||||
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
|
||||
push(errs, 'jmin > jmax');
|
||||
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
|
||||
push(errs, 's1 + 56 = s2');
|
||||
let hs = {};
|
||||
for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) {
|
||||
let v = o[k];
|
||||
if (v == null || v == '')
|
||||
continue;
|
||||
if (!match(v, /^[0-9]+(-[0-9]+)?$/))
|
||||
push(errs, `${k} must be a number or range`);
|
||||
else if (hs[v])
|
||||
push(errs, 'h1-h4 must be distinct');
|
||||
hs[v] = true;
|
||||
}
|
||||
return errs;
|
||||
};
|
||||
|
||||
/* ---------- client configuration ---------- */
|
||||
|
||||
export function endpoint_host(m, srv) {
|
||||
return srv.endpoint || m.settings.portal_host || '';
|
||||
};
|
||||
|
||||
/**
|
||||
* DNS for a server's clients: the router's tunnel address, which never
|
||||
* changes after setup. The router forwards each query where it belongs (the
|
||||
* LAN's DNS, from the LAN side; or the plain resolver), so configurations on
|
||||
* devices keep working when the LAN, its DNS or the netns address change.
|
||||
*/
|
||||
export function dns_list(m, srv) {
|
||||
if (!srv)
|
||||
return [];
|
||||
if (length(srv.dns))
|
||||
return srv.dns;
|
||||
let a = server_address(srv);
|
||||
return a ? [ a ] : [];
|
||||
};
|
||||
|
||||
/**
|
||||
* DNS written into a device's configuration. Home-only people keep their
|
||||
* device's DNS unless they chose home names; then the first server is
|
||||
* Dawnline's plain resolver (reached through the tunnel) and the second the
|
||||
* fallback the device uses when the tunnel is down.
|
||||
*/
|
||||
export function client_dns(m, srv, p) {
|
||||
if (p?.access != 'lan')
|
||||
return dns_list(m, srv);
|
||||
if (p.dns_mode != 'home')
|
||||
return [];
|
||||
let a = server_address(srv);
|
||||
let out = a ? [ a ] : [];
|
||||
if (m.settings.home_dns_fallback && m.settings.home_dns_fallback != a)
|
||||
push(out, m.settings.home_dns_fallback);
|
||||
return out;
|
||||
};
|
||||
|
||||
export function allowed_ips(m, srv, p) {
|
||||
if (p.access == 'lan') {
|
||||
let nets = net.server_net(srv).nets;
|
||||
let a = server_address(srv);
|
||||
if (a)
|
||||
push(nets, `${a}/32`);
|
||||
// The resolver address must be reachable through the tunnel too (not the fallback).
|
||||
let dns = client_dns(m, srv, p)[0];
|
||||
if (dns)
|
||||
push(nets, `${dns}/32`);
|
||||
return net.collapse(nets);
|
||||
}
|
||||
return [ '0.0.0.0/0', '::/0' ];
|
||||
};
|
||||
|
||||
/** Everything a client needs; `conf` is the .conf text. */
|
||||
export function client_config(m, dev) {
|
||||
let p = m.people[dev.person];
|
||||
let srv = p ? m.servers[p.server] : null;
|
||||
if (!srv)
|
||||
return null;
|
||||
let host = endpoint_host(m, srv);
|
||||
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
|
||||
let allowed = allowed_ips(m, srv, p);
|
||||
let dns = client_dns(m, srv, p);
|
||||
let lines = [ '[Interface]' ];
|
||||
push(lines, `PrivateKey = ${dev.private_key || '<private key stays on your device>'}`);
|
||||
push(lines, `Address = ${dev.address}/32`);
|
||||
if (length(dns))
|
||||
push(lines, `DNS = ${join(', ', dns)}`);
|
||||
push(lines, `MTU = ${srv.mtu}`);
|
||||
for (let k in OBF_KEYS)
|
||||
if (srv.obf[k] != null && srv.obf[k] != '')
|
||||
push(lines, `${OBF_CONF[k]} = ${srv.obf[k]}`);
|
||||
push(lines, '', '[Peer]');
|
||||
push(lines, `PublicKey = ${srv.public_key}`);
|
||||
if (dev.preshared_key)
|
||||
push(lines, `PresharedKey = ${dev.preshared_key}`);
|
||||
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
|
||||
push(lines, `Endpoint = ${ep}:${srv.port}`);
|
||||
if (srv.keepalive > 0)
|
||||
push(lines, `PersistentKeepalive = ${srv.keepalive}`);
|
||||
return {
|
||||
name: dev.name,
|
||||
person: p.name,
|
||||
server: srv.name,
|
||||
filename: `${substr(replace(lc(p.id + '-' + dev.name), /[^a-z0-9]+/g, '-'), 0, 15)}.conf`,
|
||||
conf: join('\n', lines) + '\n',
|
||||
has_private_key: dev.private_key != '',
|
||||
amnezia: {
|
||||
host,
|
||||
port: srv.port,
|
||||
mtu: `${srv.mtu}`,
|
||||
dns,
|
||||
allowed_ips: allowed,
|
||||
client_ip: dev.address,
|
||||
client_priv_key: dev.private_key,
|
||||
client_pub_key: dev.public_key,
|
||||
psk_key: dev.preshared_key,
|
||||
server_pub_key: srv.public_key,
|
||||
persistent_keep_alive: `${srv.keepalive}`,
|
||||
obfuscation: srv.obf,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/* ---------- issued configurations ---------- */
|
||||
|
||||
const ISSUED = `${DATA_DIR}/issued.json`;
|
||||
|
||||
function fnv32(str) {
|
||||
let h = 2166136261;
|
||||
for (let i = 0; i < length(str); i++)
|
||||
h = ((h ^ ord(str, i)) * 16777619) & 0xffffffff;
|
||||
return sprintf('%08x', h);
|
||||
}
|
||||
|
||||
/** What a device holds, minus its private key: changes when it must import again. */
|
||||
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/)))) : null;
|
||||
};
|
||||
|
||||
/** Device id → fingerprint of the configuration last shown or downloaded. */
|
||||
export function issued() {
|
||||
return read_json(ISSUED, {});
|
||||
};
|
||||
|
||||
/** Remember that a device was just given its current configuration. */
|
||||
export function mark_issued(m, id) {
|
||||
let fp = config_fingerprint(m, m.devices[id]);
|
||||
if (!fp)
|
||||
return;
|
||||
let l = lock('issued');
|
||||
let all = issued();
|
||||
if (all[id] != fp) {
|
||||
all[id] = fp;
|
||||
for (let k in keys(all))
|
||||
if (!m.devices[k])
|
||||
delete all[k];
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(ISSUED, all, 0o600);
|
||||
}
|
||||
unlock(l);
|
||||
};
|
||||
|
||||
/* ---------- mutations (caller commits) ---------- */
|
||||
|
||||
function fail(msg) {
|
||||
die(msg);
|
||||
}
|
||||
|
||||
/*
|
||||
* Personal codes are three pronounceable words of three syllables each
|
||||
* (kamiro-telosu-bavine): easy to read out or type, ~2^55 combinations, and
|
||||
* guessing is rate-limited by the portal. The code is the whole link path.
|
||||
*/
|
||||
export const WORD_CODE = /^[a-z]{6}-[a-z]{6}-[a-z]{6}$/;
|
||||
const SYL_C = 'bdfgklmnprstvz', SYL_V = 'aeiou';
|
||||
const CODE_AVOID = [ 'suka', 'pido', 'muda', 'zalup', 'dura', 'gavn' ];
|
||||
|
||||
function pick(alphabet) {
|
||||
let n = length(alphabet), lim = 256 - 256 % n;
|
||||
for (;;) {
|
||||
let b = ord(rand_bytes(1), 0);
|
||||
if (b < lim)
|
||||
return substr(alphabet, b % n, 1);
|
||||
}
|
||||
}
|
||||
|
||||
export function new_code() {
|
||||
for (;;) {
|
||||
let words = [];
|
||||
for (let w = 0; w < 3; w++) {
|
||||
let s = '';
|
||||
for (let i = 0; i < 3; i++)
|
||||
s += pick(SYL_C) + pick(SYL_V);
|
||||
push(words, s);
|
||||
}
|
||||
let code = join('-', words);
|
||||
if (!length(filter(CODE_AVOID, (x) => index(code, x) >= 0)))
|
||||
return code;
|
||||
}
|
||||
};
|
||||
|
||||
export function create_person(c, m, a) {
|
||||
if (!valid_name(a.name))
|
||||
fail('Enter a name (up to 48 characters).');
|
||||
// The id is a UCI section name: letters, digits and underscores only (a dash
|
||||
// makes uci drop the section). Repeated names get _2, _3, …
|
||||
let base = replace(a.slug ?? slugify(a.name), /-/g, '_');
|
||||
if (!match(base, /^[a-z0-9_]{1,32}$/))
|
||||
fail('The id may use lowercase letters, digits and underscores.');
|
||||
let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || id == 'settings';
|
||||
let slug = base;
|
||||
for (let n = 2; taken(slug); n++) {
|
||||
if (n > 99)
|
||||
fail(`"${base}" is already taken.`);
|
||||
slug = `${substr(base, 0, 28)}_${n}`;
|
||||
}
|
||||
let srv_id = a.server ?? keys(m.servers)[0];
|
||||
if (!m.servers[srv_id])
|
||||
fail('Set up a server first.');
|
||||
let access = a.access ?? 'internet';
|
||||
if (index(ACCESS, access) < 0)
|
||||
fail('Access must be lan, internet or both.');
|
||||
let limit = toint(a.device_limit, m.settings.default_device_limit);
|
||||
if (limit < 1 || limit > 32)
|
||||
fail('Device limit must be between 1 and 32.');
|
||||
if (a.expires && !valid_date(a.expires))
|
||||
fail('End date must be YYYY-MM-DD.');
|
||||
let quota = num(a.quota_gb, 0);
|
||||
if (quota < 0 || quota > 100000)
|
||||
fail('Monthly data must be a positive number of GB.');
|
||||
|
||||
c.set(CONFIG, slug, 'person');
|
||||
c.set(CONFIG, slug, 'server', srv_id);
|
||||
c.set(CONFIG, slug, 'name', trim(a.name));
|
||||
c.set(CONFIG, slug, 'access', access);
|
||||
c.set(CONFIG, slug, 'device_limit', `${limit}`);
|
||||
c.set(CONFIG, slug, 'code', new_code());
|
||||
c.set(CONFIG, slug, 'created', `${time()}`);
|
||||
if (a.expires)
|
||||
c.set(CONFIG, slug, 'expires', a.expires);
|
||||
if (quota > 0) {
|
||||
c.set(CONFIG, slug, 'quota_gb', `${quota}`);
|
||||
c.set(CONFIG, slug, 'quota_period', a.quota_period == 'total' ? 'total' : 'month');
|
||||
}
|
||||
return slug;
|
||||
};
|
||||
|
||||
/**
|
||||
* Immediate edit of a person from the admin page. Only keys present in `a`
|
||||
* change; '' clears optional values (end date, data limit, hours).
|
||||
*/
|
||||
export function update_person(c, m, id, a) {
|
||||
let p = m.people[id];
|
||||
if (!p)
|
||||
fail('Unknown person.');
|
||||
let set = (k, v) => (v == null || v == '') ? c.delete(CONFIG, id, k) : c.set(CONFIG, id, k, `${v}`);
|
||||
if (a.name != null) {
|
||||
if (!valid_name(a.name))
|
||||
fail('Enter a name (up to 48 characters).');
|
||||
set('name', trim(a.name));
|
||||
}
|
||||
if (a.access != null) {
|
||||
if (index(ACCESS, a.access) < 0)
|
||||
fail('Access must be lan, internet or both.');
|
||||
set('access', a.access);
|
||||
}
|
||||
if (a.device_limit != null) {
|
||||
let n = toint(a.device_limit, 0);
|
||||
if (n < 1 || n > 32)
|
||||
fail('Device limit must be between 1 and 32.');
|
||||
if (n < length(p.devices))
|
||||
fail(`${p.name} already has ${length(p.devices)} devices. Remove one first to lower the limit to ${n}.`);
|
||||
set('device_limit', n);
|
||||
}
|
||||
if (a.expires != null) {
|
||||
if (a.expires != '' && !valid_date(a.expires))
|
||||
fail('End date must be YYYY-MM-DD.');
|
||||
set('expires', a.expires);
|
||||
}
|
||||
if (a.expire_action != null) {
|
||||
if (index([ 'pause', 'notify', 'remove' ], a.expire_action) < 0)
|
||||
fail('Unknown end action.');
|
||||
set('expire_action', a.expire_action == 'pause' ? '' : a.expire_action);
|
||||
}
|
||||
if (a.dns_mode != null) {
|
||||
if (index([ 'device', 'home' ], a.dns_mode) < 0)
|
||||
fail('Unknown DNS choice.');
|
||||
set('dns_mode', a.dns_mode == 'device' ? '' : a.dns_mode);
|
||||
}
|
||||
if (a.expire_warn != null) {
|
||||
let n = toint(a.expire_warn, -1);
|
||||
if (n < 0 || n > 60)
|
||||
fail('Warning must be 0-60 days.');
|
||||
set('expire_warn', n == 3 ? '' : n);
|
||||
}
|
||||
if (a.quota_gb != null) {
|
||||
let q = num(a.quota_gb, -1);
|
||||
if (a.quota_gb != '' && (q < 0 || q > 100000))
|
||||
fail('Data limit must be a positive number of GB.');
|
||||
set('quota_gb', q > 0 ? q : '');
|
||||
}
|
||||
if (a.quota_period != null)
|
||||
set('quota_period', a.quota_period == 'total' ? 'total' : '');
|
||||
if (a.bonus_gb != null) {
|
||||
let b = num(a.bonus_gb, -1);
|
||||
if (b < 0 || b > 100000)
|
||||
fail('Extra data must be a positive number of GB.');
|
||||
set('bonus_gb', b > 0 ? b : '');
|
||||
set('bonus_month', b > 0 ? month_key() : '');
|
||||
}
|
||||
if (a.hours != null) {
|
||||
if (a.hours != '' && !parse_hours(a.hours))
|
||||
fail('Hours must look like 07:00-23:00.');
|
||||
set('hours', a.hours);
|
||||
}
|
||||
if (a.note != null)
|
||||
set('note', substr(trim(a.note), 0, 500));
|
||||
if (type(a.services) == 'array') {
|
||||
for (let sid in a.services)
|
||||
if (!m.services[sid])
|
||||
fail(`Unknown service ${sid}.`);
|
||||
if (length(a.services))
|
||||
c.set(CONFIG, id, 'service', a.services);
|
||||
else
|
||||
c.delete(CONFIG, id, 'service');
|
||||
}
|
||||
if (a.paused != null)
|
||||
set('paused', a.paused ? '1' : '');
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a device for a person. `opts.by` is 'admin' or 'portal'; the portal
|
||||
* enforces the device limit. `opts.public_key` keeps the private key on the
|
||||
* client (browser-generated keys).
|
||||
*/
|
||||
export function create_device(c, m, person_id, name, kind, opts) {
|
||||
opts ??= {};
|
||||
let p = m.people[person_id];
|
||||
if (!p)
|
||||
fail('Unknown person.');
|
||||
let srv = m.servers[p.server];
|
||||
if (!srv)
|
||||
fail('The person has no server.');
|
||||
name = trim(name ?? '');
|
||||
if (!valid_name(name))
|
||||
fail('Enter a device name (up to 48 characters).');
|
||||
if (index(KINDS, kind) < 0)
|
||||
kind = 'other';
|
||||
if (opts.by == 'portal' && length(p.devices) >= p.device_limit)
|
||||
fail(`Device limit reached (${p.device_limit}).`);
|
||||
for (let id in p.devices)
|
||||
if (lc(m.devices[id].name) == lc(name))
|
||||
fail(`"${name}" already exists.`);
|
||||
let addr = alloc_address(m, srv);
|
||||
if (!addr)
|
||||
fail('No free addresses left in the server subnet.');
|
||||
|
||||
let priv = '', pub;
|
||||
if (opts.public_key) {
|
||||
if (!valid_key(opts.public_key))
|
||||
fail('Invalid public key.');
|
||||
pub = opts.public_key;
|
||||
}
|
||||
else {
|
||||
priv = genkey();
|
||||
pub = pubkey(priv);
|
||||
}
|
||||
if (!pub)
|
||||
fail('Key generation failed (is amneziawg-tools installed?).');
|
||||
for (let id, d in m.devices)
|
||||
if (d.public_key == pub)
|
||||
fail('This key is already in use.');
|
||||
|
||||
let id = `d_${rand_hex(4)}`;
|
||||
c.set(CONFIG, id, 'device');
|
||||
c.set(CONFIG, id, 'person', person_id);
|
||||
c.set(CONFIG, id, 'name', name);
|
||||
c.set(CONFIG, id, 'kind', kind);
|
||||
c.set(CONFIG, id, 'address', addr);
|
||||
c.set(CONFIG, id, 'public_key', pub);
|
||||
if (priv)
|
||||
c.set(CONFIG, id, 'private_key', priv);
|
||||
c.set(CONFIG, id, 'preshared_key', genpsk());
|
||||
c.set(CONFIG, id, 'created', `${time()}`);
|
||||
c.set(CONFIG, id, 'created_by', opts.by ?? 'admin');
|
||||
|
||||
// Keep the in-memory model consistent for callers that continue.
|
||||
m.devices[id] = { id, person: person_id, name, kind, address: addr, public_key: pub, private_key: priv,
|
||||
preshared_key: c.get(CONFIG, id, 'preshared_key'), created: time(), created_by: opts.by ?? 'admin', disabled: false };
|
||||
push(p.devices, id);
|
||||
return id;
|
||||
};
|
||||
|
||||
export function rename_device(c, m, id, name) {
|
||||
let d = m.devices[id];
|
||||
if (!d)
|
||||
fail('Unknown device.');
|
||||
name = trim(name ?? '');
|
||||
if (!valid_name(name))
|
||||
fail('Enter a device name (up to 48 characters).');
|
||||
for (let o in m.people[d.person]?.devices ?? [])
|
||||
if (o != id && lc(m.devices[o].name) == lc(name))
|
||||
fail(`"${name}" already exists.`);
|
||||
c.set(CONFIG, id, 'name', name);
|
||||
d.name = name;
|
||||
};
|
||||
|
||||
export function delete_device(c, m, id) {
|
||||
let d = m.devices[id];
|
||||
if (!d)
|
||||
fail('Unknown device.');
|
||||
c.delete(CONFIG, id);
|
||||
let p = m.people[d.person];
|
||||
if (p)
|
||||
p.devices = filter(p.devices, (x) => x != id);
|
||||
delete m.devices[id];
|
||||
};
|
||||
|
||||
export function rotate_device(c, m, id) {
|
||||
let d = m.devices[id];
|
||||
if (!d)
|
||||
fail('Unknown device.');
|
||||
let priv = genkey(), pub = pubkey(priv);
|
||||
if (!pub)
|
||||
fail('Key generation failed.');
|
||||
c.set(CONFIG, id, 'private_key', priv);
|
||||
c.set(CONFIG, id, 'public_key', pub);
|
||||
c.set(CONFIG, id, 'preshared_key', genpsk());
|
||||
};
|
||||
|
||||
export function delete_person(c, m, id) {
|
||||
let p = m.people[id];
|
||||
if (!p)
|
||||
fail('Unknown person.');
|
||||
for (let d in p.devices)
|
||||
c.delete(CONFIG, d);
|
||||
c.delete(CONFIG, id);
|
||||
};
|
||||
|
||||
/** Validate a server definition (as loaded) against the rest of the router. */
|
||||
export function server_errors(m, srv, others_subnets) {
|
||||
let errs = [];
|
||||
if (!match(srv.ifname, /^[a-z][a-z0-9_]{0,11}$/))
|
||||
push(errs, 'Interface name: 1-12 lowercase letters, digits or _.');
|
||||
if (srv.port < 1 || srv.port > 65535)
|
||||
push(errs, 'Port must be 1-65535.');
|
||||
let c = parse_cidr(srv.subnet);
|
||||
if (!c)
|
||||
push(errs, 'Subnet must look like 10.77.0.0/24.');
|
||||
else
|
||||
for (let o in others_subnets ?? []) {
|
||||
let oc = parse_cidr(o);
|
||||
if (oc && cidr_overlaps(c, oc))
|
||||
push(errs, `Subnet overlaps ${o}.`);
|
||||
}
|
||||
if (srv.endpoint != '' && !valid_host(srv.endpoint))
|
||||
push(errs, 'Endpoint must be a hostname or IP address.');
|
||||
push(errs, ...obf_errors(srv.obf));
|
||||
return errs;
|
||||
};
|
||||
|
||||
/** Someone else already forwards this TCP port from outside (a port forward we must not take over). */
|
||||
export function wan_port_taken(port) {
|
||||
let c = cursor();
|
||||
c.load('firewall');
|
||||
let taken = false;
|
||||
c.foreach('firewall', 'redirect', (r) => {
|
||||
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT')
|
||||
return;
|
||||
for (let p in split(`${r.src_dport ?? ''}`, /[ ,]+/)) {
|
||||
let m = match(p, /^(\d+)(?:[-:](\d+))?$/);
|
||||
if (m && +m[1] <= port && port <= +(m[2] ?? m[1]))
|
||||
taken = true;
|
||||
}
|
||||
});
|
||||
return taken;
|
||||
};
|
||||
|
||||
export function wan443_taken() {
|
||||
return wan_port_taken(443);
|
||||
};
|
||||
|
||||
/** Every address the links use, the main one first. */
|
||||
export function portal_hosts(m) {
|
||||
let out = [];
|
||||
for (let h in [ m.settings.portal_host, ...m.settings.portal_alt ])
|
||||
if (h && index(out, h) < 0)
|
||||
push(out, h);
|
||||
return out;
|
||||
};
|
||||
|
||||
/** IP addresses have no certificate: the portal also answers plain HTTP for them. */
|
||||
export function portal_http(m) {
|
||||
return length(filter(portal_hosts(m), (h) => ip2int(h) != null)) > 0;
|
||||
};
|
||||
|
||||
/** Where the portal listens for plain HTTP (next to its HTTPS port). */
|
||||
export function portal_http_port(m) {
|
||||
return m.settings.portal_port + 1;
|
||||
};
|
||||
|
||||
/** The port in plain-HTTP links: 80 when standard ports are on and free. */
|
||||
export function portal_http_public(m) {
|
||||
return m.settings.portal_443 && !wan_port_taken(80) ? 80 : portal_http_port(m);
|
||||
};
|
||||
|
||||
/** The port in personal links: 443 when the portal also answers there. */
|
||||
export function portal_public_port(m) {
|
||||
let s = m.settings;
|
||||
if (s.portal_port == 443 || !s.portal_443 || wan443_taken())
|
||||
return s.portal_port;
|
||||
return 443;
|
||||
};
|
||||
|
||||
/** The link on one address: https for names, plain http for IP addresses. */
|
||||
export function portal_link(m, p, host) {
|
||||
if (!host || !m.servers[p.server] || !match(p.code ?? '', WORD_CODE))
|
||||
return null;
|
||||
if (ip2int(host) != null) {
|
||||
let hp = portal_http_public(m);
|
||||
return `http://${host}${hp == 80 ? '' : `:${hp}`}/${p.code}`;
|
||||
}
|
||||
let pp = portal_public_port(m);
|
||||
return `https://${host}${pp == 443 ? '' : `:${pp}`}/${p.code}`;
|
||||
};
|
||||
|
||||
/** The main link (QR, invite card, Copy link). */
|
||||
export function portal_url(m, p) {
|
||||
return portal_link(m, p, portal_hosts(m)[0]);
|
||||
};
|
||||
|
||||
/** Every link to the same portal, the main one first. */
|
||||
export function portal_urls(m, p) {
|
||||
return filter(map(portal_hosts(m), (h) => portal_link(m, p, h)), (x) => x != null);
|
||||
};
|
||||
@@ -0,0 +1,135 @@
|
||||
// Dawnline — city-level locations for the admin map.
|
||||
//
|
||||
// Client addresses are looked up once with a third-party service (ipwho.is,
|
||||
// ipapi.co as fallback) and cached in DATA_DIR/geo.json. Only the agent
|
||||
// performs lookups, a few per minute at most; the UI reads the cache.
|
||||
|
||||
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR } from 'dawnline.util';
|
||||
|
||||
const CACHE = `${DATA_DIR}/geo.json`;
|
||||
const TTL = 30 * 86400;
|
||||
const RETRY = 86400;
|
||||
|
||||
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
|
||||
const PRIVATE4 = map([ [ '0.0.0.0', 8 ], [ '10.0.0.0', 8 ], [ '100.64.0.0', 10 ], [ '127.0.0.0', 8 ], [ '169.254.0.0', 16 ],
|
||||
[ '172.16.0.0', 12 ], [ '192.168.0.0', 16 ], [ '198.18.0.0', 15 ], [ '224.0.0.0', 3 ] ], (r) => [ ip2int(r[0]), 1 << (32 - r[1]) ]);
|
||||
|
||||
/** True for addresses a geolocation service can say something about. */
|
||||
export function is_public(ip) {
|
||||
if (type(ip) != 'string' || ip == '')
|
||||
return false;
|
||||
let n = ip2int(ip);
|
||||
if (n != null) {
|
||||
for (let r in PRIVATE4)
|
||||
if (n >= r[0] && n < r[0] + r[1])
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
let l = lc(ip);
|
||||
return match(l, /^[0-9a-f:]+$/) != null && !match(l, /^(fe[89ab]|f[cd]|::1$|::$)/);
|
||||
};
|
||||
|
||||
export function load() {
|
||||
return read_json(CACHE, null) ?? { ips: {}, home: null };
|
||||
};
|
||||
|
||||
export function save(cache) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(CACHE, cache, 0o600);
|
||||
};
|
||||
|
||||
function fetch_json(url) {
|
||||
let out = sh_out(`uclient-fetch -q -T 8 -O - ${q(url)}`);
|
||||
if (!out)
|
||||
return null;
|
||||
try {
|
||||
return json(out);
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function lookup_ipwho(ip) {
|
||||
let j = fetch_json(`https://ipwho.is/${ip}?fields=success,ip,latitude,longitude,city,country,country_code,connection`);
|
||||
if (!j || j.success !== true || j.latitude == null)
|
||||
return null;
|
||||
let cn = j.connection ?? {};
|
||||
return { lat: +j.latitude, lon: +j.longitude, city: j.city ?? '', country: j.country ?? '', cc: j.country_code ?? '', ip: j.ip,
|
||||
asn: cn.asn ? +cn.asn : 0, org: cn.isp || cn.org || '' };
|
||||
}
|
||||
|
||||
function lookup_ipapi(ip) {
|
||||
let j = fetch_json(ip ? `https://ipapi.co/${ip}/json/` : 'https://ipapi.co/json/');
|
||||
if (!j || j.error || j.latitude == null)
|
||||
return null;
|
||||
return { lat: +j.latitude, lon: +j.longitude, city: j.city ?? '', country: j.country_name ?? '', cc: j.country_code ?? '', ip: j.ip,
|
||||
asn: +replace(`${j.asn ?? ''}`, /^AS/i, '') || 0, org: j.org ?? '' };
|
||||
}
|
||||
|
||||
/** One lookup with the configured provider and the other as fallback. */
|
||||
export function lookup(provider, ip) {
|
||||
let order = provider == 'ipapi.co' ? [ lookup_ipapi, lookup_ipwho ] : [ lookup_ipwho, lookup_ipapi ];
|
||||
for (let fn in order) {
|
||||
let r = fn(ip ?? '');
|
||||
if (r)
|
||||
return r;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve up to `max` addresses that are missing or stale. Returns true when
|
||||
* the cache changed (the caller saves it).
|
||||
*/
|
||||
export function resolve(settings, cache, ips, max) {
|
||||
let now = time(), changed = false, done = 0;
|
||||
for (let ip in ips) {
|
||||
if (done >= max)
|
||||
break;
|
||||
if (!is_public(ip))
|
||||
continue;
|
||||
let c = cache.ips[ip];
|
||||
if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL)))
|
||||
continue;
|
||||
let r = lookup(settings.geo_provider, ip);
|
||||
done++;
|
||||
changed = true;
|
||||
if (r) {
|
||||
delete r.ip;
|
||||
r.ts = now;
|
||||
cache.ips[ip] = r;
|
||||
}
|
||||
else
|
||||
cache.ips[ip] = { fail: now };
|
||||
}
|
||||
// Keep the cache bounded: drop the oldest entries beyond 500.
|
||||
let all = keys(cache.ips);
|
||||
if (length(all) > 500) {
|
||||
all = sort(all, (a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
|
||||
for (let i = 0; i < length(all) - 500; i++)
|
||||
delete cache.ips[all[i]];
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
|
||||
/** Locate the router itself (the arcs' origin), at most every 6 hours. */
|
||||
export function resolve_home(settings, cache, wan_ip) {
|
||||
let h = cache.home;
|
||||
let now = time();
|
||||
if (h && h.asn != null && now - (h.ts ?? 0) < 6 * 3600 && (!wan_ip || !is_public(wan_ip) || h.wan == wan_ip))
|
||||
return false;
|
||||
// Behind NAT, ask the service for our public address instead.
|
||||
let r = lookup(settings.geo_provider, is_public(wan_ip) ? wan_ip : '');
|
||||
cache.home = r ? { ...r, wan: wan_ip, ts: now } : { ...(h ?? {}), ts: now };
|
||||
return true;
|
||||
};
|
||||
|
||||
export function place(cache, ip) {
|
||||
let c = cache.ips[ip];
|
||||
return (c && !c.fail) ? c : null;
|
||||
};
|
||||
|
||||
export function clear() {
|
||||
save({ ips: {}, home: null });
|
||||
};
|
||||
@@ -0,0 +1,408 @@
|
||||
// Dawnline — live data: peer status from `awg show all dump`, traffic
|
||||
// accounting and the connection/event log.
|
||||
//
|
||||
// Counters live in RUN_DIR (tmpfs) and are flushed to DATA_DIR at most once
|
||||
// an hour, so flash is not worn by the 60-second agent loop.
|
||||
|
||||
import { readfile, stat, unlink } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import {
|
||||
q, sh, sh_out, sh_bg, ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, uniq,
|
||||
RUN_DIR, DATA_DIR
|
||||
} from 'dawnline.util';
|
||||
|
||||
export const ONLINE_WINDOW = 300;
|
||||
const KEEP_DAYS = 62;
|
||||
const KEEP_MONTHS = 24;
|
||||
const KEEP_EVENTS = 2000;
|
||||
|
||||
/* ---------- retention policy ---------- */
|
||||
|
||||
/** Event type → log category (what Settings lets you switch off or clear). */
|
||||
export const CATEGORY = {
|
||||
connect: 'connections', disconnect: 'connections', roam: 'connections',
|
||||
device_added: 'devices', device_removed: 'devices', devices_removed: 'devices',
|
||||
person_added: 'people', person_removed: 'people', person_changed: 'people',
|
||||
paused: 'people', resumed: 'people', paused_all: 'people', resumed_all: 'people',
|
||||
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
|
||||
};
|
||||
export const CATEGORIES = [ 'connections', 'devices', 'people', 'problems' ];
|
||||
|
||||
export function category_of(type) {
|
||||
return CATEGORY[type] ?? 'problems';
|
||||
};
|
||||
|
||||
function int_or(v, d) {
|
||||
return (v == null || v == '' || match(`${v}`, /[^0-9]/)) ? d : +v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log and history retention from /etc/config/dawnline (read fresh, the
|
||||
* portal and rpcd call add_event without a loaded model).
|
||||
* log_keep_days days of activity to keep, 0 = until log_max
|
||||
* log_max newest N events kept
|
||||
* log_category categories that are recorded
|
||||
* log_persist how often the log is saved to flash: 10min | hourly | off
|
||||
* usage_keep_days / usage_keep_months daily / monthly traffic buckets
|
||||
*/
|
||||
export function policy(s) {
|
||||
if (s == null) {
|
||||
let c = cursor();
|
||||
s = c.get_all('dawnline', 'settings') ?? {};
|
||||
}
|
||||
let cats = s.log_category;
|
||||
if (cats == null)
|
||||
cats = (s.log_connections == '0') ? filter(CATEGORIES, (x) => x != 'connections') : CATEGORIES;
|
||||
else if (type(cats) != 'array')
|
||||
cats = split(cats, /[ ,]+/);
|
||||
cats = filter(cats, (x) => index(CATEGORIES, x) >= 0);
|
||||
return {
|
||||
keep_days: int_or(s.log_keep_days, 30),
|
||||
max: min(max(int_or(s.log_max, KEEP_EVENTS), 100), 20000),
|
||||
categories: cats,
|
||||
persist: index([ '10min', 'hourly', 'off' ], s.log_persist) >= 0 ? s.log_persist : 'hourly',
|
||||
usage_days: min(max(int_or(s.usage_keep_days, KEEP_DAYS), 7), 1830),
|
||||
usage_months: min(max(int_or(s.usage_keep_months, KEEP_MONTHS), 1), 120),
|
||||
};
|
||||
};
|
||||
|
||||
/** Drop events older than keep_days and beyond max. */
|
||||
function trim_events(ev, pol) {
|
||||
if (pol.keep_days > 0) {
|
||||
let cut = time() - pol.keep_days * 86400;
|
||||
ev = filter(ev, (e) => (e.ts ?? 0) >= cut);
|
||||
}
|
||||
if (length(ev) > pol.max)
|
||||
ev = slice(ev, length(ev) - pol.max);
|
||||
return ev;
|
||||
}
|
||||
|
||||
/* ---------- awg dump ---------- */
|
||||
|
||||
/**
|
||||
* Parse `awg show all dump`. Returns { ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
|
||||
* Interface lines have many fields (AmneziaWG adds obfuscation values); peer
|
||||
* lines always have 9.
|
||||
*/
|
||||
export function dump() {
|
||||
let r = sh('awg show all dump');
|
||||
let out = { ifaces: {}, peers: {} };
|
||||
if (r.code != 0)
|
||||
return out;
|
||||
for (let line in split(r.out, '\n')) {
|
||||
let f = split(line, '\t');
|
||||
if (length(f) == 9) {
|
||||
let ep = f[3] == '(none)' ? '' : f[3];
|
||||
out.peers[f[1]] = {
|
||||
ifname: f[0],
|
||||
endpoint: ep,
|
||||
handshake: +f[5],
|
||||
rx: +f[6],
|
||||
tx: +f[7],
|
||||
};
|
||||
}
|
||||
else if (length(f) >= 5) {
|
||||
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
export function endpoint_ip(ep) {
|
||||
let m = match(ep ?? '', /^\[?([^\]]+?)\]?:[0-9]+$/);
|
||||
return m ? m[1] : ep;
|
||||
};
|
||||
|
||||
/* ---------- usage ---------- */
|
||||
|
||||
function empty_usage() {
|
||||
return { devices: {}, people: {}, updated: 0, flushed: 0 };
|
||||
}
|
||||
|
||||
export function load_usage() {
|
||||
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
|
||||
};
|
||||
|
||||
function add(bucket, key, rx, tx) {
|
||||
let v = bucket[key] ?? [ 0, 0 ];
|
||||
bucket[key] = [ v[0] + rx, v[1] + tx ];
|
||||
}
|
||||
|
||||
function prune(obj, keep) {
|
||||
let ks = sort(keys(obj));
|
||||
for (let i = 0; i < length(ks) - keep; i++)
|
||||
delete obj[ks[i]];
|
||||
}
|
||||
|
||||
function account(rec, rx, tx, ts) {
|
||||
rec.total = [ (rec.total?.[0] ?? 0) + rx, (rec.total?.[1] ?? 0) + tx ];
|
||||
rec.months ??= {};
|
||||
rec.days ??= {};
|
||||
add(rec.months, month_key(ts), rx, tx);
|
||||
add(rec.days, day_key(ts), rx, tx);
|
||||
}
|
||||
|
||||
/** Apply the traffic history retention to every record. */
|
||||
export function prune_usage(usage, pol) {
|
||||
pol ??= policy();
|
||||
for (let grp in [ usage.devices, usage.people ])
|
||||
for (let id, rec in grp) {
|
||||
if (rec.months)
|
||||
prune(rec.months, pol.usage_months);
|
||||
if (rec.days)
|
||||
prune(rec.days, pol.usage_days);
|
||||
}
|
||||
};
|
||||
|
||||
/** Forget a record's traffic history; kernel counters (raw) and the last handshake stay. */
|
||||
function wipe(rec) {
|
||||
if (!rec)
|
||||
return;
|
||||
delete rec.total;
|
||||
delete rec.months;
|
||||
delete rec.days;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset traffic history. scope: all | person | device. A person reset also
|
||||
* clears their devices and restarts their data limit; a device reset leaves
|
||||
* the person's totals (and so their limit) alone.
|
||||
*/
|
||||
export function reset_usage(usage, m, scope, id) {
|
||||
if (scope == 'all') {
|
||||
for (let k, rec in usage.devices)
|
||||
wipe(rec);
|
||||
for (let k, rec in usage.people)
|
||||
wipe(rec);
|
||||
}
|
||||
else if (scope == 'person') {
|
||||
wipe(usage.people[id]);
|
||||
for (let did in m.people[id]?.devices ?? [])
|
||||
wipe(usage.devices[did]);
|
||||
}
|
||||
else if (scope == 'device') {
|
||||
wipe(usage.devices[id]);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fold the current kernel counters into `usage`. Counters restart from zero
|
||||
* when a peer is re-added or the interface restarts; a drop is treated as a
|
||||
* reset. Returns the per-device live view keyed by device id.
|
||||
*/
|
||||
export function collect(m, usage, d) {
|
||||
d ??= dump();
|
||||
let ts = time();
|
||||
let live = {};
|
||||
let by_key = {};
|
||||
for (let id, dev in m.devices)
|
||||
by_key[dev.public_key] = id;
|
||||
|
||||
for (let id, dev in m.devices) {
|
||||
let rec = usage.devices[id] ??= { raw: [ 0, 0 ] };
|
||||
let peer = d.peers[dev.public_key];
|
||||
if (!peer) {
|
||||
rec.raw = [ 0, 0 ];
|
||||
live[id] = { online: false, handshake: rec.handshake ?? 0, endpoint: rec.endpoint ?? '', present: false };
|
||||
continue;
|
||||
}
|
||||
let raw = rec.raw ?? [ 0, 0 ];
|
||||
let drx = peer.rx >= raw[0] ? peer.rx - raw[0] : peer.rx;
|
||||
let dtx = peer.tx >= raw[1] ? peer.tx - raw[1] : peer.tx;
|
||||
rec.raw = [ peer.rx, peer.tx ];
|
||||
if (drx > 0 || dtx > 0) {
|
||||
account(rec, drx, dtx, ts);
|
||||
let p = usage.people[dev.person] ??= {};
|
||||
account(p, drx, dtx, ts);
|
||||
}
|
||||
if (peer.handshake > 0) {
|
||||
rec.handshake = peer.handshake;
|
||||
rec.endpoint = endpoint_ip(peer.endpoint);
|
||||
// Recent client addresses (for the map): ip → last seen, newest 8.
|
||||
rec.ips ??= {};
|
||||
if (rec.endpoint)
|
||||
rec.ips[rec.endpoint] = peer.handshake;
|
||||
let ips = sort(keys(rec.ips), (x, y) => rec.ips[y] - rec.ips[x]);
|
||||
for (let i = 8; i < length(ips); i++)
|
||||
delete rec.ips[ips[i]];
|
||||
}
|
||||
live[id] = {
|
||||
online: peer.handshake > 0 && ts - peer.handshake < ONLINE_WINDOW,
|
||||
handshake: peer.handshake || rec.handshake || 0,
|
||||
endpoint: endpoint_ip(peer.endpoint) || rec.endpoint || '',
|
||||
present: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Forget counters of devices that no longer exist (their bytes stay in
|
||||
// the person's totals).
|
||||
for (let id in keys(usage.devices))
|
||||
if (!m.devices[id])
|
||||
delete usage.devices[id];
|
||||
|
||||
prune_usage(usage, policy(m.settings.retention));
|
||||
usage.updated = ts;
|
||||
return live;
|
||||
};
|
||||
|
||||
export function save_usage(usage, persist) {
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/usage.json`, usage, 0o600);
|
||||
if (persist) {
|
||||
usage.flushed = time();
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(`${DATA_DIR}/usage.json`, usage, 0o600);
|
||||
}
|
||||
};
|
||||
|
||||
/** Sum of [rx, tx] over the last `days` days for a usage record. */
|
||||
export function recent(rec, days) {
|
||||
let out = [ 0, 0 ];
|
||||
let ts = time();
|
||||
for (let i = 0; i < days; i++) {
|
||||
let v = rec?.days?.[day_key(ts - i * 86400)];
|
||||
if (v) {
|
||||
out[0] += v[0];
|
||||
out[1] += v[1];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
export function month(rec) {
|
||||
return rec?.months?.[month_key()] ?? [ 0, 0 ];
|
||||
};
|
||||
|
||||
/** Daily series for the last `days` days: [{ day, rx, tx }]. */
|
||||
export function series(recs, days) {
|
||||
let out = [];
|
||||
let ts = time();
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
let k = day_key(ts - i * 86400);
|
||||
let rx = 0, tx = 0;
|
||||
for (let r in recs) {
|
||||
let v = r?.days?.[k];
|
||||
if (v) {
|
||||
rx += v[0];
|
||||
tx += v[1];
|
||||
}
|
||||
}
|
||||
push(out, { day: k, rx, tx });
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/* ---------- events ---------- */
|
||||
|
||||
export function load_events() {
|
||||
return read_json(`${RUN_DIR}/events.json`, null) ?? read_json(`${DATA_DIR}/events.json`, []);
|
||||
};
|
||||
|
||||
export function add_events(list, pol) {
|
||||
pol ??= policy();
|
||||
list = filter(list ?? [], (e) => index(pol.categories, category_of(e.type)) >= 0);
|
||||
if (!length(list))
|
||||
return;
|
||||
let l = lock('events');
|
||||
let ev = load_events();
|
||||
let ts = time();
|
||||
for (let e in list) {
|
||||
e.ts ??= ts;
|
||||
push(ev, e);
|
||||
}
|
||||
ev = trim_events(ev, pol);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/events.json`, ev, 0o600);
|
||||
unlock(l);
|
||||
};
|
||||
|
||||
export function add_event(e) {
|
||||
add_events([ e ]);
|
||||
};
|
||||
|
||||
/** Like add_event, but folds into the previous event of the same kind and person within `window` s. */
|
||||
export function add_event_merged(e, window) {
|
||||
let pol = policy();
|
||||
if (index(pol.categories, category_of(e.type)) < 0)
|
||||
return;
|
||||
let l = lock('events');
|
||||
let ev = load_events();
|
||||
let last = ev[length(ev) - 1];
|
||||
let ts = time();
|
||||
if (last && last.type == e.type && last.person == e.person && ts - last.ts < (window ?? 120)) {
|
||||
let parts = uniq([ ...split(last.detail ?? '', ', '), ...split(e.detail ?? '', ', ') ]);
|
||||
last.detail = join(', ', filter(parts, (x) => x != ''));
|
||||
last.ts = ts;
|
||||
}
|
||||
else {
|
||||
e.ts = ts;
|
||||
push(ev, e);
|
||||
}
|
||||
ev = trim_events(ev, pol);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/events.json`, ev, 0o600);
|
||||
unlock(l);
|
||||
};
|
||||
|
||||
/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */
|
||||
export function persist_events(pol) {
|
||||
pol ??= policy();
|
||||
if (pol.persist == 'off') {
|
||||
if (stat(`${DATA_DIR}/events.json`))
|
||||
unlink(`${DATA_DIR}/events.json`);
|
||||
return;
|
||||
}
|
||||
let ev = read_json(`${RUN_DIR}/events.json`, null);
|
||||
if (ev != null) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(`${DATA_DIR}/events.json`, trim_events(ev, pol), 0o600);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove events matching every given filter (person, device, category,
|
||||
* older than `before` ts); no filters clears the whole log. Edits both the
|
||||
* live copy and the one on flash. Returns how many were removed.
|
||||
*/
|
||||
export function clear_events(f) {
|
||||
f ??= {};
|
||||
let hit = (e) =>
|
||||
(!f.person || e.person == f.person) &&
|
||||
(!f.device || e.device == f.device) &&
|
||||
(!f.category || category_of(e.type) == f.category) &&
|
||||
(!f.before || (e.ts ?? 0) < f.before);
|
||||
let l = lock('events');
|
||||
let removed = 0;
|
||||
for (let path in [ `${RUN_DIR}/events.json`, `${DATA_DIR}/events.json` ]) {
|
||||
let ev = read_json(path, null);
|
||||
if (ev == null)
|
||||
continue;
|
||||
let keep = filter(ev, (e) => !hit(e));
|
||||
if (path == `${RUN_DIR}/events.json` || removed == 0)
|
||||
removed = max(removed, length(ev) - length(keep));
|
||||
write_json(path, keep, 0o600);
|
||||
}
|
||||
unlock(l);
|
||||
return removed;
|
||||
};
|
||||
|
||||
/* ---------- health ---------- */
|
||||
|
||||
export function iface_status(ifname) {
|
||||
if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/))
|
||||
return null;
|
||||
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
|
||||
if (!s)
|
||||
return null;
|
||||
try {
|
||||
return json(s);
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export function uptime() {
|
||||
let s = readfile('/proc/uptime');
|
||||
return s ? int(+split(s, ' ')[0]) : 0;
|
||||
};
|
||||
@@ -0,0 +1,555 @@
|
||||
// Dawnline — "like a home device": tunnel clients' internet traffic enters
|
||||
// the router from the LAN, so whatever handles LAN traffic there (proxies,
|
||||
// DPI bypass, DNS filters, fw4's lan zone, ...) handles it too, without
|
||||
// Dawnline knowing about any of them.
|
||||
//
|
||||
// dawn0 ──policy route──▶ dlx0 ═veth═ dlx1 ┐ netns "dawnline" ┌ dll1 ═veth═ dll0 ── br-lan
|
||||
// └── 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.
|
||||
// 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.
|
||||
//
|
||||
// Separately, people with Home-only access get a plain resolver (real
|
||||
// addresses from the WAN's DNS, home names from the LAN DNS): their internet
|
||||
// does not use the tunnel, so fake-IP answers would break it. While the netns
|
||||
// exists the resolver runs inside it and sends its upstream queries back out
|
||||
// through the transit link as forwarded traffic — not as the router's own
|
||||
// traffic and not from the LAN — so tools that capture either leave it alone.
|
||||
//
|
||||
// Everything is derived from the router at run time; nothing assumes a
|
||||
// particular subnet or tool. If the LAN is not a bridge or setup fails, the
|
||||
// direct path stays and status() says why.
|
||||
|
||||
import { readfile, writefile, readlink, stat, unlink } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { sh, sh_out, q, ip2int, int2ip, ensure_dir, read_json, write_json, uniq, RUN_DIR } from 'dawnline.util';
|
||||
import * as net from 'dawnline.net';
|
||||
|
||||
export const NS = 'dawnline';
|
||||
const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.lan, LAN_NS = 'dll1';
|
||||
const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
|
||||
const RESOLVER_PORT = 5354;
|
||||
export const RESOLVER_CONF = '/var/etc/dawnline-dns.conf';
|
||||
const RESOLVER_RESOLV = '/var/etc/dawnline-dns.resolv';
|
||||
const RESOLVER_PID = '/var/run/dawnline-dns.pid';
|
||||
const STATE = `${RUN_DIR}/loop.json`;
|
||||
const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ];
|
||||
|
||||
function log(msg) {
|
||||
system(`logger -t dawnline ${q(msg)}`);
|
||||
}
|
||||
|
||||
function run(cmds) {
|
||||
let errs = [];
|
||||
for (let c in cmds) {
|
||||
let r = sh(c);
|
||||
if (r.code != 0)
|
||||
push(errs, `${c}: ${trim(r.out)}`);
|
||||
}
|
||||
return errs;
|
||||
}
|
||||
|
||||
function exists(dev) {
|
||||
return stat(`/sys/class/net/${dev}`) != null;
|
||||
}
|
||||
|
||||
function cidr_of(a) {
|
||||
let m = match(a ?? '', /^([0-9.]+)\/([0-9]+)$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = +m[2];
|
||||
if (ip == null || prefix < 8 || prefix > 30)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
return { ip, prefix, size, net: ip - ip % size };
|
||||
}
|
||||
|
||||
/* ---------- facts about the LAN ---------- */
|
||||
|
||||
/** DHCP pool, static leases and the DNS handed to LAN clients, for one netifd interface. */
|
||||
function dhcp_facts(logical, lan) {
|
||||
let c = cursor();
|
||||
c.load('dhcp');
|
||||
let pool = null, dns = null, statics = [];
|
||||
c.foreach('dhcp', 'dhcp', (s) => {
|
||||
if (s.interface != logical || s.ignore == '1')
|
||||
return;
|
||||
let start = +(s.start ?? 100), limit = +(s.limit ?? 150);
|
||||
pool = [ lan.net + start, lan.net + start + limit - 1 ];
|
||||
let opts = type(s.dhcp_option) == 'array' ? s.dhcp_option : (s.dhcp_option ? [ s.dhcp_option ] : []);
|
||||
for (let o in opts) {
|
||||
let m = match(o, /^(option:dns-server|6),([0-9.]+)/);
|
||||
if (m && !dns)
|
||||
dns = m[2];
|
||||
}
|
||||
});
|
||||
c.foreach('dhcp', 'host', (s) => {
|
||||
let ip = ip2int(s.ip ?? '');
|
||||
if (ip != null)
|
||||
push(statics, ip);
|
||||
});
|
||||
return { pool, dns, statics };
|
||||
}
|
||||
|
||||
/** Addresses other devices are using right now (neighbour table + leases). */
|
||||
function used_addresses(dev) {
|
||||
let used = {};
|
||||
try {
|
||||
for (let n in json(sh_out(`ip -j -4 neigh show dev ${q(dev)}`) || '[]') ?? [])
|
||||
if (n.dst && !(index(n.state ?? [], 'FAILED') >= 0 || index(n.state ?? [], 'INCOMPLETE') >= 0))
|
||||
used[n.dst] = n.lladdr ?? true;
|
||||
}
|
||||
catch (e) {}
|
||||
for (let l in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) {
|
||||
let f = split(l, ' ');
|
||||
if (length(f) >= 3)
|
||||
used[f[2]] = f[1];
|
||||
}
|
||||
return used;
|
||||
}
|
||||
|
||||
function our_mac() {
|
||||
return sh_out(`ip -n ${NS} -j link show ${LAN_NS} 2>/dev/null | jsonfilter -e '@[0].address'`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
function pick_address(lan, facts, saved, dev) {
|
||||
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))
|
||||
return int2ip(sv);
|
||||
for (let ip = lan.net + lan.size - 2; ip > lan.net; ip--) {
|
||||
if (taken(ip))
|
||||
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);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A /30 in 169.254.0.0/16 that no route or address on the router overlaps. */
|
||||
function pick_transit(saved) {
|
||||
let busy = [];
|
||||
for (let dev, d in net.snapshot().devices)
|
||||
for (let n in [ ...d.nets, ...d.addrs ])
|
||||
push(busy, n);
|
||||
let free = (base) => {
|
||||
for (let b in busy) {
|
||||
let c = match(b, /^([0-9.]+)(\/([0-9]+))?$/);
|
||||
if (!c)
|
||||
continue;
|
||||
let ip = ip2int(c[1]), size = 1 << (32 - (c[3] != null ? +c[3] : 32));
|
||||
let bn = ip - ip % size;
|
||||
if (base < bn + size && bn < base + 4)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
let sv = ip2int(saved ?? '');
|
||||
if (sv != null && free(sv))
|
||||
return sv;
|
||||
for (let k = 77; k < 77 + 256; k++) {
|
||||
let base = ip2int(`169.254.${k % 256}.0`);
|
||||
if (free(base))
|
||||
return base;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A routing table nobody else uses (ours holds a single route via the transit link). */
|
||||
function pick_table(saved) {
|
||||
let free = (t) => {
|
||||
let r = sh_out(`ip -4 route show table ${t}`) ?? '';
|
||||
return r == '' || (length(split(r, '\n')) == 1 && index(r, ` dev ${TX_ROOT}`) >= 0);
|
||||
};
|
||||
if (saved && free(saved))
|
||||
return saved;
|
||||
for (let t = 2077; t < 2177; t++)
|
||||
if (free(t))
|
||||
return t;
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ---------- plan ---------- */
|
||||
|
||||
function settings() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
return c.get_all('dawnline', 'settings') ?? {};
|
||||
}
|
||||
|
||||
/** Servers that want "like a home device" (default on). */
|
||||
function wanted(m) {
|
||||
return filter(values(m.servers), (s) => s.private_key && s.enabled && s.lan_like);
|
||||
}
|
||||
|
||||
/**
|
||||
* What should exist, or { error } when it cannot. Pure apart from reading
|
||||
* router state (and one ping per candidate address).
|
||||
*/
|
||||
export function plan(m) {
|
||||
let srvs = wanted(m);
|
||||
if (!length(srvs))
|
||||
return { off: true };
|
||||
let snap = net.snapshot();
|
||||
let dev = snap.lan;
|
||||
let d = snap.devices[dev];
|
||||
if (!dev || !d)
|
||||
return { error: 'No LAN detected.' };
|
||||
if (d.kind != 'bridge')
|
||||
return { error: `${dev} is not a bridge, so Dawnline cannot join the LAN as a device.` };
|
||||
let lan = cidr_of(d.addrs[0]);
|
||||
if (!lan)
|
||||
return { error: `${dev} has no IPv4 address.` };
|
||||
let facts = dhcp_facts(d.logical, lan);
|
||||
let st = settings();
|
||||
let addr = pick_address(lan, facts, st.lan_address, dev);
|
||||
if (!addr)
|
||||
return { error: `No free address on ${int2ip(lan.net)}/${lan.prefix}.` };
|
||||
let last = read_json(STATE, {});
|
||||
let tx = pick_transit(last?.transit);
|
||||
if (tx == null)
|
||||
return { error: 'No free link-local range for the internal link.' };
|
||||
let table = pick_table(last?.plan?.table);
|
||||
if (table == null)
|
||||
return { error: 'No free routing table.' };
|
||||
let servers = [];
|
||||
for (let srv in srvs) {
|
||||
let sn = net.server_net(srv, snap);
|
||||
push(servers, { ifname: srv.ifname, subnet: srv.subnet, direct: net.collapse([ srv.subnet, ...sn.nets ]) });
|
||||
}
|
||||
return {
|
||||
dev,
|
||||
gateway: int2ip(lan.ip),
|
||||
address: addr,
|
||||
prefix: lan.prefix,
|
||||
dns: facts.dns ?? int2ip(lan.ip),
|
||||
transit: tx,
|
||||
tx_root: int2ip(tx + 1),
|
||||
tx_ns: int2ip(tx + 2),
|
||||
table,
|
||||
servers,
|
||||
};
|
||||
};
|
||||
|
||||
/* ---------- apply ---------- */
|
||||
|
||||
function ns_rules(p) {
|
||||
return `table inet dawnline
|
||||
delete table inet dawnline
|
||||
table inet dawnline {
|
||||
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
|
||||
}
|
||||
chain nat_post {
|
||||
type nat hook postrouting priority srcnat; policy accept;
|
||||
oifname "${LAN_NS}" masquerade
|
||||
}
|
||||
chain filter_forward {
|
||||
type filter hook forward priority filter; policy drop;
|
||||
ct state established,related accept
|
||||
iifname "${TX_NS}" oifname "${LAN_NS}" accept
|
||||
}
|
||||
chain filter_input {
|
||||
type filter hook input priority filter; policy drop;
|
||||
ct state established,related accept
|
||||
iifname "lo" accept
|
||||
icmp type echo-request accept
|
||||
iifname "${TX_NS}" meta l4proto { tcp, udp } th dport 53 accept
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
/** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */
|
||||
function current_rules(ifnames) {
|
||||
let out = [];
|
||||
try {
|
||||
for (let r in json(sh_out('ip -j -4 rule show') || '[]') ?? [])
|
||||
if (r.priority >= 5200 && r.priority < 5300 && r.iif && index(ifnames, r.iif) >= 0)
|
||||
push(out, r);
|
||||
}
|
||||
catch (e) {}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
function rule_key(pref, iif, to, table) {
|
||||
return `${pref} ${iif} ${to ?? 'all'} ${table}`;
|
||||
}
|
||||
|
||||
function sync_rules(p, ifnames) {
|
||||
let want = [];
|
||||
for (let s in p?.servers ?? []) {
|
||||
push(want, [ PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}` ]);
|
||||
for (let n in s.direct)
|
||||
push(want, [ PREF_MAIN, s.ifname, n, 'main' ]);
|
||||
push(want, [ PREF_LOOP, s.ifname, null, `${p.table}` ]);
|
||||
}
|
||||
let have = map(current_rules(ifnames), (r) => rule_key(r.priority, r.iif, r.dst ? `${r.dst}${r.dstlen != null ? '/' + r.dstlen : ''}` : null, r.table));
|
||||
let wantk = map(want, (w) => rule_key(w[0], w[1], w[2] ?? null, w[3]));
|
||||
if (join('\n', sort(have)) == join('\n', sort(wantk)))
|
||||
return [];
|
||||
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}`);
|
||||
for (let w in want)
|
||||
push(cmds, `ip -4 rule add priority ${w[0]} iif ${q(w[1])}${w[2] ? ' to ' + w[2] : ''} lookup ${w[3]}`);
|
||||
return cmds;
|
||||
}
|
||||
|
||||
function tunnel_ifnames() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let out = [];
|
||||
c.foreach('dawnline', 'server', (s) => push(out, s.ifname ?? s['.name']));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Remove the netns, links and rules. */
|
||||
export function remove(ifnames) {
|
||||
ifnames ??= tunnel_ifnames();
|
||||
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 (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}`);
|
||||
run(cmds);
|
||||
unlink(STATE);
|
||||
};
|
||||
|
||||
/**
|
||||
* Bring the loop to the plan. Cheap when nothing changed: compares with the
|
||||
* last applied plan and only checks that links, bridge port and rules exist.
|
||||
*/
|
||||
export function ensure(m, force) {
|
||||
let ifnames = map(values(m.servers), (s) => s.ifname);
|
||||
let p = plan(m);
|
||||
if (p.off || p.error) {
|
||||
if (stat(STATE) || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames)))
|
||||
remove(ifnames);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(STATE, { error: p.error, off: !!p.off }, 0o644);
|
||||
if (p.error)
|
||||
log(`like-home routing off: ${p.error}`);
|
||||
return p;
|
||||
}
|
||||
let last = read_json(STATE, {});
|
||||
let same = !force && last.applied && sprintf('%J', last.plan) == sprintf('%J', p);
|
||||
let healthy = exists(TX_ROOT) && exists(LAN_ROOT) && stat(`/var/run/netns/${NS}`) &&
|
||||
replace(readlink(`/sys/class/net/${LAN_ROOT}/master`) ?? '', /^.*\//, '') == p.dev;
|
||||
let rules = sync_rules(p, ifnames);
|
||||
if (same && healthy && !length(rules))
|
||||
return p;
|
||||
|
||||
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}`);
|
||||
let errs = run(cmds);
|
||||
cmds = [
|
||||
`ip addr flush dev ${TX_ROOT}`,
|
||||
`ip addr add ${p.tx_root}/30 dev ${TX_ROOT}`,
|
||||
`ip link set ${TX_ROOT} up`,
|
||||
`ip link set ${LAN_ROOT} master ${q(p.dev)}`,
|
||||
`ip link set ${LAN_ROOT} up`,
|
||||
`ip -n ${NS} link set lo up`,
|
||||
`ip -n ${NS} addr flush dev ${TX_NS}`,
|
||||
`ip -n ${NS} addr add ${p.tx_ns}/30 dev ${TX_NS}`,
|
||||
`ip -n ${NS} link set ${TX_NS} up`,
|
||||
`ip -n ${NS} addr flush dev ${LAN_NS}`,
|
||||
`ip -n ${NS} addr add ${p.address}/${p.prefix} dev ${LAN_NS}`,
|
||||
`ip -n ${NS} link set ${LAN_NS} up`,
|
||||
`ip -n ${NS} route replace default via ${p.gateway} dev ${LAN_NS}`,
|
||||
// The resolver's own queries (from the transit address) go back out the transit link.
|
||||
`ip -n ${NS} route replace default via ${p.tx_root} dev ${TX_NS} table 100`,
|
||||
`ip -n ${NS} rule del from ${p.tx_ns} lookup 100 2>/dev/null; ip -n ${NS} rule add from ${p.tx_ns} lookup 100`,
|
||||
`ip netns exec ${NS} sh -c 'echo 1 > /proc/sys/net/ipv4/ip_forward; echo 0 > /proc/sys/net/ipv4/conf/all/rp_filter; echo 0 > /proc/sys/net/ipv4/conf/default/rp_filter'`,
|
||||
`ip -4 route replace default via ${p.tx_ns} dev ${TX_ROOT} table ${p.table}`,
|
||||
];
|
||||
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`);
|
||||
push(errs, ...run(cmds));
|
||||
push(errs, ...run(sync_rules(p, ifnames)));
|
||||
|
||||
if (length(errs)) {
|
||||
log(`like-home routing failed, using the direct path: ${errs[0]}`);
|
||||
remove(ifnames);
|
||||
write_json(STATE, { error: `Setup failed: ${errs[0]}` }, 0o644);
|
||||
return { error: errs[0] };
|
||||
}
|
||||
// Keep the chosen LAN address stable across restarts.
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
if (c.get('dawnline', 'settings', 'lan_address') != p.address) {
|
||||
c.set('dawnline', 'settings', 'settings');
|
||||
c.set('dawnline', 'settings', 'lan_address', p.address);
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
}
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
|
||||
log(`like-home routing: ${p.dev} as ${p.address}`);
|
||||
return p;
|
||||
};
|
||||
|
||||
/** Last applied state for views and health checks. */
|
||||
export function status() {
|
||||
let s = read_json(STATE, {});
|
||||
if (s.plan)
|
||||
return {
|
||||
active: exists(TX_ROOT) && exists(LAN_ROOT),
|
||||
dev: s.plan.dev, address: s.plan.address, dns: s.plan.dns, gateway: s.plan.gateway, transit: s.plan.tx_ns,
|
||||
bridged: replace(readlink(`/sys/class/net/${LAN_ROOT}/master`) ?? '', /^.*\//, '') == s.plan.dev,
|
||||
};
|
||||
return { active: false, off: !!s.off, error: s.error };
|
||||
};
|
||||
|
||||
/** The DNS address tunnel clients should use while the loop is up. */
|
||||
export function client_dns() {
|
||||
let s = status();
|
||||
return s.active ? s.address : null;
|
||||
};
|
||||
|
||||
/* ---------- plain resolver for Home-only clients ---------- */
|
||||
|
||||
function wan_dns() {
|
||||
let out = [];
|
||||
let snap = net.snapshot();
|
||||
let wan = snap.devices[snap.wan]?.logical;
|
||||
for (let name in uniq([ wan, 'wan', 'wan6' ])) {
|
||||
if (!name)
|
||||
continue;
|
||||
try {
|
||||
let st = json(sh_out(`ubus call network.interface.${name} status 2>/dev/null`) || 'null');
|
||||
for (let a in st?.['dns-server'] ?? [])
|
||||
if (match(a, /^[0-9.]+$/))
|
||||
push(out, a);
|
||||
}
|
||||
catch (e) {}
|
||||
}
|
||||
return length(out) ? uniq(out) : FALLBACK_DNS;
|
||||
}
|
||||
|
||||
/** Local domain of the LAN DNS (dnsmasq `domain`, else the Dawnline hostname domain). */
|
||||
function lan_domain(m) {
|
||||
let c = cursor();
|
||||
c.load('dhcp');
|
||||
let d = null;
|
||||
c.foreach('dhcp', 'dnsmasq', (s) => { d ??= s.domain; });
|
||||
return uniq(filter([ d, m.settings.domain ], (x) => x));
|
||||
}
|
||||
|
||||
/** The DNS your LAN gets from DHCP (option 6), else the router on the LAN. */
|
||||
export function lan_dns() {
|
||||
let st = status();
|
||||
if (st.dns)
|
||||
return st.dns;
|
||||
let snap = net.snapshot();
|
||||
let d = snap.devices[snap.lan];
|
||||
let a = d?.addrs?.[0];
|
||||
return a ? (dhcp_facts(d.logical, cidr_of(a))?.dns ?? split(a, '/')[0]) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Where Home-only clients' DNS goes: inside the netns while it is up
|
||||
* (`ns`: transit address, port 53), otherwise on the tunnel address (`root`).
|
||||
*/
|
||||
export function resolver_target() {
|
||||
let st = status();
|
||||
return st.active && st.transit ? { mode: 'ns', address: st.transit, port: 53 } : { mode: 'root', port: RESOLVER_PORT };
|
||||
};
|
||||
|
||||
/**
|
||||
* Write the resolver config; returns true when it changed (the running
|
||||
* instance is then restarted by procd's respawn after a kill). The first line
|
||||
* tells /usr/libexec/dawnline/resolver where to run it.
|
||||
*/
|
||||
export function sync_resolver(m) {
|
||||
ensure_dir('/var/etc');
|
||||
let ifs = map(filter(values(m.servers), (s) => s.private_key), (s) => s.ifname);
|
||||
let target = resolver_target();
|
||||
let lan = lan_dns();
|
||||
let lines = [
|
||||
`# mode=${target.mode}`,
|
||||
'# Generated by Dawnline: plain DNS for Home-only tunnel clients.',
|
||||
`port=${target.port}`,
|
||||
'no-hosts',
|
||||
'bogus-priv',
|
||||
'cache-size=1000',
|
||||
`pid-file=${RESOLVER_PID}`,
|
||||
'user=dnsmasq',
|
||||
'group=dnsmasq',
|
||||
];
|
||||
if (target.mode == 'ns') {
|
||||
push(lines, `listen-address=${target.address}`, 'bind-interfaces', 'no-resolv');
|
||||
// Upstream from the transit address: forwarded through the router to the WAN.
|
||||
for (let a in wan_dns())
|
||||
push(lines, `server=${a}@${target.address}`);
|
||||
}
|
||||
else {
|
||||
push(lines, 'bind-dynamic', ...map(ifs, (i) => `interface=${i}`), `resolv-file=${RESOLVER_RESOLV}`);
|
||||
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
|
||||
if ((readfile(RESOLVER_RESOLV) ?? '') != resolv) {
|
||||
writefile(RESOLVER_RESOLV, resolv);
|
||||
system(`chmod 644 ${RESOLVER_RESOLV}`);
|
||||
}
|
||||
}
|
||||
if (lan)
|
||||
for (let d in lan_domain(m))
|
||||
push(lines, `server=/${d}/${lan}`);
|
||||
let conf = join('\n', lines) + '\n';
|
||||
if ((readfile(RESOLVER_CONF) ?? '') == conf)
|
||||
return false;
|
||||
writefile(RESOLVER_CONF, conf);
|
||||
system(`chmod 644 ${RESOLVER_CONF}`);
|
||||
let pid = trim(readfile(RESOLVER_PID) ?? '');
|
||||
if (match(pid, /^[0-9]+$/))
|
||||
system(`kill ${pid} 2>/dev/null`);
|
||||
return true;
|
||||
};
|
||||
|
||||
/** True when the resolver process is alive. */
|
||||
export function resolver_running() {
|
||||
let pid = trim(readfile(RESOLVER_PID) ?? '');
|
||||
return match(pid, /^[0-9]+$/) != null && stat(`/proc/${pid}`) != null;
|
||||
};
|
||||
|
||||
export const RESOLVER = { port: RESOLVER_PORT, conf: RESOLVER_CONF };
|
||||
@@ -0,0 +1,268 @@
|
||||
// Dawnline — the router's network interfaces: what exists, which one is the
|
||||
// WAN, and which ones make up a server's "home network".
|
||||
//
|
||||
// Per server (uci `server` section):
|
||||
// auto_wan 1 = use the interface of the default route (detected_wan
|
||||
// is kept as a fallback while the WAN is down)
|
||||
// wan_device the WAN interface when auto_wan is off
|
||||
// auto_lan 1 = include the detected LAN (detected_lan as fallback)
|
||||
// lan_device extra interfaces that count as the home network (list)
|
||||
//
|
||||
// Home access is enforced by destination: the networks routed out of the
|
||||
// chosen interfaces form the nft `lan_nets` set, and the tunnel's firewall
|
||||
// zone gets a forwarding to each of their zones.
|
||||
|
||||
import { readfile, readlink, lsdir, stat } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { sh_out, ip2int, int2ip, uniq } from 'dawnline.util';
|
||||
|
||||
const SYS = '/sys/class/net';
|
||||
/** Links Dawnline creates itself (dawnline.loop); never offered as interfaces. */
|
||||
export const INTERNAL = { transit: 'dlx0', lan: 'dll0' };
|
||||
const VPN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc', 'pptp', 'l2tp', 'gre', 'gretap', 'vti', 'xfrm' ];
|
||||
// Kernel placeholder devices that never carry a network on their own.
|
||||
const NOISE = /^(ifb|teql|sit|ip6tnl|gre|gretap|erspan|ip6gre|ip6gretap|ip_vti|ip6_vti|tunl|bond)[0-9]*$/;
|
||||
const PRIVATE = [ [ '10.0.0.0', 8 ], [ '172.16.0.0', 12 ], [ '192.168.0.0', 16 ], [ '100.64.0.0', 10 ] ];
|
||||
|
||||
function sysread(dev, f) {
|
||||
return trim(readfile(`${SYS}/${dev}/${f}`) ?? '');
|
||||
}
|
||||
|
||||
function ip_json(args) {
|
||||
try {
|
||||
return json(sh_out(`ip -j ${args} 2>/dev/null`) || '[]') ?? [];
|
||||
}
|
||||
catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function ubus_json(path, method) {
|
||||
try {
|
||||
return json(sh_out(`ubus call ${path} ${method} 2>/dev/null`) || 'null');
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** "a.b.c.d[/len]" → { net, prefix, size } for any prefix 1-32; null for default or junk. */
|
||||
function net_of(s) {
|
||||
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
|
||||
if (ip == null || prefix < 1 || prefix > 32)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
if (prefix == 1)
|
||||
size = 2147483648;
|
||||
return { net: ip - ip % size, prefix, size };
|
||||
}
|
||||
|
||||
function net_str(n) {
|
||||
return `${int2ip(n.net)}/${n.prefix}`;
|
||||
}
|
||||
|
||||
/** Drop networks already covered by a wider one. */
|
||||
export function collapse(list) {
|
||||
let nets = filter(map(uniq(list), net_of), (x) => x != null);
|
||||
nets = sort(nets, (a, b) => a.prefix - b.prefix || a.net - b.net);
|
||||
let keep = [];
|
||||
for (let n in nets) {
|
||||
let inside = false;
|
||||
for (let k in keep)
|
||||
if (n.net >= k.net && n.net < k.net + k.size) {
|
||||
inside = true;
|
||||
break;
|
||||
}
|
||||
if (!inside)
|
||||
push(keep, n);
|
||||
}
|
||||
return map(sort(keep, (a, b) => a.net - b.net), net_str);
|
||||
};
|
||||
|
||||
function is_private(cidr) {
|
||||
let n = net_of(cidr);
|
||||
if (!n)
|
||||
return false;
|
||||
for (let p in PRIVATE) {
|
||||
let base = ip2int(p[0]), size = 1 << (32 - p[1]);
|
||||
if (n.net >= base && n.net < base + size)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* ---------- snapshot ---------- */
|
||||
|
||||
let cache = null;
|
||||
|
||||
/**
|
||||
* One consistent view of the router's interfaces, cached for a few seconds
|
||||
* (rpcd keeps this module loaded, so the cache must expire).
|
||||
*/
|
||||
export function snapshot(fresh) {
|
||||
if (!fresh && cache && time() - cache.ts < 5)
|
||||
return cache;
|
||||
|
||||
// Networks reachable through each device (main table, IPv4).
|
||||
let routes = {}, wan_dev = null;
|
||||
for (let r in ip_json('-4 route show table main')) {
|
||||
if (!r.dev)
|
||||
continue;
|
||||
if (r.dst == 'default') {
|
||||
wan_dev ??= r.dev;
|
||||
continue;
|
||||
}
|
||||
push(routes[r.dev] ??= [], r.dst);
|
||||
}
|
||||
let addrs = {};
|
||||
for (let l in ip_json('-4 addr show'))
|
||||
for (let a in l.addr_info ?? [])
|
||||
if (a.family == 'inet')
|
||||
push(addrs[l.ifname] ??= [], `${a.local}/${a.prefixlen}`);
|
||||
|
||||
// Logical (netifd) interfaces by device, and firewall zones by network.
|
||||
let logical = {};
|
||||
for (let i in ubus_json('network.interface', 'dump')?.interface ?? []) {
|
||||
let dev = i.l3_device ?? i.device;
|
||||
if (dev && !logical[dev])
|
||||
logical[dev] = { name: i.interface, proto: i.proto, up: i.up };
|
||||
}
|
||||
let zone_by_net = {}, zone_by_dev = {}, zones = [];
|
||||
let fc = cursor();
|
||||
fc.load('firewall');
|
||||
fc.foreach('firewall', 'zone', (z) => {
|
||||
if (!z.name)
|
||||
return;
|
||||
push(zones, z.name);
|
||||
for (let n in (type(z.network) == 'array' ? z.network : split(z.network ?? '', /\s+/)))
|
||||
if (n != '')
|
||||
zone_by_net[n] ??= z.name;
|
||||
for (let d in (type(z.device) == 'array' ? z.device : split(z.device ?? '', /\s+/)))
|
||||
if (d != '')
|
||||
zone_by_dev[d] ??= z.name;
|
||||
});
|
||||
|
||||
let devices = {};
|
||||
for (let dev in sort(lsdir(SYS) ?? [])) {
|
||||
if (dev == 'lo' || dev == INTERNAL.transit || dev == INTERNAL.lan)
|
||||
continue;
|
||||
let lg = logical[dev];
|
||||
let flags = hex(sysread(dev, 'flags') || '0');
|
||||
let kind = +(sysread(dev, 'type') || '0');
|
||||
let master = readlink(`${SYS}/${dev}/master`);
|
||||
master = master ? replace(master, /^.*\//, '') : 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]) : [];
|
||||
let up = (flags & 1) != 0;
|
||||
if (match(dev, NOISE) && !length(nets))
|
||||
continue;
|
||||
let cat;
|
||||
if (wifi)
|
||||
cat = 'wifi';
|
||||
else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/))
|
||||
cat = 'vpn';
|
||||
else if (kind == 1 || bridge)
|
||||
cat = 'ethernet';
|
||||
else
|
||||
cat = 'other';
|
||||
devices[dev] = {
|
||||
name: dev,
|
||||
category: dev == wan_dev ? 'wan' : cat,
|
||||
kind: bridge ? 'bridge' : cat,
|
||||
up,
|
||||
master,
|
||||
members: [],
|
||||
nets,
|
||||
addrs: addrs[dev] ?? [],
|
||||
logical: lg?.name,
|
||||
proto: lg?.proto,
|
||||
zone: zone_by_dev[dev] ?? (lg ? zone_by_net[lg.name] : null),
|
||||
};
|
||||
}
|
||||
for (let dev, d in devices)
|
||||
if (d.master && devices[d.master])
|
||||
push(devices[d.master].members, dev);
|
||||
|
||||
// The LAN: netifd's "lan" if present, otherwise the first bridge (then
|
||||
// ethernet device) carrying a private network.
|
||||
let lan_dev = null;
|
||||
for (let dev, lg in logical)
|
||||
if (lg.name == 'lan' && devices[dev])
|
||||
lan_dev = dev;
|
||||
if (!lan_dev)
|
||||
for (let pass in [ 'bridge', 'ethernet' ])
|
||||
for (let dev, d in devices)
|
||||
if (!lan_dev && dev != wan_dev && d.kind == pass && !d.master && length(filter(d.nets, is_private)))
|
||||
lan_dev = dev;
|
||||
|
||||
cache = { ts: time(), devices, wan: wan_dev, lan: lan_dev, zones };
|
||||
return cache;
|
||||
};
|
||||
|
||||
/* ---------- per server ---------- */
|
||||
|
||||
/**
|
||||
* What a server actually uses right now:
|
||||
* wan: { dev, zone, auto, missing }
|
||||
* home: [{ dev, auto, nets, zone, missing }]
|
||||
* nets: home networks (collapsed), zones: their firewall zones
|
||||
*/
|
||||
export function server_net(srv, snap) {
|
||||
snap ??= snapshot();
|
||||
let devs = snap.devices;
|
||||
|
||||
let wan_dev = srv.auto_wan ? (snap.wan ?? srv.detected_wan) : srv.wan_device;
|
||||
let wan = {
|
||||
dev: wan_dev || null,
|
||||
auto: !!srv.auto_wan,
|
||||
zone: devs[wan_dev]?.zone ?? srv.wan_zone ?? 'wan',
|
||||
missing: !!wan_dev && !devs[wan_dev],
|
||||
};
|
||||
|
||||
let picked = [];
|
||||
let auto_lan = srv.auto_lan ? (snap.lan ?? srv.detected_lan) : null;
|
||||
if (auto_lan)
|
||||
push(picked, [ auto_lan, true ]);
|
||||
for (let d in srv.lan_devices ?? [])
|
||||
if (d != auto_lan)
|
||||
push(picked, [ d, false ]);
|
||||
|
||||
let home = [], nets = [], zones = [];
|
||||
for (let p in picked) {
|
||||
let dev = p[0];
|
||||
// Never the WAN, the tunnel itself, or a bridge port (routing only sees the bridge).
|
||||
if (dev == wan.dev || dev == srv.ifname || devs[dev]?.master)
|
||||
continue;
|
||||
let d = devs[dev];
|
||||
let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? null, missing: !d };
|
||||
push(home, h);
|
||||
push(nets, ...h.nets);
|
||||
if (h.zone)
|
||||
push(zones, h.zone);
|
||||
}
|
||||
// Older configs and routers where nothing could be resolved: the zone set at setup.
|
||||
if (!length(home) && srv.auto_lan && srv.lan_zone)
|
||||
push(zones, srv.lan_zone);
|
||||
return { wan, home, nets: collapse(nets), zones: uniq(zones) };
|
||||
};
|
||||
|
||||
/** Router address on the home network (DNS for tunnel clients). */
|
||||
export function home_address(srv, snap) {
|
||||
snap ??= snapshot();
|
||||
let sn = server_net(srv, snap);
|
||||
for (let h in sn.home)
|
||||
for (let a in snap.devices[h.dev]?.addrs ?? [])
|
||||
return split(a, '/')[0];
|
||||
return null;
|
||||
};
|
||||
|
||||
/** WAN IPv4 address of a server's WAN interface. */
|
||||
export function wan_address(srv, snap) {
|
||||
snap ??= snapshot();
|
||||
let a = snap.devices[server_net(srv, snap).wan.dev]?.addrs?.[0];
|
||||
return a ? split(a, '/')[0] : null;
|
||||
};
|
||||
@@ -0,0 +1,658 @@
|
||||
// Dawnline — operations: health checks (with fixes), backups, export/import.
|
||||
|
||||
import { readfile, writefile, stat, unlink, lsdir } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import {
|
||||
q, sh, sh_out, ensure_dir, read_json, write_json, write_file, parse_cidr, cidr_overlaps, cidr_str,
|
||||
ip2int, in_cidr, file_exists, valid_host, cloudflare_ip, DATA_DIR, RUN_DIR, VERSION
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import * as net from 'dawnline.net';
|
||||
|
||||
const BACKUP_DIR = `${DATA_DIR}/backups`;
|
||||
const KEEP_BACKUPS = 10;
|
||||
|
||||
/**
|
||||
* Packages a feature needs that are missing, by feature: https (the portal: openssl-util and any
|
||||
* TLS module for uhttpd), acme (Let's Encrypt certificates), home (the home-like link). Checked by
|
||||
* files, so it is cheap enough for every page load.
|
||||
*/
|
||||
export function needs() {
|
||||
let tls = false;
|
||||
for (let d in [ '/lib', '/usr/lib' ])
|
||||
for (let f in lsdir(d) ?? [])
|
||||
if (substr(f, 0, 16) == 'libustream-ssl.s')
|
||||
tls = true;
|
||||
let kver = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||
let veth = stat('/sys/module/veth') != null || file_exists(`/lib/modules/${kver}/veth.ko`);
|
||||
let miss = (list) => map(filter(list, (x) => !x[0]), (x) => x[1]);
|
||||
return {
|
||||
https: miss([ [ file_exists('/usr/bin/openssl'), 'openssl-util' ], [ tls, 'libustream-openssl' ] ]),
|
||||
acme: miss([ [ file_exists('/usr/lib/acme/client/acme.sh'), 'acme' ], [ file_exists('/usr/lib/acme/client/dnsapi/dns_cf.sh'), 'acme-acmesh-dnsapi' ],
|
||||
[ file_exists('/www/luci-static/resources/view/acme.js'), 'luci-app-acme' ] ]),
|
||||
home: miss([ [ file_exists('/usr/libexec/ip-full'), 'ip-full' ], [ veth, 'kmod-veth' ] ]),
|
||||
};
|
||||
};
|
||||
|
||||
/** ACME certificates on the router and the names each covers. */
|
||||
function acme_certs() {
|
||||
let out = [];
|
||||
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
|
||||
let m = match(f, /^(.+)\.fullchain\.crt$/);
|
||||
if (!m)
|
||||
continue;
|
||||
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
|
||||
if (!file_exists(k))
|
||||
continue;
|
||||
let sans = sh_out(`openssl x509 -in ${q(c)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '';
|
||||
push(out, { cert: c, key: k, names: filter(split(replace(sans, /DNS:/g, ''), /[ \t\r\n]+/), (x) => x != '') });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The ACME certificate that covers host (exact name or a wildcard), if any. */
|
||||
function acme_cert_for(host) {
|
||||
for (let a in acme_certs())
|
||||
for (let n in a.names)
|
||||
if (n == host || (substr(n, 0, 2) == '*.' && index(host, '.') > 0 && substr(host, index(host, '.')) == substr(n, 1)))
|
||||
return a;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Certificate the portal should use: configured, ACME for the host, or self-signed. */
|
||||
export function portal_cert(s) {
|
||||
if (s.portal_cert && s.portal_key && file_exists(s.portal_cert) && file_exists(s.portal_key))
|
||||
return { cert: s.portal_cert, key: s.portal_key, self_signed: false };
|
||||
if (s.portal_host) {
|
||||
for (let base in [ `/etc/ssl/acme/${s.portal_host}`, `/etc/acme/${s.portal_host}_ecc/${s.portal_host}` ]) {
|
||||
let c = `${base}.fullchain.crt`, k = `${base}.key`;
|
||||
if (file_exists(c) && file_exists(k))
|
||||
return { cert: c, key: k, self_signed: false };
|
||||
}
|
||||
// An ACME certificate issued for several names, the portal's among them.
|
||||
let a = acme_cert_for(s.portal_host);
|
||||
if (a)
|
||||
return { cert: a.cert, key: a.key, self_signed: false };
|
||||
}
|
||||
let c = `${DATA_DIR}/portal.crt`, k = `${DATA_DIR}/portal.key`;
|
||||
if (!file_exists(c) || !file_exists(k)) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
let cn = s.portal_host || 'dawnline';
|
||||
sh(`openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj ${q('/CN=' + cn)} -keyout ${k} -out ${c}`);
|
||||
system(`chmod 600 ${k}`);
|
||||
}
|
||||
return { cert: c, key: k, self_signed: true };
|
||||
};
|
||||
|
||||
/* ---------- health ---------- */
|
||||
|
||||
function check(id, title, status, detail, fix) {
|
||||
return { id, title, status, detail: detail ?? '', fix: fix ?? null };
|
||||
}
|
||||
|
||||
function udp_listening(port) {
|
||||
let hex = sprintf(':%04X ', port);
|
||||
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
|
||||
if (index(readfile(f) ?? '', hex) >= 0)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function tcp_listening(port) {
|
||||
let hex = sprintf(':%04X ', port);
|
||||
for (let f in [ '/proc/net/tcp', '/proc/net/tcp6' ])
|
||||
for (let line in split(readfile(f) ?? '', '\n'))
|
||||
// state 0A = LISTEN
|
||||
if (index(line, hex) > 0 && match(line, / 0A /))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Processes other than our portal listening on a TCP port: [ "name" ]. */
|
||||
export function tcp_port_owners(port) {
|
||||
let out = sh_out(`netstat -lntp 2>/dev/null | awk '$4 ~ /:${+port}$/ {print $7}'`) ?? '';
|
||||
let owners = [];
|
||||
for (let o in split(out, '\n')) {
|
||||
let name = split(o, '/')[1];
|
||||
if (!name || index(owners, name) >= 0)
|
||||
continue;
|
||||
// Our own portal runs as a dedicated uhttpd instance.
|
||||
let pid = +split(o, '/')[0];
|
||||
let cmd = readfile(`/proc/${pid}/cmdline`) ?? '';
|
||||
if (index(cmd, '/usr/share/dawnline/portal') >= 0)
|
||||
continue;
|
||||
push(owners, name);
|
||||
}
|
||||
return owners;
|
||||
};
|
||||
|
||||
function resolve(host) {
|
||||
if (ip2int(host) != null)
|
||||
return [ host ];
|
||||
// Public resolvers first: local DNS often rewrites the router's own name
|
||||
// to its LAN address (split horizon).
|
||||
for (let srv in [ '1.1.1.1', '8.8.8.8', '127.0.0.1' ]) {
|
||||
let out = sh_out(`timeout 5 nslookup ${q(host)} ${srv} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}'`);
|
||||
let ips = out ? filter(split(out, '\n'), (x) => ip2int(x) != null) : [];
|
||||
if (length(ips))
|
||||
return ips;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function wan_ipv4(zone) {
|
||||
let st = live.iface_status(zone == 'wan' ? 'wan' : zone);
|
||||
return st?.['ipv4-address']?.[0]?.address;
|
||||
}
|
||||
|
||||
/** The router's public IPv4 (the first server's WAN, else the wan interface). */
|
||||
function router_wan(m) {
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key) {
|
||||
let a = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
|
||||
if (a)
|
||||
return a;
|
||||
}
|
||||
return wan_ipv4('wan');
|
||||
}
|
||||
|
||||
/*
|
||||
* Addresses the portal could use in links, found on the router: names in ACME
|
||||
* certificates, server endpoints, DDNS names, the current one, and the WAN IP.
|
||||
* Each says where it points and whether a certificate covers it.
|
||||
*/
|
||||
export function portal_candidates(m) {
|
||||
let wan = router_wan(m);
|
||||
let names = [];
|
||||
let add = (h) => {
|
||||
if (h && valid_host(h) && ip2int(h) == null && substr(h, 0, 2) != '*.' && index(names, h) < 0)
|
||||
push(names, h);
|
||||
};
|
||||
for (let a in acme_certs())
|
||||
for (let n in a.names)
|
||||
add(n);
|
||||
for (let id, srv in m.servers)
|
||||
add(srv.endpoint);
|
||||
let dc = cursor();
|
||||
if (dc.load('ddns'))
|
||||
dc.foreach('ddns', 'service', (sv) => {
|
||||
if (sv.enabled != '0') {
|
||||
add(sv.lookup_host);
|
||||
add(sv.domain);
|
||||
}
|
||||
});
|
||||
for (let h in core.portal_hosts(m))
|
||||
add(h);
|
||||
let out = [];
|
||||
for (let h in names) {
|
||||
let ips = resolve(h);
|
||||
push(out, { host: h, kind: 'name', ips, here: wan != null && index(ips, wan) >= 0,
|
||||
cloudflare: length(filter(ips, (x) => cloudflare_ip(x))) > 0, cert: acme_cert_for(h) != null });
|
||||
}
|
||||
if (wan)
|
||||
push(out, { host: wan, kind: 'ip', ips: [ wan ], here: true, cloudflare: false, cert: false });
|
||||
for (let ph in core.portal_hosts(m))
|
||||
if (ip2int(ph) != null && ph != wan)
|
||||
push(out, { host: ph, kind: 'ip', ips: [ ph ], here: false, cloudflare: false, cert: false });
|
||||
// Best first: here with a certificate, then here, then the rest.
|
||||
let score = (c) => (c.here ? 4 : 0) + (c.cert ? 2 : 0) + (c.kind == 'name' ? 1 : 0) - (c.cloudflare ? 8 : 0);
|
||||
return sort(out, (a, b) => score(b) - score(a));
|
||||
};
|
||||
|
||||
function service_running(name, instance) {
|
||||
let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`);
|
||||
if (!s)
|
||||
return false;
|
||||
try {
|
||||
let j = json(s);
|
||||
let inst = j?.[name]?.instances?.[instance];
|
||||
return !!inst?.running;
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function other_subnets(srv_id) {
|
||||
let out = [];
|
||||
let st = sh_out('ubus call network.interface dump 2>/dev/null');
|
||||
let d = st ? json(st) : null;
|
||||
let ours = {};
|
||||
let m = core.load();
|
||||
for (let id, s in m.servers)
|
||||
ours[s.ifname] = id;
|
||||
for (let i in d?.interface ?? []) {
|
||||
if (srv_id != null && ours[i.interface] == srv_id)
|
||||
continue;
|
||||
for (let a in i['ipv4-address'] ?? [])
|
||||
push(out, { iface: i.interface, cidr: `${a.address}/${a.mask}` });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function used_subnets(except_srv) {
|
||||
return map(other_subnets(except_srv), (x) => x.cidr);
|
||||
};
|
||||
|
||||
/**
|
||||
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }.
|
||||
* `fix` names an action accepted by fix().
|
||||
*/
|
||||
/*
|
||||
* Policy rules that send the router's own (marked) traffic into a local table,
|
||||
* the way transparent proxies capture it: "pref 1000 fwmark 0x1 → table 100".
|
||||
*/
|
||||
function proxy_diverts() {
|
||||
let out = [];
|
||||
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
|
||||
let mm = match(line, /^(\d+):.*fwmark (\S+).* lookup (\S+)/);
|
||||
if (!mm || +mm[1] >= 32766)
|
||||
continue;
|
||||
if (match(sh_out(`ip -4 route show table ${mm[3]} 2>/dev/null`) ?? '', /(^|\n)local default/))
|
||||
push(out, `pref ${mm[1]} fwmark ${mm[2]} → table ${mm[3]}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Our "answers leave by main" rule for this port (see apply.sync_reply_routes). */
|
||||
function reply_rule(proto, port) {
|
||||
return index(sh_out('ip -4 rule show priority 90 2>/dev/null') ?? '', `ipproto ${proto} sport ${+port} lookup main`) >= 0;
|
||||
}
|
||||
|
||||
function reply_check(id, title, proto, port, diverts) {
|
||||
let ok = reply_rule(proto, port);
|
||||
let via = length(diverts) ? ` A proxy on the router diverts its own traffic (${join(', ', diverts)}); these answers skip it.` : '';
|
||||
return check(id, title, ok ? 'ok' : (length(diverts) ? 'error' : 'warn'),
|
||||
ok ? `Answers from ${uc(proto)} ${port} go straight out.${via}`
|
||||
: length(diverts) ? `Answers from ${uc(proto)} ${port} can be swallowed by a proxy on the router (${join(', ', diverts)}): clients get no reply.`
|
||||
: `The rule that keeps answers from ${uc(proto)} ${port} out of proxies is missing.`,
|
||||
ok ? null : 'apply');
|
||||
}
|
||||
|
||||
export function health(m) {
|
||||
let diverts = proxy_diverts();
|
||||
m ??= core.load();
|
||||
let out = [];
|
||||
let dmp = live.dump();
|
||||
|
||||
let kmod = file_exists('/sys/module/amneziawg');
|
||||
let tools = file_exists('/usr/bin/awg');
|
||||
push(out, check('awg', 'AmneziaWG installed', kmod && tools ? 'ok' : 'error',
|
||||
kmod && tools ? 'Kernel module and awg tool present.' :
|
||||
(!tools ? 'amneziawg-tools is missing.' : 'The kmod-amneziawg module is not loaded.'), kmod && tools ? null : 'updates'));
|
||||
|
||||
let y = localtime().year;
|
||||
push(out, check('clock', 'Clock is set', y >= 2025 ? 'ok' : 'error',
|
||||
y >= 2025 ? 'End dates and quotas use the router clock.' : 'The router clock looks wrong; end dates will misbehave. Check NTP.'));
|
||||
|
||||
push(out, check('agent', 'Background agent running', service_running('dawnline', 'agent') ? 'ok' : 'error',
|
||||
'Counts traffic and enforces end dates and quotas.', service_running('dawnline', 'agent') ? null : 'restart'));
|
||||
|
||||
if (!length(m.servers)) {
|
||||
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.'));
|
||||
return out;
|
||||
}
|
||||
|
||||
let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0;
|
||||
push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error',
|
||||
nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.' : 'Table inet dawnline is missing: access is not enforced.',
|
||||
nft_ok ? null : 'apply'));
|
||||
|
||||
let fwc = cursor();
|
||||
fwc.load('firewall');
|
||||
|
||||
for (let id, srv in m.servers) {
|
||||
let label = length(m.servers) > 1 ? ` (${srv.name})` : '';
|
||||
if (!srv.enabled) {
|
||||
push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.'));
|
||||
continue;
|
||||
}
|
||||
let st = live.iface_status(srv.ifname);
|
||||
let up = !!st?.up;
|
||||
push(out, check(`up_${id}`, `Tunnel interface up${label}`, up ? 'ok' : 'error',
|
||||
up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` :
|
||||
(st ? `${srv.ifname} is down${st.errors ? ': ' + join(', ', map(st.errors, (e) => e.code)) : ''}.` : `${srv.ifname} does not exist.`),
|
||||
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
|
||||
|
||||
if (up) {
|
||||
let expected = 0;
|
||||
let states = apply.states_for(m, core.load_usage());
|
||||
for (let did, d in m.devices)
|
||||
if (m.people[d.person]?.server == id && !d.disabled && states[d.person] == 'active')
|
||||
expected++;
|
||||
let actual = 0;
|
||||
for (let k, p in dmp.peers)
|
||||
if (p.ifname == srv.ifname)
|
||||
actual++;
|
||||
push(out, check(`peers_${id}`, `Devices loaded${label}`, expected == actual ? 'ok' : 'warn',
|
||||
`${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync'));
|
||||
}
|
||||
|
||||
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
|
||||
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
|
||||
push(out, check(`fw_${id}`, `Firewall${label}`, rule && zone ? 'ok' : 'error',
|
||||
rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.',
|
||||
rule && zone ? null : 'apply'));
|
||||
push(out, reply_check(`reply_${id}`, `Answers reach clients${label}`, 'udp', srv.port, diverts));
|
||||
|
||||
// Port collisions with other tunnels.
|
||||
let clash = [];
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
nc.foreach('network', 'interface', (s) => {
|
||||
if (s['.name'] != srv.ifname && (s.proto == 'amneziawg' || s.proto == 'wireguard') && +s.listen_port == srv.port)
|
||||
push(clash, s['.name']);
|
||||
});
|
||||
if (length(clash))
|
||||
push(out, check(`port_${id}`, `Port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', clash)}.`));
|
||||
|
||||
let overlaps = [];
|
||||
let sc = parse_cidr(srv.subnet);
|
||||
for (let o in other_subnets(id)) {
|
||||
let oc = parse_cidr(o.cidr);
|
||||
if (sc && oc && cidr_overlaps(sc, oc))
|
||||
push(overlaps, `${o.iface} (${o.cidr})`);
|
||||
}
|
||||
push(out, check(`subnet_${id}`, `Subnet is unique${label}`, length(overlaps) ? 'error' : 'ok',
|
||||
length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`));
|
||||
|
||||
let host = core.endpoint_host(m, srv);
|
||||
if (!host)
|
||||
push(out, check(`ep_${id}`, `Public address${label}`, 'error', 'No endpoint hostname: clients will not know where to connect.'));
|
||||
else {
|
||||
let ips = resolve(host);
|
||||
let wan = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
|
||||
let wc = wan ? ip2int(wan) : null;
|
||||
let cgnat = wc != null && (in_cidr(wc, parse_cidr('100.64.0.0/10')) || in_cidr(wc, parse_cidr('10.0.0.0/8')) ||
|
||||
in_cidr(wc, parse_cidr('172.16.0.0/12')) || in_cidr(wc, parse_cidr('192.168.0.0/16')));
|
||||
let stv = 'ok', det;
|
||||
if (!length(ips)) {
|
||||
stv = 'error';
|
||||
det = `${host} does not resolve.`;
|
||||
}
|
||||
else if (cgnat) {
|
||||
stv = 'warn';
|
||||
det = `WAN address ${wan} is private: forward UDP ${srv.port} on the upstream router, or clients cannot connect.`;
|
||||
}
|
||||
else if (wan && index(ips, wan) < 0) {
|
||||
stv = 'warn';
|
||||
det = `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`;
|
||||
}
|
||||
else
|
||||
det = `${host} → ${join(', ', ips)}`;
|
||||
push(out, check(`ep_${id}`, `Public address${label}`, stv, det));
|
||||
}
|
||||
|
||||
if (srv.lan_like) {
|
||||
let ls = loop.status();
|
||||
let nh = needs().home;
|
||||
push(out, check(`home_${id}`, `Internet like a home device${label}`, ls.active && ls.bridged ? 'ok' : 'warn',
|
||||
ls.active && ls.bridged ? `Traffic enters ${ls.dev} as ${ls.address}, so it is handled like any device on your LAN.` :
|
||||
length(nh) ? `Needs ${join(' and ', nh)}. Internet traffic leaves through WAN directly until then.` :
|
||||
ls.active ? `The link is up but not attached to ${ls.dev}.` :
|
||||
`${ls.error ?? 'Not set up.'} Internet traffic leaves through WAN directly.`,
|
||||
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply'));
|
||||
}
|
||||
}
|
||||
|
||||
if (length(filter(values(m.servers), (x) => x.private_key))) {
|
||||
let rt = loop.resolver_target();
|
||||
let ok = stat(loop.RESOLVER.conf) != null && loop.resolver_running();
|
||||
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
|
||||
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`)
|
||||
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply'));
|
||||
}
|
||||
|
||||
let s = m.settings;
|
||||
let need = needs();
|
||||
if (s.portal_enabled && length(need.https))
|
||||
push(out, check('portal', 'Personal portal', 'error',
|
||||
`HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https'));
|
||||
else if (s.portal_enabled) {
|
||||
let owners = tcp_port_owners(s.portal_port);
|
||||
let listening = tcp_listening(s.portal_port);
|
||||
if (length(owners))
|
||||
push(out, check('portal', 'Personal portal', 'error',
|
||||
`TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`));
|
||||
else
|
||||
push(out, check('portal', 'Personal portal', listening ? 'ok' : 'error',
|
||||
listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart'));
|
||||
if (!s.portal_host)
|
||||
push(out, check('portal_host', 'Portal address', 'error', 'Set the public hostname in Settings so links can be generated.'));
|
||||
else {
|
||||
let ips = resolve(s.portal_host), wan = router_wan(m);
|
||||
let cf = filter(ips, (x) => cloudflare_ip(x));
|
||||
push(out, check('portal_dns', 'Portal address points here', !length(ips) ? 'error' : length(cf) ? 'warn' : wan && index(ips, wan) < 0 ? 'warn' : 'ok',
|
||||
!length(ips) ? `${s.portal_host} does not resolve.` :
|
||||
length(cf) ? `${s.portal_host} goes through Cloudflare; in Russia such connections often stall after ~16 KB.` :
|
||||
wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` :
|
||||
`${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`));
|
||||
}
|
||||
push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, diverts));
|
||||
if (core.portal_http(m)) {
|
||||
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
|
||||
push(out, check('portal_http', 'Plain HTTP links', 'warn',
|
||||
`Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`));
|
||||
}
|
||||
|
||||
// Links on 443: forwarded from outside, and the same link at home through LuCI's web server.
|
||||
let pub = core.portal_public_port(m);
|
||||
if (s.portal_port != 443) {
|
||||
if (!s.portal_443)
|
||||
push(out, check('portal_443', 'Links without a port', 'skip',
|
||||
`Off: links use port ${s.portal_port}. Mobile networks often drop HTTPS on ports other than 443.`));
|
||||
else if (pub != 443)
|
||||
push(out, check('portal_443', 'Links without a port', 'warn',
|
||||
`TCP 443 is already forwarded to another device, so links use port ${s.portal_port}.`));
|
||||
else {
|
||||
let fw = system(`nft list ruleset 2>/dev/null | grep -q 'Dawnline-Portal-443'`) == 0;
|
||||
push(out, check('portal_443', 'Links without a port', fw ? 'ok' : 'error',
|
||||
fw ? `From the internet TCP 443 reaches the portal only (LuCI stays closed there).` : 'The 443 forward to the portal is missing.',
|
||||
fw ? null : 'apply'));
|
||||
let uc_ = cursor();
|
||||
uc_.load('uhttpd');
|
||||
let ep = uc_.get('uhttpd', 'main', 'error_page');
|
||||
let mine = ep == '/cgi-bin/dawnline-portal' && stat('/www/cgi-bin/dawnline-portal') != null;
|
||||
push(out, check('portal_lan', 'Same link at home', mine ? 'ok' : ep ? 'warn' : 'error',
|
||||
mine ? 'At home the link opens through LuCI\'s web server, which hands unknown paths to the portal.'
|
||||
: ep ? `LuCI's web server already uses ${ep} for unknown paths, so at home links need :${s.portal_port}.`
|
||||
: 'LuCI\'s web server does not hand portal links to the portal: at home they show Not found.',
|
||||
mine || ep ? null : 'apply'));
|
||||
}
|
||||
}
|
||||
|
||||
let cert = portal_cert(s);
|
||||
if (ip2int(s.portal_host) != null)
|
||||
push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.'));
|
||||
else {
|
||||
let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0;
|
||||
let sans = cert.self_signed ? [] : split(replace(sh_out(`openssl x509 -in ${q(cert.cert)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '', /DNS:/g, ''), /[ \t\r\n]+/);
|
||||
let covers = !s.portal_host || cert.self_signed || index(sans, s.portal_host) >= 0 ||
|
||||
length(filter(sans, (n) => substr(n, 0, 2) == '*.' && substr(s.portal_host, index(s.portal_host, '.')) == substr(n, 1)));
|
||||
push(out, check('cert', 'Portal certificate', cert.self_signed || !ok || !covers ? 'warn' : 'ok',
|
||||
cert.self_signed ? `Using a self-signed certificate: browsers will show a warning.${length(need.acme) ? ' ACME can get a free Let’s Encrypt one.' : ''}` :
|
||||
!covers ? `${cert.cert} does not cover ${s.portal_host} (it has ${join(', ', sans)}): browsers will warn.` :
|
||||
ok ? `${cert.cert} covers ${s.portal_host} and is valid for more than 14 days.` : `${cert.cert} expires within 14 days.`));
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
};
|
||||
|
||||
export function fix(id) {
|
||||
if (id == 'apply')
|
||||
return apply.apply();
|
||||
if (id == 'sync')
|
||||
return apply.sync();
|
||||
if (id == 'restart')
|
||||
return { code: system('/etc/init.d/dawnline restart >/dev/null 2>&1') };
|
||||
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
|
||||
if (m) {
|
||||
system(`ifup ${q(m[1])}`);
|
||||
return { ok: true };
|
||||
}
|
||||
die('Unknown fix.');
|
||||
};
|
||||
|
||||
/* ---------- backups ---------- */
|
||||
|
||||
function backup_files() {
|
||||
let out = [ '/etc/config/dawnline' ];
|
||||
for (let f in [ 'usage.json', 'events.json' ])
|
||||
if (file_exists(`${DATA_DIR}/${f}`))
|
||||
push(out, `${DATA_DIR}/${f}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function backup_list() {
|
||||
let out = [];
|
||||
for (let f in lsdir(BACKUP_DIR) ?? []) {
|
||||
let mm = match(f, /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/);
|
||||
if (!mm)
|
||||
continue;
|
||||
let st = stat(`${BACKUP_DIR}/${f}`);
|
||||
push(out, { name: f, created: st?.mtime ?? 0, size: st?.size ?? 0, reason: mm[3] ?? 'manual' });
|
||||
}
|
||||
return sort(out, (a, b) => b.created - a.created);
|
||||
};
|
||||
|
||||
export function backup_create(reason) {
|
||||
// Flush live counters first so the backup has current usage.
|
||||
let u = read_json(`${RUN_DIR}/usage.json`, null);
|
||||
if (u)
|
||||
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
|
||||
live.persist_events();
|
||||
ensure_dir(BACKUP_DIR, 0o700);
|
||||
let t = localtime();
|
||||
let tag = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? `-${reason}` : '';
|
||||
let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, tag);
|
||||
let files = join(' ', map(backup_files(), (f) => q(substr(f, 1))));
|
||||
let r = sh(`tar -czf ${q(BACKUP_DIR + '/' + name)} -C / ${files}`);
|
||||
if (r.code != 0)
|
||||
die(`Backup failed: ${trim(r.out)}`);
|
||||
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
|
||||
let all = backup_list();
|
||||
for (let i = KEEP_BACKUPS; i < length(all); i++)
|
||||
unlink(`${BACKUP_DIR}/${all[i].name}`);
|
||||
return name;
|
||||
};
|
||||
|
||||
function backup_path(name) {
|
||||
if (!match(name ?? '', /^dawnline-[0-9]{8}-[0-9]{6}(-[a-z0-9-]+)?\.tar\.gz$/))
|
||||
die('Invalid backup name.');
|
||||
let p = `${BACKUP_DIR}/${name}`;
|
||||
if (!file_exists(p))
|
||||
die('Backup not found.');
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Validate an archive: only Dawnline's own files may be inside. */
|
||||
function check_archive(path) {
|
||||
let r = sh(`tar -tzf ${q(path)}`);
|
||||
if (r.code != 0)
|
||||
die('Not a valid backup archive.');
|
||||
let allowed = { 'etc/config/dawnline': true };
|
||||
let has_config = false;
|
||||
for (let f in split(trim(r.out), '\n')) {
|
||||
f = replace(f, /^\.?\//, '');
|
||||
// The config plus Dawnline's own data files (older versions had more of them).
|
||||
if (!allowed[f] && !match(f, /^etc\/dawnline\/[a-z0-9_-]+\.json$/))
|
||||
die(`Unexpected file in backup: ${f}`);
|
||||
if (f == 'etc/config/dawnline')
|
||||
has_config = true;
|
||||
}
|
||||
if (!has_config)
|
||||
die('Backup does not contain /etc/config/dawnline.');
|
||||
}
|
||||
|
||||
export function backup_restore(name, path) {
|
||||
path ??= backup_path(name);
|
||||
check_archive(path);
|
||||
backup_create('pre-restore');
|
||||
let r = sh(`tar -xzf ${q(path)} -C /`);
|
||||
if (r.code != 0)
|
||||
die(`Restore failed: ${trim(r.out)}`);
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
// Live counters must follow the restored file.
|
||||
unlink(`${RUN_DIR}/usage.json`);
|
||||
unlink(`${RUN_DIR}/events.json`);
|
||||
return apply.apply();
|
||||
};
|
||||
|
||||
export function backup_delete(name) {
|
||||
unlink(backup_path(name));
|
||||
return true;
|
||||
};
|
||||
|
||||
export function backup_read(name) {
|
||||
return b64enc(readfile(backup_path(name)));
|
||||
};
|
||||
|
||||
export function backup_upload(data_b64) {
|
||||
let data = b64dec(data_b64 ?? '');
|
||||
if (!data || length(data) > 4 * 1024 * 1024)
|
||||
die('Upload is empty or too large.');
|
||||
ensure_dir(RUN_DIR);
|
||||
let tmp = `${RUN_DIR}/upload.tar.gz`;
|
||||
write_file(tmp, data);
|
||||
let res;
|
||||
try {
|
||||
res = backup_restore(null, tmp);
|
||||
}
|
||||
catch (e) {
|
||||
unlink(tmp);
|
||||
die(e.message);
|
||||
}
|
||||
unlink(tmp);
|
||||
return res;
|
||||
};
|
||||
|
||||
/* ---------- export / import (JSON) ---------- */
|
||||
|
||||
export function export_json() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let sections = [];
|
||||
c.foreach('dawnline', null, (s) => {
|
||||
let o = { '.type': s['.type'], '.name': s['.name'] };
|
||||
for (let k, v in s)
|
||||
if (substr(k, 0, 1) != '.')
|
||||
o[k] = v;
|
||||
push(sections, o);
|
||||
});
|
||||
return { format: 'dawnline', version: VERSION, exported: time(), sections };
|
||||
};
|
||||
|
||||
export function import_json(data) {
|
||||
if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array')
|
||||
die('Not a Dawnline export.');
|
||||
let types = { settings: true, server: true, person: true, device: true, service: true };
|
||||
for (let s in data.sections) {
|
||||
if (!types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/))
|
||||
die(`Invalid section ${s['.name']}.`);
|
||||
for (let k, v in s)
|
||||
if (substr(k, 0, 1) != '.' && (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array')))
|
||||
die(`Invalid option ${k}.`);
|
||||
}
|
||||
backup_create('pre-import');
|
||||
let lines = [];
|
||||
for (let s in data.sections) {
|
||||
push(lines, `config ${s['.type']} '${s['.name']}'`);
|
||||
for (let k, v in s) {
|
||||
if (substr(k, 0, 1) == '.')
|
||||
continue;
|
||||
let esc = (x) => replace(`${x}`, "'", "'\\''");
|
||||
if (type(v) == 'array')
|
||||
for (let x in v)
|
||||
push(lines, `\tlist ${k} '${esc(x)}'`);
|
||||
else
|
||||
push(lines, `\toption ${k} '${esc(v)}'`);
|
||||
}
|
||||
push(lines, '');
|
||||
}
|
||||
write_file('/etc/config/dawnline', join('\n', lines), 0o600);
|
||||
return apply.apply();
|
||||
};
|
||||
@@ -0,0 +1,276 @@
|
||||
// Dawnline — small helpers shared by the rpcd plugin, the CLI, the agent and
|
||||
// the portal CGI. Nothing in here touches configuration.
|
||||
|
||||
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
|
||||
|
||||
export const VERSION = '0.1.0';
|
||||
/** GitHub repository with Dawnline releases (updates and the installer). */
|
||||
export const REPO = 'tickcount/luci-app-dawnline';
|
||||
export const RUN_DIR = '/var/run/dawnline';
|
||||
export const DATA_DIR = '/etc/dawnline';
|
||||
|
||||
/* ---------- shell ---------- */
|
||||
|
||||
export function q(s) {
|
||||
return "'" + replace(`${s}`, "'", "'\\''") + "'";
|
||||
};
|
||||
|
||||
/** Run a shell command; returns { code, out }. Stdout and stderr are merged. */
|
||||
export function sh(cmd) {
|
||||
let p = popen(`${cmd} 2>&1`, 'r');
|
||||
if (!p)
|
||||
return { code: -1, out: '' };
|
||||
let out = p.read('all') ?? '';
|
||||
let code = p.close();
|
||||
return { code: code ?? 0, out: out };
|
||||
};
|
||||
|
||||
/** Trimmed stdout of a command, or null when it failed. */
|
||||
export function sh_out(cmd) {
|
||||
let r = sh(cmd);
|
||||
return r.code == 0 ? trim(r.out) : null;
|
||||
};
|
||||
|
||||
/** Fire-and-forget: run a shell snippet detached from the caller. */
|
||||
export function sh_bg(cmd) {
|
||||
system(`( ${cmd} ) >/dev/null 2>&1 </dev/null &`);
|
||||
};
|
||||
|
||||
/* ---------- randomness ---------- */
|
||||
|
||||
export function rand_bytes(n) {
|
||||
let f = open('/dev/urandom', 'r');
|
||||
let b = f.read(n);
|
||||
f.close();
|
||||
return b;
|
||||
};
|
||||
|
||||
export function rand_hex(n) {
|
||||
return hexenc(rand_bytes(n));
|
||||
};
|
||||
|
||||
const ALNUM = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
|
||||
/** URL-safe random token without look-alike characters. */
|
||||
export function rand_token(len) {
|
||||
let b = rand_bytes(len), s = '';
|
||||
for (let i = 0; i < len; i++)
|
||||
s += substr(ALNUM, ord(b, i) % length(ALNUM), 1);
|
||||
return s;
|
||||
};
|
||||
|
||||
export function rand_int(lo, hi) {
|
||||
let b = rand_bytes(4);
|
||||
let n = (ord(b, 0) << 24 | ord(b, 1) << 16 | ord(b, 2) << 8 | ord(b, 3)) & 0x7fffffff;
|
||||
return lo + n % (hi - lo + 1);
|
||||
};
|
||||
|
||||
/* ---------- files ---------- */
|
||||
|
||||
export function ensure_dir(path, mode) {
|
||||
let parts = split(path, '/'), cur = '';
|
||||
for (let p in parts) {
|
||||
if (p == '')
|
||||
continue;
|
||||
cur += '/' + p;
|
||||
if (!stat(cur))
|
||||
mkdir(cur, mode ?? 0o755);
|
||||
}
|
||||
};
|
||||
|
||||
export function read_json(path, fallback) {
|
||||
let s = readfile(path);
|
||||
if (s == null || s == '')
|
||||
return fallback;
|
||||
try {
|
||||
let v = json(s);
|
||||
return v ?? fallback;
|
||||
}
|
||||
catch (e) {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
/** Atomic write (temp file + rename). `mode` defaults to 0600. */
|
||||
export function write_file(path, data, mode) {
|
||||
let tmp = `${path}.tmp${rand_hex(3)}`;
|
||||
let f = open(tmp, 'w', mode ?? 0o600);
|
||||
if (!f)
|
||||
return false;
|
||||
f.write(data);
|
||||
f.close();
|
||||
return rename(tmp, path);
|
||||
};
|
||||
|
||||
export function write_json(path, data, mode) {
|
||||
return write_file(path, sprintf('%J', data), mode);
|
||||
};
|
||||
|
||||
export function file_exists(path) {
|
||||
return stat(path) != null;
|
||||
};
|
||||
|
||||
/** Exclusive lock on a file under RUN_DIR; returns a handle to pass to unlock(). */
|
||||
export function lock(name) {
|
||||
ensure_dir(RUN_DIR);
|
||||
let f = open(`${RUN_DIR}/${name}.lock`, 'w');
|
||||
if (f)
|
||||
f.lock('x');
|
||||
return f;
|
||||
};
|
||||
|
||||
export function unlock(f) {
|
||||
if (f) {
|
||||
f.lock('u');
|
||||
f.close();
|
||||
}
|
||||
};
|
||||
|
||||
/* ---------- IPv4 ---------- */
|
||||
|
||||
export function ip2int(ip) {
|
||||
let m = match(ip, /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let n = 0;
|
||||
for (let i = 1; i <= 4; i++) {
|
||||
let o = +m[i];
|
||||
if (o > 255)
|
||||
return null;
|
||||
n = n * 256 + o;
|
||||
}
|
||||
return n;
|
||||
};
|
||||
|
||||
export function int2ip(n) {
|
||||
return sprintf('%d.%d.%d.%d', (n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255);
|
||||
};
|
||||
|
||||
// Cloudflare's published ranges (https://www.cloudflare.com/ips/).
|
||||
const CF_V4 = [ '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18',
|
||||
'108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17',
|
||||
'162.158.0.0/15', '104.16.0.0/13', '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22' ];
|
||||
const CF_V6 = [ /^2400:cb00:/i, /^2606:4700:/i, /^2803:f800:/i, /^2405:b500:/i, /^2405:8100:/i, /^2a06:98c[0-7]:/i, /^2c0f:f248:/i ];
|
||||
|
||||
/** True for an address in Cloudflare's network (its proxies and edge). */
|
||||
export function cloudflare_ip(a) {
|
||||
let n = ip2int(a);
|
||||
if (n == null) {
|
||||
for (let r in CF_V6)
|
||||
if (match(a ?? '', r))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
for (let c in CF_V4) {
|
||||
let m = match(c, /^([0-9.]+)\/([0-9]+)$/);
|
||||
let size = 1 << (32 - +m[2]), net = ip2int(m[1]);
|
||||
if (n >= net && n < net + size)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/** 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)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = +m[2];
|
||||
if (ip == null || prefix < 8 || prefix > 30)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
let net = ip - ip % size;
|
||||
return { net, prefix, size, first: net + 1, last: net + size - 2, ip };
|
||||
};
|
||||
|
||||
export function cidr_str(c) {
|
||||
return `${int2ip(c.net)}/${c.prefix}`;
|
||||
};
|
||||
|
||||
export function cidr_overlaps(a, b) {
|
||||
return a.net < b.net + b.size && b.net < a.net + a.size;
|
||||
};
|
||||
|
||||
export function in_cidr(ip, c) {
|
||||
let n = type(ip) == 'int' ? ip : ip2int(ip);
|
||||
return n != null && n >= c.net && n < c.net + c.size;
|
||||
};
|
||||
|
||||
/* ---------- validation ---------- */
|
||||
|
||||
export function valid_slug(s) {
|
||||
return type(s) == 'string' && match(s, /^[a-z0-9][a-z0-9-]{0,30}[a-z0-9]$|^[a-z0-9]$/) != null;
|
||||
};
|
||||
|
||||
export function valid_name(s) {
|
||||
return type(s) == 'string' && length(trim(s)) > 0 && length(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
|
||||
};
|
||||
|
||||
export function valid_key(s) {
|
||||
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
|
||||
};
|
||||
|
||||
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 || match(s, /^[0-9a-fA-F:]+$/) != null);
|
||||
};
|
||||
|
||||
export function valid_date(s) {
|
||||
return type(s) == 'string' && match(s, /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/) != null;
|
||||
};
|
||||
|
||||
/** Turn a display name into a portal slug candidate. */
|
||||
export function slugify(s) {
|
||||
let out = lc(trim(`${s ?? ''}`));
|
||||
out = replace(out, /[^a-z0-9]+/g, '-');
|
||||
out = replace(out, /^-+|-+$/g, '');
|
||||
return substr(out, 0, 32) || 'user';
|
||||
};
|
||||
|
||||
/* ---------- time ---------- */
|
||||
|
||||
/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */
|
||||
export function date_end(s) {
|
||||
let m = match(s ?? '', /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/);
|
||||
if (!m)
|
||||
return null;
|
||||
return timelocal({ sec: 59, min: 59, hour: 23, mday: +m[3], mon: +m[2], year: +m[1] });
|
||||
};
|
||||
|
||||
export function today() {
|
||||
let t = localtime();
|
||||
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
|
||||
};
|
||||
|
||||
export function month_key(ts) {
|
||||
let t = localtime(ts ?? time());
|
||||
return sprintf('%04d-%02d', t.year, t.mon);
|
||||
};
|
||||
|
||||
export function day_key(ts) {
|
||||
let t = localtime(ts ?? time());
|
||||
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
|
||||
};
|
||||
|
||||
export function uniq(arr) {
|
||||
let seen = {}, out = [];
|
||||
for (let v in arr)
|
||||
if (!seen[v]) {
|
||||
seen[v] = true;
|
||||
push(out, v);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
export function list_dir(path) {
|
||||
return lsdir(path) ?? [];
|
||||
};
|
||||
|
||||
export function remove(path) {
|
||||
return unlink(path);
|
||||
};
|
||||
|
||||
export function now() {
|
||||
return time();
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
// Dawnline — read models shared by the admin RPC and the portal: people and
|
||||
// devices merged with live peer state and usage.
|
||||
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import { day_key, month_key } from 'dawnline.util';
|
||||
|
||||
/** Daily totals (rx+tx) for the last `n` days, oldest first. */
|
||||
export function spark(rec, n) {
|
||||
let out = [], ts = time();
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
let v = rec?.days?.[day_key(ts - i * 86400)];
|
||||
push(out, v ? v[0] + v[1] : 0);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
function config_stale(m, d) {
|
||||
m._issued ??= core.issued();
|
||||
let was = m._issued[d.id];
|
||||
return was != null && was != core.config_fingerprint(m, d);
|
||||
}
|
||||
|
||||
export function device_view(m, d, usage, dmp) {
|
||||
let u = usage.devices?.[d.id];
|
||||
let peer = dmp.peers[d.public_key];
|
||||
let ts = time();
|
||||
let hs = peer?.handshake || u?.handshake || 0;
|
||||
let p = m.people[d.person];
|
||||
return {
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
kind: d.kind,
|
||||
address: d.address,
|
||||
disabled: d.disabled,
|
||||
created: d.created,
|
||||
created_by: d.created_by,
|
||||
online: !!(peer && peer.handshake > 0 && ts - peer.handshake < live.ONLINE_WINDOW),
|
||||
handshake: hs,
|
||||
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
|
||||
active: !!peer,
|
||||
month: live.month(u),
|
||||
total: u?.total ?? [ 0, 0 ],
|
||||
spark: spark(u, 7),
|
||||
hostname: m.settings.hostnames && p ? `${replace(replace(lc(d.name), /[^a-z0-9]+/g, '-'), /^-+|-+$/g, '') || 'device'}.${p.id}.${m.settings.domain}` : '',
|
||||
browser_key: d.private_key == '',
|
||||
// Its configuration changed since it was last shown or downloaded.
|
||||
config_stale: config_stale(m, d),
|
||||
};
|
||||
};
|
||||
|
||||
export function person_view(m, p, usage, dmp, states, opts) {
|
||||
opts ??= {};
|
||||
let u = usage.people?.[p.id];
|
||||
let devs = [];
|
||||
for (let id in p.devices)
|
||||
push(devs, device_view(m, m.devices[id], usage, dmp));
|
||||
devs = sort(devs, (a, b) => a.created - b.created);
|
||||
let used = core.person_usage(p, usage);
|
||||
let v = {
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
server: p.server,
|
||||
access: p.access,
|
||||
device_limit: p.device_limit,
|
||||
expires: p.expires,
|
||||
quota_gb: p.quota_gb,
|
||||
quota_period: p.quota_period,
|
||||
quota_used: used,
|
||||
quota_limit: core.person_quota(p),
|
||||
bonus_gb: (p.bonus_gb > 0 && p.bonus_month == month_key()) ? p.bonus_gb : 0,
|
||||
expire_action: p.expire_action,
|
||||
dns_mode: p.dns_mode,
|
||||
expire_warn: p.expire_warn,
|
||||
paused: p.paused,
|
||||
hours: p.hours,
|
||||
state: states[p.id] ?? core.person_state(m, p, usage),
|
||||
month: live.month(u),
|
||||
total: u?.total ?? [ 0, 0 ],
|
||||
online: length(filter(devs, (d) => d.online)),
|
||||
last_seen: 0,
|
||||
devices: devs,
|
||||
};
|
||||
for (let d in devs)
|
||||
if (d.handshake > v.last_seen)
|
||||
v.last_seen = d.handshake;
|
||||
if (opts.admin) {
|
||||
v.code = p.code;
|
||||
v.link = core.portal_url(m, p);
|
||||
v.links = core.portal_urls(m, p);
|
||||
v.note = p.note;
|
||||
v.services = p.services;
|
||||
v.created = p.created;
|
||||
}
|
||||
return v;
|
||||
};
|
||||
|
||||
export function states(m, usage) {
|
||||
let out = {};
|
||||
for (let id, p in m.people)
|
||||
out[id] = core.person_state(m, p, usage);
|
||||
return out;
|
||||
};
|
||||
Reference in new issue
Block a user