- Components tab replaces Updates: Dawnline, the AmneziaWG build for this firmware (Slava-Shchipunov 2.0 or 2Grey 3.1, Russian translation) and the system packages Dawnline adds, each checked, installed, reinstalled or rolled back in place, with What's new, versions and an activity log - Automatic updates: daily check, install at a set time or right away, per component; AmneziaWG is left out by default and an automatic run never switches its build or generation - Downloads verified against GitHub's sha256; mirrors are used only when GitHub is unreachable and the hash is known - New installer: checks firmware, clock, space and DNS, lets you pick a release, shows the plan and asks first; --dry-run - New uninstaller removes everything Dawnline added (cron, nft, firewall, routing, interfaces, packages it installed); --dry-run - Works without AmneziaWG on the router: Overview, the setup wizard, Health and Components say what is missing and offer to install it - Overview shows failed health checks as notices with their fix - People list no longer reads the config from the browser: private keys stay on the router; personal links are fetched on demand - Config changes are serialized under one lock, the nft table loads atomically and fails closed, and Dawnline never touches network sections it did not create - The portal never opens system ports, keeps disabled devices disabled, rate-limits per address and counts days by the router's clock - Settings and Diagnostics load their heavy parts in the background - Release notes are written from the commits since the previous release - Backend and admin UI split into small single-purpose modules
This commit is contained in:
1 parent
70a932b8ea
commit
34293fb8e5
158 files changed
+17418
-10022
No files matched your search
@@ -0,0 +1 @@
|
||||
/etc/dawnline/
|
||||
@@ -6,9 +6,15 @@ 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 * as health from 'dawnline.health';
|
||||
import * as backup from 'dawnline.backup';
|
||||
import * as pc from 'dawnline.portalcert';
|
||||
import * as watchdog from 'dawnline.watchdog';
|
||||
import { VERSION, slog, sh_out, q, take_iface_intent } from 'dawnline.util';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as store from 'dawnline.store';
|
||||
import {
|
||||
VERSION, slog, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
|
||||
} from 'dawnline.util';
|
||||
|
||||
const args = ARGV;
|
||||
const cmd = args[0] ?? 'help';
|
||||
@@ -30,7 +36,7 @@ function help() {
|
||||
Usage: dawnline <command>
|
||||
|
||||
apply Reconcile router configuration and runtime state
|
||||
sync Push devices and access rules to the tunnel
|
||||
sync Push devices and access rules to the tunnels
|
||||
status People and devices with live state (JSON)
|
||||
health Run health checks (JSON)
|
||||
person add <name> [--slug s] [--access lan|internet|both] [--devices n]
|
||||
@@ -38,7 +44,7 @@ Usage: dawnline <command>
|
||||
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 conf <id> Print a device configuration (.conf)
|
||||
device rm <id> Remove a device
|
||||
backup Create a backup in /etc/dawnline/backups
|
||||
portal-cert Print the certificate and key the portal uses
|
||||
@@ -48,9 +54,47 @@ Usage: dawnline <command>
|
||||
version`);
|
||||
}
|
||||
|
||||
function commit(c) {
|
||||
c.commit('dawnline');
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
/*
|
||||
* netifd retries a tunnel that fails to start every few seconds (a kernel
|
||||
* module that won't load, AmneziaWG removed): one line per interface every
|
||||
* 10 minutes, with how many attempts failed meanwhile. A start clears it.
|
||||
*/
|
||||
const FAILS = `${RUN_DIR}/ifup-failed.json`;
|
||||
const FAIL_EVERY = 600;
|
||||
|
||||
function ifup_failed(ifname, who) {
|
||||
let now = time();
|
||||
// Attempts since the last line (a quiet spell starts a new count), and over how long.
|
||||
let r = with_lock('ifup-failed', () => {
|
||||
let all = read_json(FAILS, {});
|
||||
let f = all[ifname];
|
||||
if (!f || now - f.last > FAIL_EVERY)
|
||||
f = all[ifname] = { logged: 0, count: 0, since: now };
|
||||
f.count++;
|
||||
f.last = now;
|
||||
let out = null;
|
||||
if (now - f.logged >= FAIL_EVERY) {
|
||||
out = { n: f.count, mins: int((now - f.since) / 60) };
|
||||
f.logged = f.since = now;
|
||||
f.count = 0;
|
||||
}
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(FAILS, all, 0o600);
|
||||
return out;
|
||||
});
|
||||
if (r)
|
||||
slog('awg', 'error', r.n > 1 ? `couldn't start · ${r.n} failed attempts in ${r.mins} min` : "couldn't start",
|
||||
watchdog.iface_errors(ifname), who);
|
||||
}
|
||||
|
||||
function ifup_ok(ifname) {
|
||||
with_lock('ifup-failed', () => {
|
||||
let all = read_json(FAILS, {});
|
||||
if (all[ifname]) {
|
||||
delete all[ifname];
|
||||
write_json(FAILS, all, 0o600);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -59,18 +103,16 @@ try {
|
||||
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);
|
||||
let m = core.load(), u = core.load_usage(), d = live.dump(m), 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());
|
||||
out(health.health());
|
||||
else if (cmd == 'person' && args[1] == 'add') {
|
||||
let c = core.open_cursor(), m = core.load(c);
|
||||
let id = core.create_person(c, m, {
|
||||
let id = store.transact((c, m) => 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);
|
||||
}
|
||||
@@ -80,33 +122,29 @@ try {
|
||||
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);
|
||||
store.transact((c, m) => core.delete_person(c, m, args[2]));
|
||||
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);
|
||||
// Keys first: generating them runs the awg tool, not worth holding the config lock for.
|
||||
let keys = awg.new_keys();
|
||||
let id = store.transact((c, m) => core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin', keys }));
|
||||
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);
|
||||
print(awg.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);
|
||||
store.transact((c, m) => core.delete_device(c, m, args[2]));
|
||||
apply.sync();
|
||||
}
|
||||
else if (cmd == 'backup')
|
||||
out(ops.backup_create(opt('reason')));
|
||||
out(backup.backup_create(opt('reason')));
|
||||
else if (cmd == 'portal-cert') {
|
||||
let c = ops.portal_cert(core.load().settings);
|
||||
let c = pc.portal_cert(core.load().settings);
|
||||
out(`${c.cert} ${c.key}`);
|
||||
}
|
||||
else if (cmd == 'portal-http-port') {
|
||||
@@ -137,6 +175,7 @@ try {
|
||||
if (srv.ifname == ifname)
|
||||
who = srv.name;
|
||||
if (args[1] == 'ifup') {
|
||||
ifup_ok(ifname);
|
||||
let port = sh_out(`awg show ${q(ifname)} listen-port 2>/dev/null`);
|
||||
slog('awg', 'up', port ? `started · accepting connections on port ${port}` : 'started', null, who);
|
||||
}
|
||||
@@ -152,7 +191,7 @@ try {
|
||||
], (x) => x)), who);
|
||||
}
|
||||
else if (args[1] == 'ifup-failed')
|
||||
slog('awg', 'error', "couldn't start", watchdog.iface_errors(ifname), who);
|
||||
ifup_failed(ifname, who);
|
||||
}
|
||||
else if (cmd == 'teardown')
|
||||
apply.teardown();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/ucode
|
||||
// Dawnline agent (procd instance). Every minute it:
|
||||
// * folds AmneziaWG counters into usage (tmpfs; flushed to flash hourly)
|
||||
// * folds the tunnels' 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
|
||||
@@ -16,15 +16,19 @@ import {
|
||||
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 backup from 'dawnline.backup';
|
||||
import * as pc from 'dawnline.portalcert';
|
||||
import * as geo from 'dawnline.geo';
|
||||
import * as watchdog from 'dawnline.watchdog';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as upd from 'dawnline.updates';
|
||||
|
||||
const TICK = 60 * 1000;
|
||||
const FLUSH_EVERY = 3600;
|
||||
const LOG_FLUSH = { '10min': 600, hourly: 3600 };
|
||||
const RESYNC_EVERY = 600;
|
||||
const CONFIG_FILE = '/etc/config/dawnline';
|
||||
|
||||
let usage = live.load_usage();
|
||||
let last_states = null;
|
||||
@@ -36,7 +40,10 @@ let last_endpoint = presence.endpoint ?? {};
|
||||
let offline_ticks = {};
|
||||
let last_flush = time();
|
||||
let last_log_flush = time();
|
||||
let last_net = null;
|
||||
// The network as apply() last saw it (apply.NET_SIG; this when it never ran),
|
||||
// and a different one seen on the previous tick.
|
||||
let base_net = null;
|
||||
let pending_net = null;
|
||||
let rate_prev = null;
|
||||
|
||||
/**
|
||||
@@ -95,6 +102,7 @@ function record_rate(m) {
|
||||
write_json(`${RUN_DIR}/rate_people.json`, people, 0o644);
|
||||
}
|
||||
let last_sync = 0;
|
||||
let conf_mtime = null;
|
||||
let cert_mtime = null;
|
||||
|
||||
const REASON = {
|
||||
@@ -113,12 +121,10 @@ function check_people(m, states, events) {
|
||||
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');
|
||||
store.transact((c, mm) => {
|
||||
for (let d in mm.people[id]?.devices ?? [])
|
||||
core.delete_device(c, mm, d);
|
||||
});
|
||||
push(events, { type: 'devices_removed', person: id, detail: 'end date reached' });
|
||||
last_sync = 0;
|
||||
}
|
||||
@@ -217,7 +223,7 @@ function cert_end(path) {
|
||||
function check_cert(m) {
|
||||
if (!m.settings.portal_enabled)
|
||||
return;
|
||||
let c = ops.portal_cert(m.settings);
|
||||
let c = pc.portal_cert(m.settings);
|
||||
let mt = stat(c.cert)?.mtime;
|
||||
if (cert_mtime != null && mt != null && mt != cert_mtime) {
|
||||
slog('portal', 'up', `certificate renewed · valid until ${cert_end(c.cert) ?? '?'}`, null, 'Personal portal');
|
||||
@@ -268,13 +274,22 @@ function nightly_backup() {
|
||||
let st = read_json(`${DATA_DIR}/backup-state.json`, {});
|
||||
if (sum && sum != st.auto) {
|
||||
try {
|
||||
ops.backup_create('auto');
|
||||
backup.backup_create('auto');
|
||||
write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600);
|
||||
}
|
||||
catch (e) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings → Updates: an automatic check or update when one is due. The
|
||||
* updater does the work in its own process; this only decides when.
|
||||
*/
|
||||
function check_updates(m) {
|
||||
if (upd.due(m.settings.updates, upd.auto_state()) && !upd.busy())
|
||||
system('start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- auto');
|
||||
}
|
||||
|
||||
/**
|
||||
* Traffic history resets requested from LuCI (rpcd cannot touch the
|
||||
* counters this process holds in memory). Applied, then saved to flash.
|
||||
@@ -291,78 +306,131 @@ function check_usage_reset(m) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Push devices and access rules when people's states changed, the config
|
||||
* file was written (by anyone: rpcd, the portal, the CLI, a restore), or
|
||||
* every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
|
||||
*/
|
||||
function sync_runtime(t) {
|
||||
// uci commits replace the file: a new inode even within the same second.
|
||||
let st = stat(CONFIG_FILE);
|
||||
let mt = st ? `${st.mtime}/${st.inode}` : null;
|
||||
let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) ||
|
||||
(conf_mtime != null && mt != conf_mtime);
|
||||
if (changed || time() - last_sync > RESYNC_EVERY) {
|
||||
apply.sync(t.m, usage);
|
||||
last_sync = time();
|
||||
}
|
||||
conf_mtime = mt;
|
||||
last_states = t.states;
|
||||
}
|
||||
|
||||
/*
|
||||
* The router's network changed under us: re-derive everything. Only a change
|
||||
* seen on two ticks in a row (a bridge recreated or an interface restarting
|
||||
* passes), compared with what the last apply() used.
|
||||
*/
|
||||
function check_network(t) {
|
||||
let sig = apply.net_signature(t.m);
|
||||
let applied = readfile(apply.NET_SIG) ?? base_net;
|
||||
if (applied == null || sig == applied) {
|
||||
base_net ??= sig;
|
||||
pending_net = null;
|
||||
return;
|
||||
}
|
||||
if (pending_net != sig) {
|
||||
pending_net = sig;
|
||||
return;
|
||||
}
|
||||
pending_net = null;
|
||||
slog('dawnline', 'info', 'network changed — Dawnline set itself up again', null, 'Router');
|
||||
apply.apply();
|
||||
base_net = readfile(apply.NET_SIG) ?? apply.net_signature(core.load());
|
||||
}
|
||||
|
||||
/*
|
||||
* One tick is a list of steps, each on its own: a failing step is logged
|
||||
* (each new message once in the service log, every time in syslog) and the
|
||||
* others still run. Steps that need the model wait for it; the counters and
|
||||
* the logs are saved at the end whatever happened.
|
||||
*/
|
||||
const STEPS = [
|
||||
{ who: 'Dawnline', run: (t) => {
|
||||
t.m = core.load();
|
||||
t.pol = live.policy(t.m.settings.retention);
|
||||
} },
|
||||
{ who: 'Traffic', run: (t) => {
|
||||
t.reset = check_usage_reset(t.m);
|
||||
t.dmp = live.dump(t.m);
|
||||
t.lv = live.collect(t.m, usage, t.dmp);
|
||||
} },
|
||||
{ who: 'Speed', quiet: true, run: (t) => record_rate(t.m) },
|
||||
// Connects and disconnects only from a complete read of the tunnels.
|
||||
{ who: 'Connections', run: (t) => {
|
||||
if (t.lv && t.dmp?.ok)
|
||||
check_devices(t.m, t.lv, t.events);
|
||||
} },
|
||||
{ who: 'People', run: (t) => {
|
||||
t.states = apply.states_for(t.m, usage);
|
||||
check_people(t.m, t.states, t.events);
|
||||
} },
|
||||
{ who: 'Access rules', run: (t) => {
|
||||
if (t.states)
|
||||
sync_runtime(t);
|
||||
} },
|
||||
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
|
||||
{ who: 'Activity', run: (t) => live.add_events(t.events, t.pol) },
|
||||
{ who: 'Internet like a home device', run: (t) => apply.sync_loop(t.m, usage) },
|
||||
{ who: 'Router', run: check_network },
|
||||
{ who: 'Watchdog', run: (t) => watchdog.run(core.load()) },
|
||||
{ who: 'Personal portal', run: (t) => check_cert(t.m) },
|
||||
{ who: 'Router', quiet: true, run: (t) => check_wan(t.m) },
|
||||
{ who: 'Backup', run: (t) => nightly_backup() },
|
||||
{ who: 'updates', quiet: true, run: (t) => check_updates(t.m) },
|
||||
{ who: 'geo', quiet: true, run: (t) => check_geo(t.m) },
|
||||
];
|
||||
|
||||
// Step → the last error it logged (cleared when it works again).
|
||||
let step_err = {};
|
||||
|
||||
function step(i, s, fn) {
|
||||
try {
|
||||
fn();
|
||||
delete step_err[i];
|
||||
}
|
||||
catch (e) {
|
||||
system(`logger -t dawnline-agent ${q(`${s.who}: ${e.message}`)}`);
|
||||
if (!s.quiet && step_err[i] != e.message)
|
||||
slog('dawnline', 'error', `failed: ${e.message}`, e.stacktrace?.[0]?.context, s.who);
|
||||
step_err[i] = e.message;
|
||||
}
|
||||
}
|
||||
|
||||
function tick() {
|
||||
ensure_dir(RUN_DIR);
|
||||
writefile(watchdog.BEAT, `${time()}`);
|
||||
// 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 = [];
|
||||
let t = { m: null, pol: null, reset: false, events: [] };
|
||||
for (let i, s in STEPS)
|
||||
if (i == 0 || t.m)
|
||||
step(i, s, () => s.run(t));
|
||||
|
||||
check_devices(m, lv, events);
|
||||
check_people(m, states, events);
|
||||
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
|
||||
|
||||
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);
|
||||
slog_trim(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) {
|
||||
slog('dawnline', 'info', 'network changed — Dawnline set itself up again', null, 'Router');
|
||||
apply.apply();
|
||||
sig = apply.net_signature(core.load());
|
||||
let persist = t.reset || time() - last_flush >= FLUSH_EVERY;
|
||||
step('save', { who: 'Traffic' }, () => {
|
||||
live.save_usage(usage, persist);
|
||||
if (persist)
|
||||
last_flush = time();
|
||||
});
|
||||
step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist));
|
||||
step('events', { who: 'Activity' }, () => {
|
||||
let pol = t.pol ?? live.policy();
|
||||
if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) {
|
||||
live.persist_events(pol);
|
||||
last_log_flush = time();
|
||||
}
|
||||
last_net = sig;
|
||||
}
|
||||
catch (e) {
|
||||
slog('dawnline', 'error', `failed: ${e.message}`, null, 'Internet like a home device');
|
||||
}
|
||||
try {
|
||||
watchdog.run(core.load());
|
||||
}
|
||||
catch (e) {
|
||||
slog('dawnline', 'error', `failed: ${e.message}`, null, 'Watchdog');
|
||||
}
|
||||
check_cert(m);
|
||||
try {
|
||||
check_wan(m);
|
||||
}
|
||||
catch (e) {}
|
||||
nightly_backup();
|
||||
try {
|
||||
check_geo(m);
|
||||
}
|
||||
catch (e) {
|
||||
system(`logger -t dawnline-agent ${q('geo: ' + e.message)}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function shutdown() {
|
||||
|
||||
@@ -1,64 +1,52 @@
|
||||
#!/usr/bin/ucode
|
||||
// Dawnline background update worker, started detached by luci.dawnline.
|
||||
// Dawnline background update worker, started detached by luci.dawnline and
|
||||
// by the agent (automatic runs).
|
||||
//
|
||||
// updater check
|
||||
// updater install app|amneziawg[:slava|grey[:ru]]|pkgs:<name,…>|all
|
||||
// updater check [app|amneziawg|packages]
|
||||
// updater install app | app@<tag> | app:reinstall | app:rollback
|
||||
// updater install amneziawg[:auto|slava|grey[:ru]] | amneziawg:rollback
|
||||
// updater install pkgs:<name,…>
|
||||
// updater auto (Settings → Updates: check, then install)
|
||||
//
|
||||
// Progress: /var/run/dawnline/update-job.json; check results:
|
||||
// /var/run/dawnline/update-check.json. The Updates tab polls both.
|
||||
// One job at a time: the job holds the update lock (dawnline.updates) until
|
||||
// it exits. Progress: /var/run/dawnline/update-job.json; check results:
|
||||
// /var/run/dawnline/update-check.json. The Components tab polls both. The
|
||||
// components themselves are dawnline.upd_app, upd_awg and upd_pkgs.
|
||||
'use strict';
|
||||
|
||||
import * as fs from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { connect } from 'ubus';
|
||||
import { VERSION, REPO, slog, iface_intent } from 'dawnline.util';
|
||||
import { slog, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as app from 'dawnline.upd_app';
|
||||
import * as awg from 'dawnline.upd_awg';
|
||||
import * as pkgs from 'dawnline.upd_pkgs';
|
||||
|
||||
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;
|
||||
}
|
||||
const PID = +split(fs.readfile('/proc/self/stat') ?? '0', ' ')[0];
|
||||
const POL = core.load().settings.updates;
|
||||
const CHECKS = { app: app.check, amneziawg: awg.check, packages: pkgs.check };
|
||||
const INSTALLS = { app: app.install, amneziawg: awg.install, pkgs: pkgs.install };
|
||||
const WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages', packages: 'System packages' };
|
||||
|
||||
let job = {
|
||||
action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null,
|
||||
phase: '', log: [], error: null, result: null,
|
||||
id: `${time()}-${PID}`, action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null,
|
||||
pid: PID, auto: false, phase: '', from: null, to: null, log: [], error: null, result: null,
|
||||
};
|
||||
// An automatic run only shows up as a job once it installs something.
|
||||
let quiet = ARGV[0] == 'auto';
|
||||
// What to restart once the job is over (never in the middle of it).
|
||||
let after = {};
|
||||
|
||||
function save() {
|
||||
fs.writefile(`${JOB_FILE}.tmp`, sprintf('%J', job));
|
||||
fs.rename(`${JOB_FILE}.tmp`, JOB_FILE);
|
||||
if (!quiet)
|
||||
write_json(upd.JOB_FILE, job, 0o644);
|
||||
}
|
||||
|
||||
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);
|
||||
if (length(job.log) > 400)
|
||||
splice(job.log, 0, length(job.log) - 400);
|
||||
save();
|
||||
}
|
||||
|
||||
@@ -67,475 +55,261 @@ function phase(p) {
|
||||
log(p);
|
||||
}
|
||||
|
||||
function q(s) {
|
||||
return "'" + replace(`${s ?? ''}`, "'", "'\\''") + "'";
|
||||
}
|
||||
|
||||
/** A command, its output in the log: { code, out }. */
|
||||
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'))
|
||||
let r = { code: p.close(), out };
|
||||
for (let line in split(trim(out), '\n'))
|
||||
if (length(trim(line)))
|
||||
log(` ${line}`);
|
||||
return r;
|
||||
}
|
||||
|
||||
function repo() {
|
||||
return REPO;
|
||||
const ctx = {
|
||||
pol: POL,
|
||||
work: `/tmp/dawnline-update.${PID}`,
|
||||
log, phase, run, save,
|
||||
versions: (from, to) => {
|
||||
job.from = from;
|
||||
job.to = to;
|
||||
save();
|
||||
},
|
||||
after: (what) => after[what] = true,
|
||||
};
|
||||
|
||||
/* ---------- check results ---------- */
|
||||
|
||||
function checks_file() {
|
||||
return read_json(upd.CHECK_FILE, null)?.components ?? {};
|
||||
}
|
||||
|
||||
function have_curl() {
|
||||
return fs.access('/usr/bin/curl', 'x');
|
||||
/** Components' results into the check file (the others stay as they were). */
|
||||
function save_check(res) {
|
||||
let c = read_json(upd.CHECK_FILE, null) ?? {};
|
||||
c.components ??= {};
|
||||
for (let k, v in res)
|
||||
c.components[k] = { ...v, time: time() };
|
||||
c.time = time();
|
||||
write_json(upd.CHECK_FILE, c, 0o644);
|
||||
}
|
||||
|
||||
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;
|
||||
/** What a check found, as short names ("Dawnline 0.3.3", "2 system packages"). */
|
||||
function found_in(res) {
|
||||
let found = [];
|
||||
if (res.app?.update)
|
||||
push(found, `Dawnline ${res.app.latest}`);
|
||||
if (res.amneziawg?.update && res.amneziawg.installed)
|
||||
push(found, `AmneziaWG ${res.amneziawg.latest}`);
|
||||
if (res.packages?.updates)
|
||||
push(found, `${res.packages.updates} system package${res.packages.updates == 1 ? '' : 's'}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
/** 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;
|
||||
function run_checks(which) {
|
||||
let res = {};
|
||||
for (let name in which) {
|
||||
phase(`Checking ${WHO[name]}`);
|
||||
try {
|
||||
res[name] = CHECKS[name](ctx);
|
||||
}
|
||||
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) {
|
||||
log(`Error: ${e.message}`);
|
||||
res[name] = { error: e.message, status: '' };
|
||||
}
|
||||
}
|
||||
catch (e) {}
|
||||
return best;
|
||||
save_check(res);
|
||||
return res;
|
||||
}
|
||||
|
||||
function awg_installed() {
|
||||
let r = {};
|
||||
for (let p in AWG_PKGS)
|
||||
r[p] = pkg_version(p);
|
||||
return r;
|
||||
/** One line in Activity per new finding (the same finding is not repeated). */
|
||||
function note_found(res, st, auto) {
|
||||
let found = found_in(res);
|
||||
let sig = join(', ', found);
|
||||
if (length(found) && sig != st.announced) {
|
||||
if (auto)
|
||||
slog('dawnline', 'info', `updates available · ${sig}`, null, 'Components');
|
||||
upd.history_add({ kind: 'found', items: found, auto });
|
||||
}
|
||||
st.announced = sig;
|
||||
}
|
||||
|
||||
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' };
|
||||
}
|
||||
/* ---------- installs ---------- */
|
||||
|
||||
/** A line in the service log for each finished update (Dawnline's own is logged by the new agent). */
|
||||
function log_update(name, r) {
|
||||
let how = job.auto ? ' automatically' : '';
|
||||
if (name == 'amneziawg') {
|
||||
let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg'];
|
||||
slog('awg', 'up', b && a && b != a ? `updated${how} · ${b} → ${a}`
|
||||
: `installed the ${r?.build ?? ''} build${a ? ' · ' + a : ''}`, null, 'AmneziaWG');
|
||||
}
|
||||
else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ]))
|
||||
slog('dawnline', 'up', `updated${how} · ${join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])}`, null, 'System packages');
|
||||
}
|
||||
|
||||
function split_target(w) {
|
||||
let i = index(w, ':'), at = index(w, '@');
|
||||
let cut = i < 0 ? at : at < 0 || i < at ? i : at;
|
||||
if (cut < 0)
|
||||
return [ w, null ];
|
||||
return [ substr(w, 0, cut), substr(w, cut + (substr(w, cut, 1) == ':' ? 1 : 0)) ];
|
||||
}
|
||||
|
||||
function app_status(installed, latest) {
|
||||
if (!latest)
|
||||
return 'latest';
|
||||
let c = upd.version_cmp(installed, latest);
|
||||
return c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
|
||||
}
|
||||
|
||||
function install(what) {
|
||||
job.result ??= {};
|
||||
for (let w in what) {
|
||||
let t = split_target(w), name = t[0], arg = t[1];
|
||||
if (!INSTALLS[name])
|
||||
die(`Unknown component ${name}`);
|
||||
job.current = name;
|
||||
phase(`Updating ${WHO[name]}`);
|
||||
let r = INSTALLS[name](ctx, arg);
|
||||
job.result[name] = r;
|
||||
log_update(name, r);
|
||||
// Installed components are current now: no stale "Update available".
|
||||
let c = checks_file();
|
||||
if (name == 'pkgs' && r.check)
|
||||
save_check({ packages: r.check });
|
||||
else if (name == 'app' && r.to && c.app) {
|
||||
let s = app_status(r.to, c.app.latest);
|
||||
save_check({ app: { ...c.app, installed: r.to, update: s == 'outdated', status: s } });
|
||||
}
|
||||
sources[id] = s2;
|
||||
else if (name == 'amneziawg' && r.after)
|
||||
save_check({ amneziawg: { ...(c.amneziawg ?? {}), installed: r.after['amneziawg-tools'], packages: r.after,
|
||||
current: r.build ?? c.amneziawg?.current, update: false, status: 'latest' } });
|
||||
upd.history_add({ kind: 'install', component: w, from: r.from, to: r.to, state: 'done', auto: job.auto,
|
||||
took: time() - job.started });
|
||||
delete job.current;
|
||||
}
|
||||
// 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) {
|
||||
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
|
||||
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];
|
||||
}
|
||||
/** Settings → Updates: check when due, install what is allowed (scheduled or right away). */
|
||||
function auto() {
|
||||
let st = upd.auto_state();
|
||||
let what = upd.due(POL, st);
|
||||
if (!what)
|
||||
return;
|
||||
let now = time();
|
||||
let res;
|
||||
if (what == 'check' || now - (st.check ?? 0) >= 3600) {
|
||||
res = run_checks(upd.TARGETS);
|
||||
st.check = now;
|
||||
note_found(res, st, true);
|
||||
}
|
||||
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;
|
||||
res = checks_file();
|
||||
if (what == 'install')
|
||||
upd.mark_day(POL, st, now);
|
||||
upd.auto_save(st);
|
||||
if (!POL.auto || (what != 'install' && POL.mode != 'immediate'))
|
||||
return;
|
||||
let todo = [];
|
||||
// Packages first, Dawnline last: it restarts rpcd and itself.
|
||||
if (index(POL.targets, 'packages') >= 0 && res.packages?.updates) {
|
||||
let names = filter(keys(res.packages.pkgs ?? {}), (p) => res.packages.pkgs[p].latest || length(res.packages.pkgs[p].with ?? []));
|
||||
if (length(names))
|
||||
push(todo, `pkgs:${join(',', names)}`);
|
||||
}
|
||||
let a = res.amneziawg;
|
||||
if (index(POL.targets, 'amneziawg') >= 0 && a?.update && a.installed) {
|
||||
// Only the same build, same generation: anything else needs a person to decide.
|
||||
if (a.current && !a.gen_change)
|
||||
push(todo, `amneziawg:${a.current}${a.ru ? ':ru' : ''}`);
|
||||
else
|
||||
slog('awg', 'info', `${a.latest ?? 'a new build'} needs a manual switch in Components`, null, 'AmneziaWG');
|
||||
}
|
||||
if (index(POL.targets, 'app') >= 0 && res.app?.update)
|
||||
push(todo, 'app');
|
||||
if (!length(todo))
|
||||
return;
|
||||
quiet = false;
|
||||
job.action = 'install';
|
||||
job.component = join(' ', todo);
|
||||
job.auto = true;
|
||||
job.log = [];
|
||||
log(`Automatic update: ${join(', ', todo)}`);
|
||||
install(todo);
|
||||
}
|
||||
|
||||
// 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 };
|
||||
/** The restarts the job asked for, in one go, after its final state is saved. */
|
||||
function restarts() {
|
||||
let cmds = [];
|
||||
if (after.app)
|
||||
push(cmds, '/etc/init.d/rpcd reload');
|
||||
else if (after.apply)
|
||||
push(cmds, '/usr/bin/dawnline apply');
|
||||
if (after.uhttpd)
|
||||
push(cmds, '/etc/init.d/uhttpd restart');
|
||||
if (after.app || after.apply || after.uhttpd)
|
||||
push(cmds, '/etc/init.d/dawnline restart');
|
||||
if (length(cmds))
|
||||
system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`);
|
||||
}
|
||||
|
||||
/* ---------- main ---------- */
|
||||
|
||||
const CHECKS = { app: check_app, amneziawg: check_awg, packages: check_pkgs };
|
||||
const INSTALLS = { app: install_app, amneziawg: install_awg, pkgs: install_pkgs };
|
||||
const UPDATE_WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages' };
|
||||
|
||||
/** A line in the service log for each finished update (nothing when there was nothing to do). */
|
||||
function log_update(name, r) {
|
||||
// Dawnline's own update is logged by the new agent when it starts (also after install.sh).
|
||||
if (name == 'amneziawg') {
|
||||
let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg'];
|
||||
slog('awg', 'up', b && a && b != a ? `updated · ${b} → ${a}` : `installed the ${AWG_SOURCES[r?.build]?.label ?? r?.build} build${a ? ' · ' + a : ''}`,
|
||||
null, 'AmneziaWG');
|
||||
}
|
||||
else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ]))
|
||||
slog('dawnline', 'up', `updated · ${join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])}`, null, 'System packages');
|
||||
ensure_dir(RUN_DIR);
|
||||
// One job at a time (LuCI refuses a second one; an automatic run just skips its turn).
|
||||
let LOCK = null;
|
||||
for (let i = 0; i < 10 && !LOCK; i++) {
|
||||
LOCK = upd.try_lock();
|
||||
if (!LOCK)
|
||||
system('usleep 100000 2>/dev/null || sleep 1');
|
||||
}
|
||||
|
||||
|
||||
if (!fs.access(STATE_DIR))
|
||||
fs.mkdir(STATE_DIR, 0o755);
|
||||
if (!LOCK)
|
||||
exit(0);
|
||||
fs.mkdir(ctx.work, 0o700);
|
||||
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);
|
||||
log_update(name, job.result[name]);
|
||||
}
|
||||
let which = job.component ? [ job.component ] : upd.TARGETS;
|
||||
for (let w in which)
|
||||
if (!CHECKS[w])
|
||||
die(`Unknown component ${w}`);
|
||||
job.result = run_checks(which);
|
||||
let st = upd.auto_state();
|
||||
note_found(job.result, st, false);
|
||||
if (length(which) == length(upd.TARGETS))
|
||||
st.check = time();
|
||||
upd.auto_save(st);
|
||||
}
|
||||
else if (job.action == 'install')
|
||||
install([ job.component ]);
|
||||
else if (job.action == 'auto')
|
||||
auto();
|
||||
else
|
||||
die('Usage: updater check | install app|amneziawg[:build[:ru]]|pkgs:<names>|all');
|
||||
die('Usage: updater check [app|amneziawg|packages] | install <what> | auto');
|
||||
job.state = 'done';
|
||||
phase('Finished');
|
||||
}
|
||||
catch (e) {
|
||||
quiet = false;
|
||||
job.state = 'failed';
|
||||
job.error = e.message;
|
||||
log(`Error: ${e.message}`);
|
||||
if (job.action == 'install') {
|
||||
let name = split(job.component, ':')[0];
|
||||
slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', 'update failed', e.message, UPDATE_WHO[name] ?? 'Dawnline');
|
||||
let name = job.current ?? split_target(split(job.component ?? '', ' ')[0])[0];
|
||||
if (job.action != 'check') {
|
||||
slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', `${job.auto ? 'automatic ' : ''}update failed`, e.message, WHO[name] ?? 'Dawnline');
|
||||
upd.history_add({ kind: 'install', component: name, from: job.from, to: job.to, state: 'failed', auto: job.auto, error: e.message,
|
||||
took: time() - job.started });
|
||||
}
|
||||
else
|
||||
upd.history_add({ kind: 'error', component: job.component ?? 'all', state: 'failed', error: e.message });
|
||||
}
|
||||
|
||||
run(`rm -rf ${WORK_DIR}`);
|
||||
system(`rm -rf '${ctx.work}'`);
|
||||
job.finished = time();
|
||||
delete job.current;
|
||||
save();
|
||||
restarts();
|
||||
@@ -1,6 +1,6 @@
|
||||
"use strict";(()=>{var rt=Object.create;var Pe=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var lt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ct=(t,e,a,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let v of st(e))!ot.call(t,v)&&v!==a&&Pe(t,v,{get:()=>e[v],enumerable:!(i=at(e,v))||i.enumerable});return t};var ut=(t,e,a)=>(a=t!=null?rt(it(t)):{},ct(e||!t||!t.__esModule?Pe(a,"default",{value:t,enumerable:!0}):a,t));var Ge=lt((Ke,Ue)=>{"use strict";var Oe=(function(){var t=function(M,k){var b=236,w=17,l=M,m=a[k],s=null,r=0,y=null,f=[],g={},T=function(c,u){r=l*4+17,s=(function(o){for(var d=new Array(o),p=0;p<o;p+=1){d[p]=new Array(o);for(var x=0;x<o;x+=1)d[p][x]=null}return d})(r),E(0,0),E(r-7,0),E(0,r-7),q(),H(),Q(c,u),l>=7&&z(c),y==null&&(y=tt(l,m,f)),W(y,u)},E=function(c,u){for(var o=-1;o<=7;o+=1)if(!(c+o<=-1||r<=c+o))for(var d=-1;d<=7;d+=1)u+d<=-1||r<=u+d||(0<=o&&o<=6&&(d==0||d==6)||0<=d&&d<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=d&&d<=4?s[c+o][u+d]=!0:s[c+o][u+d]=!1)},P=function(){for(var c=0,u=0,o=0;o<8;o+=1){T(!0,o);var d=v.getLostPoint(g);(o==0||c>d)&&(c=d,u=o)}return u},H=function(){for(var c=8;c<r-8;c+=1)s[c][6]==null&&(s[c][6]=c%2==0);for(var u=8;u<r-8;u+=1)s[6][u]==null&&(s[6][u]=u%2==0)},q=function(){for(var c=v.getPatternPosition(l),u=0;u<c.length;u+=1)for(var o=0;o<c.length;o+=1){var d=c[u],p=c[o];if(s[d][p]==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?s[d+x][p+C]=!0:s[d+x][p+C]=!1}},z=function(c){for(var u=v.getBCHTypeNumber(l),o=0;o<18;o+=1){var d=!c&&(u>>o&1)==1;s[Math.floor(o/3)][o%3+r-8-3]=d}for(var o=0;o<18;o+=1){var d=!c&&(u>>o&1)==1;s[o%3+r-8-3][Math.floor(o/3)]=d}},Q=function(c,u){for(var o=m<<3|u,d=v.getBCHTypeInfo(o),p=0;p<15;p+=1){var x=!c&&(d>>p&1)==1;p<6?s[p][8]=x:p<8?s[p+1][8]=x:s[r-15+p][8]=x}for(var p=0;p<15;p+=1){var x=!c&&(d>>p&1)==1;p<8?s[8][r-p-1]=x:p<9?s[8][15-p-1+1]=x:s[8][15-p-1]=x}s[r-8][8]=!c},W=function(c,u){for(var o=-1,d=r-1,p=7,x=0,C=v.getMaskFunction(u),_=r-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var R=0;R<2;R+=1)if(s[d][_-R]==null){var K=!1;x<c.length&&(K=(c[x]>>>p&1)==1);var L=C(d,_-R);L&&(K=!K),s[d][_-R]=K,p-=1,p==-1&&(x+=1,p=7)}if(d+=o,d<0||r<=d){d-=o,o=-o;break}}},ae=function(c,u){for(var o=0,d=0,p=0,x=new Array(u.length),C=new Array(u.length),_=0;_<u.length;_+=1){var R=u[_].dataCount,K=u[_].totalCount-R;d=Math.max(d,R),p=Math.max(p,K),x[_]=new Array(R);for(var L=0;L<x[_].length;L+=1)x[_][L]=255&c.getBuffer()[L+o];o+=R;var Y=v.getErrorCorrectPolynomial(K),j=A(x[_],Y.getLength()-1),De=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var L=0;L<C[_].length;L+=1){var Be=L+De.getLength()-C[_].length;C[_][L]=Be>=0?De.getAt(Be):0}}for(var $e=0,L=0;L<u.length;L+=1)$e+=u[L].totalCount;for(var me=new Array($e),he=0,L=0;L<d;L+=1)for(var _=0;_<u.length;_+=1)L<x[_].length&&(me[he]=x[_][L],he+=1);for(var L=0;L<p;L+=1)for(var _=0;_<u.length;_+=1)L<C[_].length&&(me[he]=C[_][L],he+=1);return me},tt=function(c,u,o){for(var d=$.getRSBlocks(c,u),p=D(),x=0;x<o.length;x+=1){var C=o[x];p.put(C.getMode(),4),p.put(C.getLength(),v.getLengthInBits(C.getMode(),c)),C.write(p)}for(var _=0,x=0;x<d.length;x+=1)_+=d[x].dataCount;if(p.getLengthInBits()>_*8)throw"code length overflow. ("+p.getLengthInBits()+">"+_*8+")";for(p.getLengthInBits()+4<=_*8&&p.put(0,4);p.getLengthInBits()%8!=0;)p.putBit(!1);for(;!(p.getLengthInBits()>=_*8||(p.put(b,8),p.getLengthInBits()>=_*8));)p.put(w,8);return ae(p,d)};g.addData=function(c,u){u=u||"Byte";var o=null;switch(u){case"Numeric":o=B(c);break;case"Alphanumeric":o=F(c);break;case"Byte":o=J(c);break;case"Kanji":o=U(c);break;default:throw"mode:"+u}f.push(o),y=null},g.isDark=function(c,u){if(c<0||r<=c||u<0||r<=u)throw c+","+u;return s[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),o=D(),d=0;d<f.length;d++){var p=f[d];o.put(p.getMode(),4),o.put(p.getLength(),v.getLengthInBits(p.getMode(),c)),p.write(o)}for(var x=0,d=0;d<u.length;d++)x+=u[d].dataCount;if(o.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 o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+u+"px;",o+='">',o+="<tbody>";for(var d=0;d<g.getModuleCount();d+=1){o+="<tr>";for(var p=0;p<g.getModuleCount();p+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+c+"px;",o+=" height: "+c+"px;",o+=" background-color: ",o+=g.isDark(d,p)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(c,u,o,d){var p={};typeof arguments[0]=="object"&&(p=arguments[0],c=p.cellSize,u=p.margin,o=p.alt,d=p.title),c=c||2,u=typeof u=="undefined"?c*4:u,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
|
||||
`}return o%2&&c>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(c,u){if(c=c||1,c<2)return nt(u);c-=1,u=typeof u=="undefined"?c*2:u;var o=g.getModuleCount()*c+u*2,d=u,p=o-u,x,C,_,R,K=Array(c+1).join("██"),L=Array(c+1).join(" "),Y="",j="";for(x=0;x<o;x+=1){for(_=Math.floor((x-d)/c),j="",C=0;C<o;C+=1)R=1,d<=C&&C<p&&d<=x&&x<p&&g.isDark(_,Math.floor((C-d)/c))&&(R=0),j+=R?K:L;for(_=0;_<c;_+=1)Y+=j+`
|
||||
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(c,u){u=u||2;for(var o=g.getModuleCount(),d=0;d<o;d++)for(var p=0;p<o;p++)c.fillStyle=g.isDark(d,p)?"black":"white",c.fillRect(d*u,p*u,u,u)},g};t.stringToBytesFuncs={default:function(M){for(var k=[],b=0;b<M.length;b+=1){var w=M.charCodeAt(b);k.push(w&255)}return k}},t.stringToBytes=t.stringToBytesFuncs.default,t.createStringToBytes=function(M,k){var b=(function(){for(var l=I(M),m=function(){var H=l.read();if(H==-1)throw"eof";return H},s=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,s+=1}if(s!=k)throw s+" != "+k;return r})(),w=63;return function(l){for(var m=[],s=0;s<l.length;s+=1){var r=l.charCodeAt(s);if(r<128)m.push(r);else{var y=b[l.charAt(s)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(w)}}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},i={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,b=7973,w=21522,l={},m=function(s){for(var r=0;s!=0;)r+=1,s>>>=1;return r};return l.getBCHTypeInfo=function(s){for(var r=s<<10;m(r)-m(k)>=0;)r^=k<<m(r)-m(k);return(s<<10|r)^w},l.getBCHTypeNumber=function(s){for(var r=s<<12;m(r)-m(b)>=0;)r^=b<<m(r)-m(b);return s<<12|r},l.getPatternPosition=function(s){return M[s-1]},l.getMaskFunction=function(s){switch(s){case i.PATTERN000:return function(r,y){return(r+y)%2==0};case i.PATTERN001:return function(r,y){return r%2==0};case i.PATTERN010:return function(r,y){return y%3==0};case i.PATTERN011:return function(r,y){return(r+y)%3==0};case i.PATTERN100:return function(r,y){return(Math.floor(r/2)+Math.floor(y/3))%2==0};case i.PATTERN101:return function(r,y){return r*y%2+r*y%3==0};case i.PATTERN110:return function(r,y){return(r*y%2+r*y%3)%2==0};case i.PATTERN111:return function(r,y){return(r*y%3+(r+y)%2)%2==0};default:throw"bad maskPattern:"+s}},l.getErrorCorrectPolynomial=function(s){for(var r=A([1],0),y=0;y<s;y+=1)r=r.multiply(A([1,h.gexp(y)],0));return r},l.getLengthInBits=function(s,r){if(1<=r&&r<10)switch(s){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:"+s}else if(r<27)switch(s){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:"+s}else if(r<41)switch(s){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:"+s}else throw"type:"+r},l.getLostPoint=function(s){for(var r=s.getModuleCount(),y=0,f=0;f<r;f+=1)for(var g=0;g<r;g+=1){for(var T=0,E=s.isDark(f,g),P=-1;P<=1;P+=1)if(!(f+P<0||r<=f+P))for(var H=-1;H<=1;H+=1)g+H<0||r<=g+H||P==0&&H==0||E==s.isDark(f+P,g+H)&&(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;s.isDark(f,g)&&(q+=1),s.isDark(f+1,g)&&(q+=1),s.isDark(f,g+1)&&(q+=1),s.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)s.isDark(f,g)&&!s.isDark(f,g+1)&&s.isDark(f,g+2)&&s.isDark(f,g+3)&&s.isDark(f,g+4)&&!s.isDark(f,g+5)&&s.isDark(f,g+6)&&(y+=40);for(var g=0;g<r;g+=1)for(var f=0;f<r-6;f+=1)s.isDark(f,g)&&!s.isDark(f+1,g)&&s.isDark(f+2,g)&&s.isDark(f+3,g)&&s.isDark(f+4,g)&&!s.isDark(f+5,g)&&s.isDark(f+6,g)&&(y+=40);for(var z=0,g=0;g<r;g+=1)for(var f=0;f<r;f+=1)s.isDark(f,g)&&(z+=1);var Q=Math.abs(100*z/r/r-50)/5;return y+=Q*10,y},l})(),h=(function(){for(var M=new Array(256),k=new Array(256),b=0;b<8;b+=1)M[b]=1<<b;for(var b=8;b<256;b+=1)M[b]=M[b-4]^M[b-5]^M[b-6]^M[b-8];for(var b=0;b<255;b+=1)k[M[b]]=b;var w={};return w.glog=function(l){if(l<1)throw"glog("+l+")";return k[l]},w.gexp=function(l){for(;l<0;)l+=255;for(;l>=256;)l-=255;return M[l]},w})();function A(M,k){if(typeof M.length=="undefined")throw M.length+"/"+k;var b=(function(){for(var l=0;l<M.length&&M[l]==0;)l+=1;for(var m=new Array(M.length-l+k),s=0;s<M.length-l;s+=1)m[s]=M[s+l];return m})(),w={};return w.getAt=function(l){return b[l]},w.getLength=function(){return b.length},w.multiply=function(l){for(var m=new Array(w.getLength()+l.getLength()-1),s=0;s<w.getLength();s+=1)for(var r=0;r<l.getLength();r+=1)m[s+r]^=h.gexp(h.glog(w.getAt(s))+h.glog(l.getAt(r)));return A(m,0)},w.mod=function(l){if(w.getLen
Line truncated
|
||||
`),hostName:h,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(A),port:String(a.port),protocol_version:i.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:h};return a.dns[0]&&($.dns1=a.dns[0]),a.dns[1]&&($.dns2=a.dns[1]),$}function gt(t){let e="";for(let a=0;a<t.length;a+=32768)e+=String.fromCharCode(...t.subarray(a,a+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function mt(t){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let a=new e.Blob([t]).stream().pipeThrough(new e.CompressionStream("deflate")),i=new Uint8Array(await new e.Response(a).arrayBuffer()),v=new Uint8Array(4+i.length);return new DataView(v.buffer).setUint32(0,t.length,!1),v.set(i,4),v}catch{return null}}async function Me(t,e,a=!0){let i=new TextEncoder().encode(JSON.stringify(pt(t,e))),v=a?await mt(i):null;return`vpn://${gt(v!=null?v:i)}`}function n(t,e={},...a){let i=document.createElement(t);for(let[h,A]of Object.entries(e))A==null||A===!1||(h.startsWith("on")&&typeof A=="function"?i.addEventListener(h.slice(2),A):h==="class"?i.className=String(A):A===!0?i.setAttribute(h,""):i.setAttribute(h,String(A)));let v=h=>{h==null||h===!1||(Array.isArray(h)?h.forEach(v):i.appendChild(typeof h=="string"?document.createTextNode(h):h))};return a.forEach(v),i}function O(t){let e=n("span",{class:"ic"});return e.innerHTML=He(t,"ic-svg"),e}var yt='<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>',Le=document.getElementById("app"),je,pe=(je=Le.dataset.base)!=null?je:"",bt=Le.dataset.title||"Dawnline",Ae=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,Ve=0,wt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(pe)?pe.slice(1):"",_e=class extends Error{constructor(a,i){super(i);this.status=a}};async function ne(t,e){var v;let a=await fetch(`${pe}/api/${t}`,{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"}),i=null;try{i=await a.json()}catch{}if(!a.ok)throw new _e(a.status,(v=i==null?void 0:i.error)!=null?v:`Request failed (${a.status})`);return i}function te(t,e=!1){let a=n("div",{class:`toast${e?" bad":""}`,role:"status"},t);document.body.appendChild(a),requestAnimationFrame(()=>a.classList.add("show")),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>a.remove(),300)},2600)}async function le(t,e="Copied"){try{await navigator.clipboard.writeText(t)}catch{let a=n("textarea",{class:"offscreen"},t);document.body.appendChild(a),a.select(),document.execCommand("copy"),a.remove()}te(e)}function ze(t,e){let a=URL.createObjectURL(new Blob([e],{type:"application/octet-stream"})),i=n("a",{href:a,download:t,class:"offscreen"});document.body.appendChild(i),i.click(),setTimeout(()=>{URL.revokeObjectURL(a),i.remove()},1e3)}var Z=null;function Je(t,e){let a=i=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...e().map((v,h)=>n("div",{class:h?"muted":"tip-title"},v))),Z.style.display="",Z.style.left=`${i.clientX}px`,Z.style.top=`${i.clientY-10}px`};t.addEventListener("mouseenter",a),t.addEventListener("mousemove",a),t.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function xt(t){let e=Math.max(1,...t),a=n("div",{class:"spark"});return t.forEach((i,v)=>{let h=n("i",{class:i?"":"zero"});h.style.height=`${Math.max(8,i/e*100)}%`;let A=t.length-1-v,$=new Date(Date.now()-A*864e5);Je(h,()=>[A===0?"Today":A===1?"Yesterday":$.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ie(i)]),a.appendChild(h)}),a}var oe=null,ce=null;function ee(t=!1){if(!oe)return;let e=oe;if(oe=null,document.body.classList.remove("locked"),ce==null||ce(),ce=null,t){e.remove();return}e.classList.remove("open"),setTimeout(()=>e.remove(),250)}function fe(t,e,...a){let i=!!oe;ee(!0);let v=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":t},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},t),e?n("span",{class:"muted s"},e):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},O("x"))),n("div",{class:"sheet-body"},...a)),h=n("div",{class:"sheet",onclick:A=>{A.target===h&&ee()}},v);return document.body.appendChild(h),document.body.classList.add("locked"),i?h.classList.add("open"):requestAnimationFrame(()=>h.classList.add("open")),oe=h,v}document.addEventListener("keydown",t=>{t.key==="Escape"&&(ge(),ee())});var X=null;function ge(){X==null||X.remove(),X=null}document.addEventListener("click",t=>{X&&!X.contains(t.target)&&ge()});function Mt(t,e){ge();let a=n("
Line truncated
|
||||
`).flatMap((h,A)=>A?[`
|
||||
`,Ye(h,e)]:[Ye(h,e)])),v=n("button",{class:"btn small",onclick:h=>{h.preventDefault(),e=!e,v.replaceChildren(O(e?"x":"key"),n("span",{},e?"Hide key":"Show key")),i()}},O("key"),n("span",{},"Show key"));return i(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},t.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>ze(t.filename,t.conf)},O("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},O("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),v,n("button",{class:"btn small",onclick:h=>{h.preventDefault(),le(t.conf,"Configuration copied")}},O("copy"),n("span",{},"Copy"))),a))}async function ue(t,e,a){let i=a!=null?a:await Ee(t);if(!i)return;let v=await Me(i,`${i.server} · ${i.name}`),h=Ae(),A={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:v},O("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let I=n("div",{class:"qr"});return I.innerHTML=Fe(i.conf),n("div",{class:"pane center"},I,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},v),n("button",{class:"btn small",onclick:()=>le(v,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Bt(i)},$=h?["app","qr","key","file"]:["qr","key","file"],D={app:"Open in app",qr:"QR code",key:"Key",file:"File"},B=n("div",{class:"tab-body"}),F=n("div",{class:"tabs",role:"tablist"}),J=I=>{F.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===I)),B.replaceChildren(A[I]())};for(let I of $)F.appendChild(n("button",{role:"tab","data-id":I,onclick:()=>J(I)},D[I]));J(e&&$.includes(e)?e:$[0]);let U=n("div",{class:"waiting"}),N=I=>{I!=null&&I.online?U.replaceChildren(n("span",{class:"ok"},`${t.name} is connected`)):I!=null&&I.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${ye(I.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};N(t);let G=window.setInterval(async()=>{try{let I=await ne("state");S=I,N(I.person.devices.find(re=>re.id===t.id))}catch{}},5e3);fe(t.handshake?`Connect ${t.name}`:`${t.name} is ready`,h?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",F,B,U),ce=()=>{clearInterval(G),S&&de(S)}}function $t(t){let e=n("input",{type:"text",value:t.name,maxlength:48,"aria-label":"Device name"});fe(`Rename ${t.name}`,null,n("form",{class:"stack gap",onsubmit:async a=>{a.preventDefault();try{S=(await ne(`devices/${t.id}`,{action:"rename",name:e.value})).state,ee(),de(S),te("Renamed")}catch(i){te(i.message,!0)}}},e,n("button",{class:"btn primary block",type:"submit"},"Save"))),setTimeout(()=>e.select(),50)}function Pt(t,e){let a=e.here===t.id;fe(`New keys for ${t.name}?`,null,n("p",{class:"muted"},a?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:async()=>{try{let i=await ne(`devices/${t.id}`,{action:"rotate"});S=i.state,de(S),ue(t,void 0,i.config)}catch(i){te(i.message,!0)}}},"New keys")))}function St(t){fe(`Remove ${t.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:async()=>{try{S=(await ne(`devices/${t.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(e){te(e.message,!0)}}},"Remove")))}var V=navigator.userAgent,Ze=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function ke(){return Ze||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Rt=[[/^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"]],Ce="",Nt=(async()=>{var e;let t=navigator.userAgentData;if(!t||!/
Line truncated
|
||||
"use strict";(()=>{var ct=Object.create;var He=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var ht=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var pt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ut(t))!dt.call(e,u)&&u!==r&&He(e,u,{get:()=>t[u],enumerable:!(s=lt(t,u))||s.enumerable});return e};var vt=(e,t,r)=>(r=e!=null?ct(ft(e)):{},pt(t||!e||!e.__esModule?He(r,"default",{value:e,enumerable:!0}):r,e));var je=ht((Ve,Ye)=>{"use strict";var qe=(function(){var e=function(M,A){var b=236,w=17,c=M,m=r[A],i=null,a=0,y=null,d=[],g={},L=function(l,f){a=c*4+17,i=(function(o){for(var h=new Array(o),v=0;v<o;v+=1){h[v]=new Array(o);for(var x=0;x<o;x+=1)h[v][x]=null}return h})(a),D(0,0),D(a-7,0),D(0,a-7),G(),I(),Q(l,f),c>=7&&z(l),y==null&&(y=st(c,m,d)),W(y,f)},D=function(l,f){for(var o=-1;o<=7;o+=1)if(!(l+o<=-1||a<=l+o))for(var h=-1;h<=7;h+=1)f+h<=-1||a<=f+h||(0<=o&&o<=6&&(h==0||h==6)||0<=h&&h<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=h&&h<=4?i[l+o][f+h]=!0:i[l+o][f+h]=!1)},P=function(){for(var l=0,f=0,o=0;o<8;o+=1){L(!0,o);var h=u.getLostPoint(g);(o==0||l>h)&&(l=h,f=o)}return f},I=function(){for(var l=8;l<a-8;l+=1)i[l][6]==null&&(i[l][6]=l%2==0);for(var f=8;f<a-8;f+=1)i[6][f]==null&&(i[6][f]=f%2==0)},G=function(){for(var l=u.getPatternPosition(c),f=0;f<l.length;f+=1)for(var o=0;o<l.length;o+=1){var h=l[f],v=l[o];if(i[h][v]==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[h+x][v+C]=!0:i[h+x][v+C]=!1}},z=function(l){for(var f=u.getBCHTypeNumber(c),o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;i[Math.floor(o/3)][o%3+a-8-3]=h}for(var o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;i[o%3+a-8-3][Math.floor(o/3)]=h}},Q=function(l,f){for(var o=m<<3|f,h=u.getBCHTypeInfo(o),v=0;v<15;v+=1){var x=!l&&(h>>v&1)==1;v<6?i[v][8]=x:v<8?i[v+1][8]=x:i[a-15+v][8]=x}for(var v=0;v<15;v+=1){var x=!l&&(h>>v&1)==1;v<8?i[8][a-v-1]=x:v<9?i[8][15-v-1+1]=x:i[8][15-v-1]=x}i[a-8][8]=!l},W=function(l,f){for(var o=-1,h=a-1,v=7,x=0,C=u.getMaskFunction(f),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var N=0;N<2;N+=1)if(i[h][_-N]==null){var K=!1;x<l.length&&(K=(l[x]>>>v&1)==1);var T=C(h,_-N);T&&(K=!K),i[h][_-N]=K,v-=1,v==-1&&(x+=1,v=7)}if(h+=o,h<0||a<=h){h-=o,o=-o;break}}},ae=function(l,f){for(var o=0,h=0,v=0,x=new Array(f.length),C=new Array(f.length),_=0;_<f.length;_+=1){var N=f[_].dataCount,K=f[_].totalCount-N;h=Math.max(h,N),v=Math.max(v,K),x[_]=new Array(N);for(var T=0;T<x[_].length;T+=1)x[_][T]=255&l.getBuffer()[T+o];o+=N;var Y=u.getErrorCorrectPolynomial(K),j=k(x[_],Y.getLength()-1),Pe=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var T=0;T<C[_].length;T+=1){var Ne=T+Pe.getLength()-C[_].length;C[_][T]=Ne>=0?Pe.getAt(Ne):0}}for(var Re=0,T=0;T<f.length;T+=1)Re+=f[T].totalCount;for(var be=new Array(Re),he=0,T=0;T<h;T+=1)for(var _=0;_<f.length;_+=1)T<x[_].length&&(be[he]=x[_][T],he+=1);for(var T=0;T<v;T+=1)for(var _=0;_<f.length;_+=1)T<C[_].length&&(be[he]=C[_][T],he+=1);return be},st=function(l,f,o){for(var h=$.getRSBlocks(l,f),v=E(),x=0;x<o.length;x+=1){var C=o[x];v.put(C.getMode(),4),v.put(C.getLength(),u.getLengthInBits(C.getMode(),l)),C.write(v)}for(var _=0,x=0;x<h.length;x+=1)_+=h[x].dataCount;if(v.getLengthInBits()>_*8)throw"code length overflow. ("+v.getLengthInBits()+">"+_*8+")";for(v.getLengthInBits()+4<=_*8&&v.put(0,4);v.getLengthInBits()%8!=0;)v.putBit(!1);for(;!(v.getLengthInBits()>=_*8||(v.put(b,8),v.getLengthInBits()>=_*8));)v.put(w,8);return ae(v,h)};g.addData=function(l,f){f=f||"Byte";var o=null;switch(f){case"Numeric":o=B(l);break;case"Alphanumeric":o=q(l);break;case"Byte":o=J(l);break;case"Kanji":o=U(l);break;default:throw"mode:"+f}d.push(o),y=null},g.isDark=function(l,f){if(l<0||a<=l||f<0||a<=f)throw l+","+f;return i[l][f]},g.getModuleCount=function(){return a},g.make=function(){if(c<1){for(var l=1;l<40;l++){for(var f=$.getRSBlocks(l,m),o=E(),h=0;h<d.length;h++){var v=d[h];o.put(v.getMode(),4),o.put(v.getLength(),u.getLengthInBits(v.getMode(),l)),v.write(o)}for(var x=0,h=0;h<f.length;h++)x+=f[h].dataCount;if(o.getLengthInBits()<=x*8)break}c=l}L(!1,P())},g.createTableTag=function(l,f){l=l||2,f=typeof f=="undefined"?l*4:f;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+f+"px;",o+='">',o+="<tbody>";for(var h=0;h<g.getModuleCount();h+=1){o+="<tr>";for(var v=0;v<g.getModuleCount();v+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+l+"px;",o+=" height: "+l+"px;",o+=" background-color: ",o+=g.isDark(h,v)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(l,f,o,h){var v={};typeof arguments[0]=="object"&&(v=arguments[0],l=v.cellSize,f=v.margin,o=v.alt,h=v.title),l=l||2,f=typeof f=="undefined"?l*4:f,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
|
||||
`}return o%2&&l>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(l,f){if(l=l||1,l<2)return ot(f);l-=1,f=typeof f=="undefined"?l*2:f;var o=g.getModuleCount()*l+f*2,h=f,v=o-f,x,C,_,N,K=Array(l+1).join("██"),T=Array(l+1).join(" "),Y="",j="";for(x=0;x<o;x+=1){for(_=Math.floor((x-h)/l),j="",C=0;C<o;C+=1)N=1,h<=C&&C<v&&h<=x&&x<v&&g.isDark(_,Math.floor((C-h)/l))&&(N=0),j+=N?K:T;for(_=0;_<l;_+=1)Y+=j+`
|
||||
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(l,f){f=f||2;for(var o=g.getModuleCount(),h=0;h<o;h++)for(var v=0;v<o;v++)l.fillStyle=g.isDark(h,v)?"black":"white",l.fillRect(h*f,v*f,f,f)},g};e.stringToBytesFuncs={default:function(M){for(var A=[],b=0;b<M.length;b+=1){var w=M.charCodeAt(b);A.push(w&255)}return A}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(M,A){var b=(function(){for(var c=H(M),m=function(){var I=c.read();if(I==-1)throw"eof";return I},i=0,a={};;){var y=c.read();if(y==-1)break;var d=m(),g=m(),L=m(),D=String.fromCharCode(y<<8|d),P=g<<8|L;a[D]=P,i+=1}if(i!=A)throw i+" != "+A;return a})(),w=63;return function(c){for(var m=[],i=0;i<c.length;i+=1){var a=c.charCodeAt(i);if(a<128)m.push(a);else{var y=b[c.charAt(i)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(w)}}return m}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},u=(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]],A=1335,b=7973,w=21522,c={},m=function(i){for(var a=0;i!=0;)a+=1,i>>>=1;return a};return c.getBCHTypeInfo=function(i){for(var a=i<<10;m(a)-m(A)>=0;)a^=A<<m(a)-m(A);return(i<<10|a)^w},c.getBCHTypeNumber=function(i){for(var a=i<<12;m(a)-m(b)>=0;)a^=b<<m(a)-m(b);return i<<12|a},c.getPatternPosition=function(i){return M[i-1]},c.getMaskFunction=function(i){switch(i){case s.PATTERN000:return function(a,y){return(a+y)%2==0};case s.PATTERN001:return function(a,y){return a%2==0};case s.PATTERN010:return function(a,y){return y%3==0};case s.PATTERN011:return function(a,y){return(a+y)%3==0};case s.PATTERN100:return function(a,y){return(Math.floor(a/2)+Math.floor(y/3))%2==0};case s.PATTERN101:return function(a,y){return a*y%2+a*y%3==0};case s.PATTERN110:return function(a,y){return(a*y%2+a*y%3)%2==0};case s.PATTERN111:return function(a,y){return(a*y%3+(a+y)%2)%2==0};default:throw"bad maskPattern:"+i}},c.getErrorCorrectPolynomial=function(i){for(var a=k([1],0),y=0;y<i;y+=1)a=a.multiply(k([1,p.gexp(y)],0));return a},c.getLengthInBits=function(i,a){if(1<=a&&a<10)switch(i){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+i}else if(a<27)switch(i){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+i}else if(a<41)switch(i){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+i}else throw"type:"+a},c.getLostPoint=function(i){for(var a=i.getModuleCount(),y=0,d=0;d<a;d+=1)for(var g=0;g<a;g+=1){for(var L=0,D=i.isDark(d,g),P=-1;P<=1;P+=1)if(!(d+P<0||a<=d+P))for(var I=-1;I<=1;I+=1)g+I<0||a<=g+I||P==0&&I==0||D==i.isDark(d+P,g+I)&&(L+=1);L>5&&(y+=3+L-5)}for(var d=0;d<a-1;d+=1)for(var g=0;g<a-1;g+=1){var G=0;i.isDark(d,g)&&(G+=1),i.isDark(d+1,g)&&(G+=1),i.isDark(d,g+1)&&(G+=1),i.isDark(d+1,g+1)&&(G+=1),(G==0||G==4)&&(y+=3)}for(var d=0;d<a;d+=1)for(var g=0;g<a-6;g+=1)i.isDark(d,g)&&!i.isDark(d,g+1)&&i.isDark(d,g+2)&&i.isDark(d,g+3)&&i.isDark(d,g+4)&&!i.isDark(d,g+5)&&i.isDark(d,g+6)&&(y+=40);for(var g=0;g<a;g+=1)for(var d=0;d<a-6;d+=1)i.isDark(d,g)&&!i.isDark(d+1,g)&&i.isDark(d+2,g)&&i.isDark(d+3,g)&&i.isDark(d+4,g)&&!i.isDark(d+5,g)&&i.isDark(d+6,g)&&(y+=40);for(var z=0,g=0;g<a;g+=1)for(var d=0;d<a;d+=1)i.isDark(d,g)&&(z+=1);var Q=Math.abs(100*z/a/a-50)/5;return y+=Q*10,y},c})(),p=(function(){for(var M=new Array(256),A=new Array(256),b=0;b<8;b+=1)M[b]=1<<b;for(var b=8;b<256;b+=1)M[b]=M[b-4]^M[b-5]^M[b-6]^M[b-8];for(var b=0;b<255;b+=1)A[M[b]]=b;var w={};return w.glog=function(c){if(c<1)throw"glog("+c+")";return A[c]},w.gexp=function(c){for(;c<0;)c+=255;for(;c>=256;)c-=255;return M[c]},w})();function k(M,A){if(typeof M.length=="undefined")throw M.length+"/"+A;var b=(function(){for(var c=0;c<M.length&&M[c]==0;)c+=1;for(var m=new Array(M.length-c+A),i=0;i<M.length-c;i+=1)m[i]=M[i+c];return m})(),w={};return w.getAt=function(c){return b[c]},w.getLength=function(){return b.length},w.multiply=function(c){for(var m=new Array(w.getLength()+c.getLength()-1),i=0;i<w.getLength();i+=1)for(var a=0;a<c.getLength();a+=1)m[i+a]^=p.gexp(p.glog(w.getAt(i))+p.glog(c.getAt(a)));return k(m,0)},w.mod=function(c){if(w.getLen
Line truncated
|
||||
`),hostName:p,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(k),port:String(r.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:p};return r.dns[0]&&($.dns1=r.dns[0]),r.dns[1]&&($.dns2=r.dns[1]),$}function kt(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function At(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),s=new Uint8Array(await new t.Response(r).arrayBuffer()),u=new Uint8Array(4+s.length);return new DataView(u.buffer).setUint32(0,e.length,!1),u.set(s,4),u}catch{return null}}async function Ae(e,t,r=!0){let s=new TextEncoder().encode(JSON.stringify(Mt(e,t))),u=r?await At(s):null;return`vpn://${kt(u!=null?u:s)}`}var De=()=>{var e;return(e=S==null?void 0:S.today)!=null?e:pe(new Date)};function n(e,t={},...r){let s=document.createElement(e);for(let[p,k]of Object.entries(t))k==null||k===!1||(p.startsWith("on")&&typeof k=="function"?s.addEventListener(p.slice(2),k):p==="class"?s.className=String(k):k===!0?s.setAttribute(p,""):s.setAttribute(p,String(k)));let u=p=>{p==null||p===!1||(Array.isArray(p)?p.forEach(u):s.appendChild(typeof p=="string"?document.createTextNode(p):p))};return r.forEach(u),s}function O(e){let t=n("span",{class:"ic"});return t.innerHTML=Ge(e,"ic-svg"),t}var _t='<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>',Ee=document.getElementById("app"),Ze,me=(Ze=Ee.dataset.base)!=null?Ze:"",Ct=Ee.dataset.title||"Dawnline",Ce=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,Qe=0,Tt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(me)?me.slice(1):"",Te=class extends Error{constructor(r,s){super(s);this.status=r}};async function ne(e,t){var u;let r=await fetch(`${me}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{}:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),s=null;try{s=await r.json()}catch{}if(!r.ok)throw new Te(r.status,(u=s==null?void 0:s.error)!=null?u:`Request failed (${r.status})`);return s}function te(e,t=!1){let r=n("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),300)},2600)}async function ce(e,t="Copied"){try{await navigator.clipboard.writeText(e)}catch{let r=n("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let s=document.execCommand("copy");if(r.remove(),!s)return te("Copying is blocked here. Select the text and copy it by hand.",!0)}te(t)}function Xe(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),s=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(s),s.click(),setTimeout(()=>{URL.revokeObjectURL(r),s.remove()},1e3)}var Z=null;function et(e,t){let r=s=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...t().map((u,p)=>n("div",{class:p?"muted":"tip-title"},u))),Z.style.display="",Z.style.left=`${s.clientX}px`,Z.style.top=`${s.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function Lt(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((s,u)=>{let p=n("i",{class:s?"":"zero"});p.style.height=`${Math.max(8,s/t*100)}%`;let k=e.length-1-u;et(p,()=>[k===0?"Today":k===1?"Yesterday":ve(Ie(De(),-k)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),se(s)]),r.appendChild(p)}),r}async function Be(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var oe=null,le=null;function ee(e=!1){if(!oe)return;let t=oe;if(oe=null,document.body.classList.remove("locked"),le==null||le(),le=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function fe(e,t,...r){let s=!!oe;ee(!0);let u=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},e),t?n("span",{class:"muted s"},t):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},O("x"))),n("div",{class:"sheet-body"},...r)),p=n("div",{class:"sheet",onclick:k=>{k.target===p&&ee()}},u);return document.body.appendChild(p),document.body.classList.add("locked"),s?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open
Line truncated
|
||||
`).flatMap((p,k)=>k?[`
|
||||
`,We(p,t)]:[We(p,t)])),u=n("button",{class:"btn small",onclick:p=>{p.preventDefault(),t=!t,u.replaceChildren(O(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),s()}},O("key"),n("span",{},"Show key"));return s(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>Xe(e.filename,e.conf)},O("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},O("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),u,n("button",{class:"btn small",onclick:p=>{p.preventDefault(),ce(e.conf,"Configuration copied")}},O("copy"),n("span",{},"Copy"))),r))}async function ue(e,t,r){let s=r!=null?r:await Se(e);if(!s)return;let u=await Ae(s,`${s.server} · ${s.name}`),p=Ce(),k={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:u},O("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=n("div",{class:"qr"});return H.innerHTML=Je(s.conf),n("div",{class:"pane center"},H,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},u),n("button",{class:"btn small",onclick:()=>ce(u,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>It(s)},$=p?["app","qr","key","file"]:["qr","key","file"],E={app:"Open in app",qr:"QR code",key:"Key",file:"File"},B=n("div",{class:"tab-body"}),q=n("div",{class:"tabs",role:"tablist"}),J=H=>{q.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===H)),B.replaceChildren(k[H]())};for(let H of $)q.appendChild(n("button",{role:"tab","data-id":H,onclick:()=>J(H)},E[H]));J(t&&$.includes(t)?t:$[0]);let U=n("div",{class:"waiting"}),R=H=>{H!=null&&H.online?U.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${we(H.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};R(e);let F=window.setInterval(async()=>{try{let H=await ne("state");S=H,R(H.person.devices.find(re=>re.id===e.id))}catch{}},5e3);fe(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",q,B,U),le=()=>{clearInterval(F),S&&de(S)}}function Ot(e){let t=n("input",{type:"text",value:e.name,maxlength:48,"aria-label":"Device name"}),r=n("button",{class:"btn primary block",type:"submit"},"Save");fe(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:s=>{s.preventDefault(),Be(r,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),de(S),te("Renamed")}catch(u){te(u.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function Kt(e,t){let r=t.here===e.id;fe(`New keys for ${e.name}?`,null,n("p",{class:"muted"},r?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:s=>Be(s.currentTarget,async()=>{try{let u=await ne(`devices/${e.id}`,{action:"rotate"});S=u.state,de(S),await ue(e,void 0,u.config)}catch(u){te(u.message,!0)}})},"New keys")))}function Ut(e){fe(`Remove ${e.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:t=>Be(t.currentTarget,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,rt=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function _e(){return rt||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Ft=[[/^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"]
Line truncated
|
||||
@@ -1,368 +1,21 @@
|
||||
#!/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.
|
||||
// Dawnline personal portal as a CGI script: the request handling itself is
|
||||
// dawnline.portal.
|
||||
'use strict';
|
||||
|
||||
import { stdin, stat, unlink, readfile } from 'fs';
|
||||
import {
|
||||
read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, sh_bg, 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';
|
||||
import { stdin } from 'fs';
|
||||
import { serve } from 'dawnline.portal';
|
||||
|
||||
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;
|
||||
let env = {};
|
||||
for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE',
|
||||
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT',
|
||||
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
|
||||
'HTTP_CF_CONNECTING_IP' ])
|
||||
env[k] = getenv(k);
|
||||
|
||||
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];
|
||||
// The device this page was opened from, when it came through the tunnel.
|
||||
let here = null;
|
||||
for (let id, d in m.devices)
|
||||
if (d.person == person.id && d.address == peer)
|
||||
here = id;
|
||||
return {
|
||||
title,
|
||||
person: v,
|
||||
here,
|
||||
server: { name: srv?.name, endpoint: core.endpoint_host(m, srv), device_mesh: !!srv?.device_mesh },
|
||||
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, by: '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 == 'rotate') {
|
||||
if (m.devices[api[1]].disabled)
|
||||
die('The admin has turned this device off.');
|
||||
core.rotate_device(c, m, api[1]);
|
||||
}
|
||||
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, dname: d.name, dkind: d.kind, by: '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];
|
||||
if (b.action == 'rotate') {
|
||||
let d = m.devices[api[1]];
|
||||
live.add_event({ type: 'device_keys', person: person.id, device: d.id, detail: d.name, by: 'portal' });
|
||||
// The device this page came through would lose its tunnel before the
|
||||
// answer gets out: load the new key a moment after answering.
|
||||
if (d.address == peer)
|
||||
sh_bg('sleep 3; /usr/bin/dawnline sync');
|
||||
else
|
||||
apply.sync();
|
||||
core.mark_issued(m, d.id);
|
||||
send_json('200 OK', { ok: true, config: core.client_config(m, d), state: state() });
|
||||
}
|
||||
send_json('200 OK', { ok: true, state: state() });
|
||||
}
|
||||
|
||||
fail('404 Not Found', 'Not found.');
|
||||
serve({
|
||||
env,
|
||||
headers: {},
|
||||
read: (n) => stdin.read(n),
|
||||
write: (s) => print(s),
|
||||
});
|
||||
@@ -70,7 +70,7 @@
|
||||
}
|
||||
},
|
||||
"admin/network/dawnline/updates": {
|
||||
"title": "Updates",
|
||||
"title": "Components",
|
||||
"order": 70,
|
||||
"action": {
|
||||
"type": "view",
|
||||
|
||||
@@ -10,27 +10,23 @@
|
||||
"service_log",
|
||||
"backup_list",
|
||||
"updates_status",
|
||||
"updates_releases",
|
||||
"updates_notes",
|
||||
"updates_changes",
|
||||
"person_usage",
|
||||
"settings_get",
|
||||
"portal_info",
|
||||
"interfaces",
|
||||
"events"
|
||||
]
|
||||
},
|
||||
"uci": [
|
||||
"dawnline",
|
||||
"network",
|
||||
"firewall"
|
||||
]
|
||||
}
|
||||
},
|
||||
"write": {
|
||||
"ubus": {
|
||||
"luci.dawnline": [
|
||||
"*"
|
||||
]
|
||||
},
|
||||
"uci": [
|
||||
"dawnline"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,11 +3,12 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
import { ip2int } from 'dawnline.util';
|
||||
import { ip2int, in_nets } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as view from 'dawnline.view';
|
||||
import * as awg from 'dawnline.awg';
|
||||
|
||||
const STATE_TEXT = {
|
||||
no_server: 'their server is turned off',
|
||||
@@ -30,21 +31,13 @@ function stop(steps, s) {
|
||||
return steps;
|
||||
}
|
||||
|
||||
/** The first of `nets` (IPv4 CIDRs, any prefix) that holds `ip`. */
|
||||
function in_any(ip, nets) {
|
||||
let n = ip2int(ip);
|
||||
if (n == null)
|
||||
return null;
|
||||
for (let c in nets) {
|
||||
let mm = match(c, /^([0-9.]+)\/([0-9]+)$/);
|
||||
let base = mm ? ip2int(mm[1]) : null;
|
||||
if (base == null)
|
||||
continue;
|
||||
let size = 1 << (32 - +mm[2]);
|
||||
if (+mm[2] == 0 || (n >= base - base % size && n < base - base % size + size))
|
||||
return c;
|
||||
}
|
||||
return null;
|
||||
/** The tunnel subnet (of any server) that holds `ip`: never home, whatever routes cover it. */
|
||||
function in_tunnels(m, ip) {
|
||||
let nets = [];
|
||||
for (let id, s in m.servers)
|
||||
for (let t in core.tunnels(s))
|
||||
push(nets, t.subnet);
|
||||
return in_nets(ip, nets);
|
||||
}
|
||||
|
||||
/** "10.0.1.20:445" → [ip, port]; a device id → its address. */
|
||||
@@ -70,10 +63,15 @@ function peer_of(dmp, d) {
|
||||
return dmp.peers[d.public_key];
|
||||
}
|
||||
|
||||
/** What the device sends to the router: its configuration's AllowedIPs. */
|
||||
function routed(m, srv, p, d) {
|
||||
return { nets: awg.allowed_ips(m, srv, p), what: 'Its configuration', list: null };
|
||||
}
|
||||
|
||||
/** The home network (interface) of a server that holds an address. */
|
||||
function home_dev_of(srv, ip, snap) {
|
||||
for (let h in net.server_net(srv, snap).home)
|
||||
if (in_any(ip, h.nets))
|
||||
if (in_nets(ip, h.nets))
|
||||
return h.dev;
|
||||
return null;
|
||||
}
|
||||
@@ -113,12 +111,14 @@ function from_device(m, d, t, states, dmp, snap) {
|
||||
let steps = [ person_ok(m, p, d, states) ];
|
||||
if (!steps[0].ok)
|
||||
return steps;
|
||||
let allowed = core.allowed_ips(m, srv, p);
|
||||
let r = routed(m, srv, p, d);
|
||||
let allowed = r.nets;
|
||||
let via = (ip) => {
|
||||
let hit = in_any(ip, allowed);
|
||||
let hit = in_nets(ip, allowed);
|
||||
let what = r.list ? `${r.what}: ${r.list}` : `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`;
|
||||
return hit
|
||||
? step(true, 'Its configuration sends it through the tunnel', `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`)
|
||||
: step(false, "Its configuration doesn't send it through the tunnel", `AllowedIPs ${join(', ', allowed)}: the device's own network handles it.`);
|
||||
? step(true, `${r.what} sends it to the router`, what)
|
||||
: step(false, `${r.what} doesn't send it to the router`, `${what}: the device's own network handles it.`);
|
||||
};
|
||||
|
||||
// Another device.
|
||||
@@ -164,6 +164,11 @@ function from_device(m, d, t, states, dmp, snap) {
|
||||
return steps;
|
||||
}
|
||||
|
||||
// A tunnel address no device has.
|
||||
let tn = in_tunnels(m, t.ip);
|
||||
if (tn)
|
||||
return stop(steps, step(false, `No device uses ${t.ip}`, `It is in the tunnel network ${tn}.`));
|
||||
|
||||
// Home.
|
||||
let sn = net.server_net(srv, snap);
|
||||
let hdev = home_dev_of(srv, t.ip, snap);
|
||||
@@ -185,7 +190,7 @@ function from_device(m, d, t, states, dmp, snap) {
|
||||
}
|
||||
else {
|
||||
let h = core.person_home(srv, p, snap);
|
||||
if (!in_any(t.ip, h.nets))
|
||||
if (!in_nets(t.ip, h.nets))
|
||||
return stop(steps, step(false, `${t.ip} is in ${hdev}, which ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`));
|
||||
push(steps, step(true, `${t.ip} is in ${hdev}`, h.all ? 'Home access reaches every home network.' : `One of the networks ${p.name} reaches.`));
|
||||
}
|
||||
@@ -195,7 +200,7 @@ function from_device(m, d, t, states, dmp, snap) {
|
||||
}
|
||||
|
||||
// Another private address, or the internet.
|
||||
if (in_any(t.ip, [ '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' ]))
|
||||
if (in_nets(t.ip, [ '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' ]))
|
||||
return stop(steps, step(false, `${t.ip} isn't in ${srv.name}'s home network`, 'Private addresses outside the home network are blocked.'));
|
||||
if (p.access == 'lan')
|
||||
return stop(steps, step(true, `${t.ip} is on the internet`, `${p.name} has Home only: their device's own internet reaches it, not the tunnel.`));
|
||||
@@ -211,7 +216,7 @@ function to_device(m, ip, d, states, dmp, snap) {
|
||||
if (!p || !srv)
|
||||
return [ step(false, `${d.name} has no server`, '') ];
|
||||
let who = `${p.name} · ${d.name}`;
|
||||
let hdev = home_dev_of(srv, ip, snap);
|
||||
let hdev = in_tunnels(m, ip) ? null : home_dev_of(srv, ip, snap);
|
||||
if (!hdev)
|
||||
return [ step(false, `${ip} isn't in ${srv.name}'s home network`, 'Only home devices reach people\'s devices.') ];
|
||||
let steps = [ step(true, `${ip} is at home (${hdev})`, '') ];
|
||||
@@ -219,7 +224,7 @@ function to_device(m, ip, d, states, dmp, snap) {
|
||||
return stop(steps, step(false, `${p.name} has ${p.access == 'lan' ? 'only some home services' : ACCESS_TEXT[p.access]}`,
|
||||
'Home devices reach only people with home access.'));
|
||||
let h = core.person_home(srv, p, snap);
|
||||
if (!in_any(ip, h.nets))
|
||||
if (!in_nets(ip, h.nets))
|
||||
return stop(steps, step(false, `${p.name} doesn't reach ${hdev}`, 'Networks a person does not reach cannot reach them either.'));
|
||||
push(steps, person_ok(m, p, d, states));
|
||||
if (!steps[length(steps) - 1].ok)
|
||||
@@ -238,7 +243,7 @@ export function check(m, from, to) {
|
||||
die(`"${to}" is not a device or an IPv4 address.`);
|
||||
let usage = core.load_usage();
|
||||
let states = view.states(m, usage);
|
||||
let dmp = live.dump();
|
||||
let dmp = live.dump(m);
|
||||
let snap = net.snapshot(true);
|
||||
let steps;
|
||||
if (a.dev)
|
||||
|
||||
@@ -1,481 +1,38 @@
|
||||
// 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
|
||||
// * network interfaces (dawnline.netifd) and the devices loaded live into
|
||||
// them (dawnline.awg)
|
||||
// * firewall zones, forwardings, WAN rules and reply routes (dawnline.fw)
|
||||
// * the nft table `inet dawnline` enforcing each person's access (dawnline.nft)
|
||||
// * 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.
|
||||
//
|
||||
// apply(), sync() and sync_loop() run under one lock ('apply') and read the
|
||||
// model inside it, so a rebuild and a runtime update never interleave and the
|
||||
// last one to run always works from the newest configuration. The config lock
|
||||
// (dawnline.store) is never taken while 'apply' is held.
|
||||
|
||||
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, slog, iface_intent, RUN_DIR
|
||||
} from 'dawnline.util';
|
||||
import { ensure_dir, write_file, write_json, with_lock, ip2int, slog, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as nft from 'dawnline.nft';
|
||||
import * as fw from 'dawnline.fw';
|
||||
import * as netifd from 'dawnline.netifd';
|
||||
import * as migrate from 'dawnline.migrate';
|
||||
|
||||
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;
|
||||
/** The network signature the last apply() worked from (the agent compares against it). */
|
||||
export const NET_SIG = `${RUN_DIR}/net.sig`;
|
||||
// The last access-table error that was logged (each distinct failure once).
|
||||
const NFT_ERR = `${RUN_DIR}/nft.err`;
|
||||
|
||||
function log(who, msg, level, detail) {
|
||||
slog('dawnline', level ?? 'info', msg, detail, who);
|
||||
}
|
||||
|
||||
/* ---------- 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);
|
||||
// Per server: with several, each changed one has to be brought up again.
|
||||
let mine = ensure_section(c, 'network', ifn, 'interface');
|
||||
let set = (opt, val) => {
|
||||
if (put(c, 'network', ifn, opt, val))
|
||||
mine = true;
|
||||
};
|
||||
set('proto', 'amneziawg');
|
||||
set('private_key', srv.private_key);
|
||||
set('listen_port', srv.port);
|
||||
set('addresses', [ `${addr}/${pc.prefix}` ]);
|
||||
set('mtu', srv.mtu);
|
||||
set('disabled', srv.enabled ? null : '1');
|
||||
set('auto', srv.enabled ? null : '0');
|
||||
set('_dawnline', id);
|
||||
// For the log once the server is gone.
|
||||
set('_dawnline_name', srv.name);
|
||||
for (let k in core.OBF_KEYS)
|
||||
set(`awg_${k}`, srv.obf[k]);
|
||||
if (mine) {
|
||||
changed = true;
|
||||
push(touched, ifn);
|
||||
// The hotplug log says why the tunnel goes down (not a failure).
|
||||
iface_intent(ifn, srv.enabled ? 'settings' : 'off', srv.name);
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
iface_intent(ifn, 'removed', c.get('network', ifn, '_dawnline_name') ?? ifn);
|
||||
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)}`);
|
||||
// Each tunnel's own line (restarting, turned off, removed) comes from hotplug.
|
||||
system(`logger -t dawnline ${q('network updated: ' + join(', ', [ ...touched, ...stale ]))}`);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/* ---------- firewall ---------- */
|
||||
|
||||
const LOOP_ZONE = 'dl_loop';
|
||||
|
||||
/** With `dry`, only says whether the firewall config differs from what Dawnline wants. */
|
||||
function sync_firewall(m, dry) {
|
||||
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', {
|
||||
// Forward within the zone (device to device) is decided by the inet dawnline table.
|
||||
name: srv.ifname, network: [ srv.ifname ],
|
||||
input: 'ACCEPT', output: 'ACCEPT', forward: 'ACCEPT',
|
||||
});
|
||||
// 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.
|
||||
// The home network may open connections to the devices too (a router
|
||||
// or a NAS on the tunnel); their answers pass the table as established.
|
||||
for (let i, zone in sn.zones)
|
||||
if (zone != sn.wan.zone && zone != srv.ifname) {
|
||||
let sfx = i == 0 ? '' : `_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`;
|
||||
sec(`${z}_lan${sfx}`, 'forwarding', { src: srv.ifname, dest: zone });
|
||||
sec(`${z}_from_lan${sfx}`, 'forwarding', { src: zone, dest: srv.ifname });
|
||||
}
|
||||
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 (dry)
|
||||
return changed;
|
||||
|
||||
if (changed) {
|
||||
c.commit('firewall');
|
||||
ack_config([ 'firewall' ]);
|
||||
system('fw4 -q reload');
|
||||
system("logger -t dawnline '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) {
|
||||
// lan_ok: home access (the router itself, the mesh); lan_all: every home
|
||||
// network; lan_part: device . network for people limited to some networks;
|
||||
// mesh_pairs: device . device within a circle (or one person's own devices).
|
||||
let sets = { lan_ok: [], lan_all: [], lan_part: [], mesh_pairs: [], inet_ok: [], svc_ok: [], dns_real: [] };
|
||||
let snap = net.snapshot();
|
||||
let homes = {}, groups = {};
|
||||
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);
|
||||
let srv = m.servers[p.server];
|
||||
let h = homes[p.id] ??= srv ? core.person_home(srv, p, snap) : { all: true, nets: [] };
|
||||
if (h.all)
|
||||
push(sets.lan_all, d.address);
|
||||
else
|
||||
for (let n in h.nets)
|
||||
push(sets.lan_part, `${d.address} . ${n}`);
|
||||
// Who this device may reach directly: its circle, or at least its owner's devices.
|
||||
if (srv?.mesh == 'circles') {
|
||||
let ci = core.person_circle(m, p);
|
||||
push(groups[ci ? `c:${ci.id}` : `p:${p.id}`] ??= [], 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}`);
|
||||
}
|
||||
}
|
||||
for (let g, addrs in groups)
|
||||
for (let a in addrs)
|
||||
for (let b in addrs)
|
||||
if (a != b)
|
||||
push(sets.mesh_pairs, `${a} . ${b}`);
|
||||
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 lan_all { type ipv4_addr; ${set_elems(sets.lan_all)} }`);
|
||||
push(t, ` set lan_part { type ipv4_addr . ipv4_addr; flags interval; ${set_elems(sets.lan_part)} }`);
|
||||
push(t, ` set mesh_pairs { type ipv4_addr . ipv4_addr; ${set_elems(sets.mesh_pairs)} }`);
|
||||
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_all accept');
|
||||
push(t, ' ip saddr . ip daddr @lan_part accept');
|
||||
// Devices with home access are part of home: they reach each other, where the
|
||||
// server allows it (everyone, or within circles). Within one server: the
|
||||
// firewall has no forwarding between different servers' zones.
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key && srv.mesh == 'all')
|
||||
push(t, ` iifname "${srv.ifname}" ip saddr @lan_ok ip daddr @lan_ok accept`);
|
||||
else if (srv.private_key && srv.mesh == 'circles')
|
||||
push(t, ` iifname "${srv.ifname}" ip saddr . ip daddr @mesh_pairs 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, ' }');
|
||||
// The other way: fw4 lets the server's home zones reach the tunnel; here
|
||||
// only connections from its home networks to people with home access pass
|
||||
// (paused, ended and internet-only people are not reachable). The admin's
|
||||
// own port forwards (DNAT) stay with fw4.
|
||||
push(t, ' chain inbound {');
|
||||
push(t, ' type filter hook forward priority filter - 5; policy accept;');
|
||||
if (length(ifs))
|
||||
push(t, ` oifname { ${join(', ', ifs)} } iifname != { ${join(', ', ifs)} } ct state new jump to_device`);
|
||||
push(t, ' }');
|
||||
push(t, ' chain to_device {');
|
||||
push(t, ' meta nfproto ipv6 drop');
|
||||
push(t, ' ct status dnat accept');
|
||||
push(t, ' ip saddr @lan_nets ip daddr @lan_all accept');
|
||||
push(t, ' ip daddr . ip saddr @lan_part accept');
|
||||
push(t, ' counter reject with icmpx admin-prohibited');
|
||||
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('Access rules', "couldn't load", 'error', 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', 'lan_all', 'lan_part', 'mesh_pairs', '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)
|
||||
slog('awg', 'error', "couldn't load devices into the tunnel", trim(r.out), srv.name);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
/* ---------- hostnames ---------- */
|
||||
|
||||
function host_label(s) {
|
||||
@@ -489,7 +46,7 @@ export function sync_hosts(m) {
|
||||
if (m.settings.hostnames)
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (p && d.address)
|
||||
if (p && ip2int(d.address) != null)
|
||||
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`);
|
||||
}
|
||||
let ls = loop.status();
|
||||
@@ -511,7 +68,7 @@ export function sync_hosts(m) {
|
||||
return true;
|
||||
};
|
||||
|
||||
/* ---------- entry points ---------- */
|
||||
/* ---------- access table ---------- */
|
||||
|
||||
export function states_for(m, usage) {
|
||||
let st = {};
|
||||
@@ -520,21 +77,84 @@ export function states_for(m, 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();
|
||||
/** Per-person runtime membership (dawnline.nft). */
|
||||
export function access_sets(m, usage, states) {
|
||||
return nft.access_sets(m, usage, states);
|
||||
};
|
||||
|
||||
/** Log an access-table failure once per distinct error; true when the table is in place. */
|
||||
function nft_result(err) {
|
||||
let was = readfile(NFT_ERR);
|
||||
if (err == null) {
|
||||
if (was != null)
|
||||
unlink(NFT_ERR);
|
||||
return true;
|
||||
}
|
||||
if (was != err) {
|
||||
log('Access rules', "couldn't load — devices aren't loaded into the tunnels until they do", 'error', err);
|
||||
ensure_dir(RUN_DIR);
|
||||
writefile(NFT_ERR, err);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The table in place: rebuilt with `full`, otherwise members only, rebuilt
|
||||
* when that fails (no table yet at boot, or an older shape) — an error only
|
||||
* when the rebuild fails too.
|
||||
*/
|
||||
function load_table(m, sets, full) {
|
||||
let err = full ? nft.rebuild(m, sets) : nft.update(sets);
|
||||
if (err != null && !full)
|
||||
err = nft.rebuild(m, sets);
|
||||
return nft_result(err);
|
||||
}
|
||||
|
||||
/** Full table rebuild (structure changes: servers, LAN subnets). */
|
||||
export function rebuild_nft(m, sets) {
|
||||
return nft_result(nft.rebuild(m, sets));
|
||||
};
|
||||
|
||||
/** Atomically replace set contents only. */
|
||||
export function update_sets(sets) {
|
||||
return nft.update(sets) == null;
|
||||
};
|
||||
|
||||
export function remove_nft() {
|
||||
nft.remove();
|
||||
};
|
||||
|
||||
/** For the watchdog (dawnline.fw). */
|
||||
export function firewall_drift(m) {
|
||||
return fw.drift(m);
|
||||
};
|
||||
|
||||
/* ---------- runtime sync ---------- */
|
||||
|
||||
/*
|
||||
* With the lock held: access sets first, and devices into the tunnels only
|
||||
* once the table that limits them is in place.
|
||||
*/
|
||||
function locked_sync(m, usage, full) {
|
||||
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);
|
||||
let sets = nft.access_sets(m, usage, states);
|
||||
let peers = {};
|
||||
if (load_table(m, sets, full))
|
||||
peers = awg.sync_peers(m, states);
|
||||
sync_hosts(m);
|
||||
unlock(l);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(`${RUN_DIR}/states.json`, states, 0o644);
|
||||
return { peers, states };
|
||||
}
|
||||
|
||||
/**
|
||||
* Runtime sync: devices into the tunnels (AmneziaWG peers), access sets,
|
||||
* hostnames. Cheap; safe to call often. The model is always read again under
|
||||
* the lock (`m` is accepted for older callers and not used); `usage` is the
|
||||
* caller's (the agent holds the live counters).
|
||||
*/
|
||||
export function sync(m, usage) {
|
||||
return with_lock('apply', () => locked_sync(core.load(), usage ?? core.load_usage()));
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -552,179 +172,66 @@ export function net_signature(m) {
|
||||
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');
|
||||
system(`logger -t dawnline ${q(want ? 'portal answers through the LuCI web server' : 'portal removed from the LuCI web server')}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* For the watchdog: what is wrong with Dawnline's firewall, or null.
|
||||
* 'off': fw4 is not running at all (not ours to start); 'changed': the config
|
||||
* lost or changed Dawnline's sections; 'not loaded': fw4 runs without them.
|
||||
*/
|
||||
export function firewall_drift(m) {
|
||||
let t = sh_out('nft -t list table inet fw4 2>/dev/null') ?? '';
|
||||
if (t == '')
|
||||
return 'off';
|
||||
if (sync_firewall(m, true))
|
||||
return 'changed';
|
||||
// Named rules show up in fw4's ruleset as comments.
|
||||
let names = [];
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.private_key && srv.enabled)
|
||||
push(names, `Dawnline-${srv.ifname}`);
|
||||
if (m.settings.portal_enabled)
|
||||
push(names, 'Dawnline-Portal');
|
||||
for (let n in names)
|
||||
if (index(t, `${n}"`) < 0)
|
||||
return 'not loaded';
|
||||
return null;
|
||||
};
|
||||
|
||||
/** For the watchdog: LuCI's web server should hand portal links to the portal, but does not. */
|
||||
export function uhttpd_drift(m) {
|
||||
if (!(m.settings.portal_enabled && core.portal_public_port(m) == 443 && m.settings.portal_port != 443))
|
||||
return false;
|
||||
let c = cursor();
|
||||
c.load('uhttpd');
|
||||
let cur = c.get('uhttpd', 'main', 'error_page');
|
||||
// Someone else's error page is theirs: Health explains, nothing to repair.
|
||||
return cur == null || (cur == LAN_CGI_URL && !stat(LAN_CGI));
|
||||
};
|
||||
|
||||
/** 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);
|
||||
}
|
||||
let p = with_lock('apply', () => {
|
||||
let mm = core.load();
|
||||
let before = `${loop.client_dns()} ${loop.resolver_target().mode}`;
|
||||
let lp = loop.ensure(mm, force);
|
||||
loop.sync_resolver(mm);
|
||||
fw.sync_reply_routes(mm);
|
||||
if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before)
|
||||
locked_sync(mm, usage ?? core.load_usage(), true);
|
||||
return lp;
|
||||
});
|
||||
loop.remember(p);
|
||||
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');
|
||||
}
|
||||
}
|
||||
/* ---------- entry points ---------- */
|
||||
|
||||
/** 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 };
|
||||
migrate.run();
|
||||
let r = with_lock('apply', () => {
|
||||
let m = core.load();
|
||||
let usage = core.load_usage();
|
||||
let network = netifd.sync(m);
|
||||
let firewall = fw.sync(m);
|
||||
let lp = loop.ensure(m, true);
|
||||
loop.sync_resolver(m);
|
||||
fw.sync_reply_routes(m);
|
||||
let s = locked_sync(m, usage, true);
|
||||
ensure_dir(RUN_DIR);
|
||||
write_file(NET_SIG, net_signature(m), 0o644);
|
||||
return { network, firewall, lp, peers: s.peers };
|
||||
});
|
||||
loop.remember(r.lp);
|
||||
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: r.lp.error } : !r.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');
|
||||
with_lock('apply', () => {
|
||||
let m = core.load();
|
||||
loop.remove();
|
||||
unlink(loop.RESOLVER.conf);
|
||||
m.servers = {};
|
||||
m.settings.portal_enabled = false;
|
||||
netifd.sync(m);
|
||||
fw.sync(m);
|
||||
fw.sync_reply_routes(m);
|
||||
nft.remove();
|
||||
unlink(HOSTS_FILE);
|
||||
unlink(NET_SIG);
|
||||
system('killall -HUP dnsmasq 2>/dev/null');
|
||||
});
|
||||
migrate.uhttpd();
|
||||
// The agent's heartbeat check.
|
||||
if (system('grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root') == 0)
|
||||
system("sed -i '\\#/usr/libexec/dawnline/heartbeat#d' /etc/crontabs/root; /etc/init.d/cron restart >/dev/null 2>&1");
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client
|
||||
// configurations (.conf, AmneziaVPN key), the netifd options of a server's
|
||||
// tunnel, its peers (`awg syncconf`, no restart), live counters and what the
|
||||
// watchdog and Health check about it. Plain WireGuard is AmneziaWG with the
|
||||
// disguise off.
|
||||
|
||||
import { readfile, stat, unlink } from 'fs';
|
||||
import {
|
||||
q, sh, sh_out, rand_int, rand_bytes, valid_key, ensure_dir, write_file, read_json, write_json, lock, unlock,
|
||||
slog, iface_status, DATA_DIR, RUN_DIR
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
|
||||
/** 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',
|
||||
};
|
||||
|
||||
const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh';
|
||||
/** The packages AmneziaWG comes in (the Components tab installs them). */
|
||||
const PACKAGES = [ 'kmod-amneziawg', 'amneziawg-tools' ];
|
||||
|
||||
/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */
|
||||
function proto_handler() {
|
||||
try {
|
||||
return 'amneziawg' in (json(sh_out('ubus call network get_proto_handlers 2>/dev/null') || '{}') ?? {});
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What of AmneziaWG is on the router:
|
||||
* tools the awg tool and the netifd protocol script (amneziawg-tools)
|
||||
* kmod the kernel module, loaded or on disk for the running kernel
|
||||
* loaded the module is loaded
|
||||
* handler netifd lists the amneziawg protocol
|
||||
* missing packages that are not installed; ok: everything is in place
|
||||
*/
|
||||
export function state() {
|
||||
let tools = stat(TOOL) != null && stat(PROTO) != null;
|
||||
let loaded = stat('/sys/module/amneziawg') != null;
|
||||
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||
let kmod = loaded || (rel != '' && stat(`/lib/modules/${rel}/amneziawg.ko`) != null);
|
||||
let handler = tools && proto_handler();
|
||||
let missing = filter(PACKAGES, (p) => p == 'kmod-amneziawg' ? !kmod : !tools);
|
||||
return { tools, kmod, loaded, handler, missing, ok: !length(missing) && loaded && handler };
|
||||
};
|
||||
|
||||
/** The kernel module and the awg tool are on the router. */
|
||||
export function installed() {
|
||||
let s = state();
|
||||
return s.tools && s.kmod;
|
||||
};
|
||||
|
||||
/* ---------- 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`);
|
||||
};
|
||||
|
||||
/** A preshared key is 32 random bytes: no tool needed (`awg genpsk` does the same). */
|
||||
export function genpsk() {
|
||||
return b64enc(rand_bytes(32));
|
||||
};
|
||||
|
||||
/**
|
||||
* Keys for a new device. With `public_key` (made in the browser) the private
|
||||
* key never reaches the router. Never without a preshared key.
|
||||
*/
|
||||
export function new_keys(public_key) {
|
||||
let psk = genpsk();
|
||||
if (!valid_key(psk))
|
||||
die('Key generation failed (no random data).');
|
||||
if (public_key) {
|
||||
if (!valid_key(public_key))
|
||||
die('Invalid public key.');
|
||||
return { public_key, preshared_key: psk };
|
||||
}
|
||||
let priv = genkey(), pub = pubkey(priv);
|
||||
if (!pub)
|
||||
die('Key generation failed (is amneziawg-tools installed?).');
|
||||
return { private_key: priv, public_key: pub, preshared_key: psk };
|
||||
};
|
||||
|
||||
/** A server's own key pair (set up once, on the server). */
|
||||
export function server_keys() {
|
||||
let priv = genkey(), pub = pubkey(priv);
|
||||
if (!pub)
|
||||
die('Key generation failed (is amneziawg-tools installed?).');
|
||||
return { private_key: priv, public_key: pub };
|
||||
};
|
||||
|
||||
/* ---------- 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 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: sh_out('awg 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;
|
||||
};
|
||||
|
||||
|
||||
|
||||
export function allowed_ips(m, srv, p) {
|
||||
if (p.access == 'lan') {
|
||||
let nets = core.person_home(srv, p).nets;
|
||||
// With devices reaching each other, the whole tunnel network (the router's
|
||||
// address is in it); otherwise only the router's own address.
|
||||
let a = core.server_address(srv);
|
||||
if (srv.device_mesh && srv.subnet)
|
||||
push(nets, srv.subnet);
|
||||
else if (a)
|
||||
push(nets, `${a}/32`);
|
||||
// The resolver address must be reachable through the tunnel too (not the fallback).
|
||||
let dns = core.client_dns(m, srv, p)[0];
|
||||
if (dns)
|
||||
push(nets, `${dns}/32`);
|
||||
return net.collapse(nets);
|
||||
}
|
||||
return [ '0.0.0.0/0', '::/0' ];
|
||||
};
|
||||
|
||||
|
||||
/** True when the obfuscation settings change nothing on the wire (plain WireGuard). */
|
||||
export function obf_neutral(o) {
|
||||
for (let k in core.OBF_KEYS) {
|
||||
let v = o?.[k];
|
||||
if (v == null || v == '')
|
||||
continue;
|
||||
let want = { h1: '1', h2: '2', h3: '3', h4: '4' }[k] ?? '0';
|
||||
if (`${v}` != want)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
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 = core.endpoint_host(m, srv);
|
||||
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
|
||||
let allowed = allowed_ips(m, srv, p);
|
||||
let dns = core.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}`);
|
||||
// "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left
|
||||
// out, so any WireGuard app accepts the file.
|
||||
if (!obf_neutral(srv.obf))
|
||||
for (let k in core.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,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
/* ---------- the server's tunnel ---------- */
|
||||
|
||||
/** netifd options of the server's interface (proto amneziawg). */
|
||||
export function netifd_options(srv) {
|
||||
let addr = core.server_address(srv);
|
||||
let prefix = split(srv.subnet, '/')[1];
|
||||
let o = {
|
||||
proto: 'amneziawg',
|
||||
private_key: srv.private_key,
|
||||
listen_port: srv.port,
|
||||
addresses: [ `${addr}/${prefix}` ],
|
||||
mtu: srv.mtu,
|
||||
};
|
||||
for (let k in core.OBF_KEYS)
|
||||
o[`awg_${k}`] = srv.obf[k];
|
||||
return o;
|
||||
};
|
||||
|
||||
/** 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) {
|
||||
// Only Dawnline's own interfaces: never another tunnel of the same name (core.tunnels).
|
||||
if (!srv.enabled || !length(core.tunnels(srv)))
|
||||
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)
|
||||
slog('awg', 'error', "couldn't load devices into the tunnel", trim(r.out), srv.name);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
|
||||
* Interface lines have many fields (AmneziaWG adds obfuscation values); peer
|
||||
* lines always have 9. The tool fails when any one interface can't be read,
|
||||
* but still prints the others: those are kept and `ok` is false, so only the
|
||||
* interfaces listed in `ifaces` are known.
|
||||
*/
|
||||
export function dump() {
|
||||
let r = sh('awg show all dump');
|
||||
let out = { ok: r.code == 0, ifaces: {}, peers: {} };
|
||||
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;
|
||||
};
|
||||
|
||||
/** Is the server's tunnel up and listening (for status and Overview). */
|
||||
export function server_state(srv) {
|
||||
let st = iface_status(srv.ifname);
|
||||
return { up: !!st?.up, uptime: st?.uptime ?? 0 };
|
||||
};
|
||||
|
||||
/* ---------- watchdog ---------- */
|
||||
|
||||
/** Why a tunnel is down, from netifd and the last related syslog lines. */
|
||||
export function iface_errors(ifname) {
|
||||
let s = iface_status(ifname);
|
||||
let errs = map(s?.errors ?? [], (e) => e.code + (length(e.data ?? []) ? ` (${join(' ', e.data)})` : ''));
|
||||
// Only what explains a failure, not the ordinary "is now up/down" lines.
|
||||
let lines = sh_out(`logread -l 400 2>/dev/null | grep -E ${q(`${ifname}|amneziawg`)} | grep -iE 'error|fail|invalid|unrecogni|cannot|unable|not found|refused|denied' | tail -n 6`);
|
||||
return join('\n', filter([ length(errs) ? `netifd: ${join(', ', errs)}` : null, lines ], (x) => x));
|
||||
};
|
||||
|
||||
/**
|
||||
* What the watchdog looks at for AmneziaWG (see dawnline.watchdog):
|
||||
* AmneziaWG itself, then every running server's tunnel. `ctx.udp_listening`,
|
||||
* `ctx.reapply` and `ctx.owner` (dawnline.netifd) come from the watchdog
|
||||
* (ops, apply and netifd import this module).
|
||||
*/
|
||||
export function probes(m, ctx) {
|
||||
let out = [];
|
||||
let srvs = filter(values(m.servers), (x) => x.enabled && x.private_key);
|
||||
if (!length(srvs))
|
||||
return out;
|
||||
// AmneziaWG itself first: without it no tunnel can run (they come back on the next pass).
|
||||
// Missing packages and an unknown protocol are reported once; only the module can be loaded here.
|
||||
let st = state();
|
||||
let base = { id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', back: 'is ready again' };
|
||||
if (!st.tools || !st.kmod) {
|
||||
push(out, { ...base, ok: false, repair: null,
|
||||
problem: `${st.tools ? "kernel module isn't" : "isn't"} installed: no tunnel can run — install it in Dawnline → Components`,
|
||||
detail: () => `Missing: ${join(', ', st.missing)}.` });
|
||||
return out;
|
||||
}
|
||||
push(out, { ...base, ok: st.loaded && st.handler,
|
||||
problem: !st.loaded ? "kernel module isn't loaded" : "isn't known to the network service — restart the network or reboot",
|
||||
detail: !st.loaded
|
||||
? () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4")
|
||||
: () => 'netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.',
|
||||
repair: !st.loaded ? { what: 'loading it', run: () => system('modprobe amneziawg >/dev/null 2>&1') } : null,
|
||||
});
|
||||
// Without the protocol handler ifup cannot work: the tunnels are not probed (or restarted) one by one.
|
||||
if (st.loaded && !st.handler)
|
||||
return out;
|
||||
for (let srv in srvs) {
|
||||
// A tunnel Dawnline may not set up (dawnline.netifd) is reported, never restarted:
|
||||
// an interface of the same name that isn't Dawnline's may be your LAN.
|
||||
let own = core.valid_ifname(srv.ifname) ? ctx.owner?.(srv.ifname) : null;
|
||||
let why = srv.blocked ?? (!core.valid_ifname(srv.ifname) ? `has an invalid interface name "${srv.ifname}"`
|
||||
: own != null && own != srv.id ? `can't use the network interface ${srv.ifname}: it exists and isn't Dawnline's` : null);
|
||||
if (why) {
|
||||
push(out, {
|
||||
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null,
|
||||
problem: why, back: 'AmneziaWG is running again',
|
||||
detail: () => 'Choose another interface name in the server settings.',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let s = iface_status(srv.ifname);
|
||||
let up = !!s?.up;
|
||||
push(out, {
|
||||
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: up && ctx.udp_listening(srv.port),
|
||||
problem: !s ? 'AmneziaWG is missing from the router' : !up ? "AmneziaWG isn't running" : `AmneziaWG isn't accepting connections on port ${srv.port}`,
|
||||
back: `AmneziaWG is running again · accepting connections on port ${srv.port}`,
|
||||
detail: () => iface_errors(srv.ifname),
|
||||
repair: s ? { what: 'restarting it', run: () => system(`ifup ${q(srv.ifname)}`) } : { what: 'setting it up again', run: ctx.reapply },
|
||||
});
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/* ---------- 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);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// Dawnline — where AmneziaWG comes from: the awg-openwrt projects publish
|
||||
// builds per OpenWrt release and target (the kernel module must match the
|
||||
// firmware). Used by the updater and the Components RPCs.
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { connect } from 'ubus';
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
|
||||
export const SOURCES = {
|
||||
slava: { repo: 'Slava-Shchipunov/awg-openwrt', label: 'Slava-Shchipunov' },
|
||||
grey: { repo: '2Grey/awg-openwrt', label: '2Grey' },
|
||||
};
|
||||
/** Tried in this order when no build is chosen. */
|
||||
export const ORDER = [ 'slava', 'grey' ];
|
||||
export const PKGS = [ 'kmod-amneziawg', 'amneziawg-tools', 'luci-proto-amneziawg' ];
|
||||
export const RU = 'luci-i18n-amneziawg-ru';
|
||||
|
||||
/**
|
||||
* This firmware as the builds name it: { tag: 'v24.10.6', postfix:
|
||||
* '_v24.10.6_aarch64_cortex-a53_mediatek_filogic', ext }, or null.
|
||||
*/
|
||||
export function firmware() {
|
||||
let u = connect();
|
||||
let b = u?.call('system', 'board') ?? {};
|
||||
u?.disconnect();
|
||||
let rel = b.release ?? {};
|
||||
let target = split(rel.target ?? '', '/');
|
||||
let arch = rel.arch ?? match(readfile('/etc/openwrt_release') ?? '', /DISTRIB_ARCH='([^']*)'/)?.[1];
|
||||
if (!rel.version || length(target) != 2 || !arch)
|
||||
return null;
|
||||
return { tag: `v${rel.version}`, postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, ext: pkg.ext() };
|
||||
};
|
||||
|
||||
/** The file name of a package in a build. */
|
||||
export function asset(fw, name) {
|
||||
return `${name}${fw.postfix}.${fw.ext}`;
|
||||
};
|
||||
|
||||
/** The same firmware, another release of its series (v24.10.6 → v24.10.8). */
|
||||
export function for_tag(fw, tag) {
|
||||
return { ...fw, tag, postfix: replace(fw.postfix, fw.tag, tag) };
|
||||
};
|
||||
|
||||
/** AmneziaWG generation of a tools version: 3.x packages carry 3.1, older ones (1.0.x) 2.0. */
|
||||
export function gen(version) {
|
||||
return version == null ? null : match(version, /^3\./) ? '3.1' : '2.0';
|
||||
};
|
||||
|
||||
/** The installed AmneziaWG packages: { name: version | null }. */
|
||||
export function installed() {
|
||||
let r = {};
|
||||
for (let p in PKGS)
|
||||
r[p] = pkg.version(p);
|
||||
return r;
|
||||
};
|
||||
@@ -0,0 +1,285 @@
|
||||
// Dawnline — backups (tar.gz of the config and its data files), restoring
|
||||
// them, and the JSON export / import. Whatever comes back in is checked first:
|
||||
// only Dawnline's own regular files, and servers that cannot take over one of
|
||||
// the router's own interfaces or networks.
|
||||
|
||||
import { readfile, stat, unlink, lsdir } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import {
|
||||
q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, 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 net from 'dawnline.net';
|
||||
import * as health from 'dawnline.health';
|
||||
|
||||
const BACKUP_DIR = `${DATA_DIR}/backups`;
|
||||
const KEEP_BACKUPS = 10;
|
||||
const NAME = /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/;
|
||||
/** What a backup holds (paths inside the archive, relative to /). */
|
||||
const FILES = [ 'etc/config/dawnline', 'etc/dawnline/usage.json', 'etc/dawnline/events.json' ];
|
||||
/** The unpacked size a backup may have (the upload itself is limited to 4 MB). */
|
||||
const MAX_UNPACKED = 16 * 1024 * 1024;
|
||||
|
||||
/* ---------- checking a configuration before it is used ---------- */
|
||||
|
||||
/**
|
||||
* What is wrong with the servers of a configuration about to replace the
|
||||
* current one (cursor `c` holds it): each must have a valid, unique interface
|
||||
* name that is not one of the router's own interfaces, a free subnet and a
|
||||
* unique port. [] when it can be used.
|
||||
*/
|
||||
export function config_errors(c) {
|
||||
let m = core.load(c);
|
||||
let errs = [];
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
let foreign = health.foreign_subnets();
|
||||
let internal = values(net.INTERNAL);
|
||||
let ifnames = {}, ports = {}, subnets = [];
|
||||
for (let id, srv in m.servers) {
|
||||
let who = `Server ${srv.name}`;
|
||||
for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ]))
|
||||
push(errs, `${who}: ${e}`);
|
||||
if (ifnames[srv.ifname])
|
||||
push(errs, `${who}: interface ${srv.ifname} is also used by ${ifnames[srv.ifname]}.`);
|
||||
ifnames[srv.ifname] = srv.name;
|
||||
let t = nc.get('network', srv.ifname);
|
||||
if (index(internal, srv.ifname) >= 0 || (t != null && (t != 'interface' || nc.get('network', srv.ifname, '_dawnline') == null)))
|
||||
push(errs, `${who}: ${srv.ifname} is one of the router's own network interfaces.`);
|
||||
if (ports[srv.port])
|
||||
push(errs, `${who}: UDP ${srv.port} is also used by ${ports[srv.port]}.`);
|
||||
ports[srv.port] = srv.name;
|
||||
if (srv.subnet)
|
||||
push(subnets, srv.subnet);
|
||||
}
|
||||
return errs;
|
||||
};
|
||||
|
||||
/** Check the config file in `dir` (as /etc/config/dawnline would be); dies listing the problems. */
|
||||
function check_config_dir(dir) {
|
||||
ensure_dir(`${dir}/.delta`, 0o700);
|
||||
// Its own delta directory: changes staged in LuCI must not leak into the check.
|
||||
let c = cursor(dir, `${dir}/.delta`);
|
||||
if (!c.load('dawnline'))
|
||||
die('The configuration in this file cannot be read.');
|
||||
let errs = config_errors(c);
|
||||
if (length(errs))
|
||||
die(`This configuration can't be used: ${join(' ', errs)}`);
|
||||
}
|
||||
|
||||
/** A private scratch directory under RUN_DIR (the caller removes it). */
|
||||
function scratch(kind) {
|
||||
ensure_dir(RUN_DIR);
|
||||
let dir = `${RUN_DIR}/${kind}.${rand_hex(4)}`;
|
||||
system(`rm -rf ${q(dir)}; mkdir -m 700 -p ${q(dir)}`);
|
||||
return dir;
|
||||
}
|
||||
|
||||
/* ---------- backups ---------- */
|
||||
|
||||
export function backup_list() {
|
||||
let out = [];
|
||||
for (let f in lsdir(BACKUP_DIR) ?? []) {
|
||||
let mm = match(f, NAME);
|
||||
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);
|
||||
};
|
||||
|
||||
/**
|
||||
* Make a backup now; returns its name. The oldest beyond KEEP_BACKUPS are
|
||||
* removed, except `keep` (the backup being restored, which must survive the
|
||||
* backup made just before restoring it).
|
||||
*/
|
||||
export function backup_create(reason, keep) {
|
||||
// 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(filter(FILES, (f) => file_exists(`/${f}`)), q));
|
||||
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();
|
||||
let old = filter(all, (b) => b.name != keep && b.name != name);
|
||||
let room = KEEP_BACKUPS - 1 - (length(old) < length(all) - 1 ? 1 : 0);
|
||||
for (let i = room; i < length(old); i++)
|
||||
unlink(`${BACKUP_DIR}/${old[i].name}`);
|
||||
return name;
|
||||
};
|
||||
|
||||
function backup_path(name) {
|
||||
if (!match(name ?? '', NAME))
|
||||
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, all of them regular files
|
||||
* (no links, devices or directories), within a sane unpacked size.
|
||||
*/
|
||||
function check_archive(path) {
|
||||
let r = sh(`tar -tvzf ${q(path)}`);
|
||||
if (r.code != 0)
|
||||
die('Not a valid backup archive.');
|
||||
let has_config = false, total = 0;
|
||||
for (let line in split(trim(r.out), '\n')) {
|
||||
let f = split(trim(line), /[ \t]+/);
|
||||
let name = replace(f[length(f) >= 6 ? 5 : length(f) - 1] ?? '', /^\.?\//, '');
|
||||
// "-rw------- root/root 1234 2026-01-01 12:00:00 etc/config/dawnline"; links show "a -> b".
|
||||
if (substr(line, 0, 1) != '-' || index(line, ' -> ') >= 0 || index(line, ' link to ') >= 0)
|
||||
die(`Unexpected entry in backup: ${name}`);
|
||||
if (index(FILES, name) < 0)
|
||||
die(`Unexpected file in backup: ${name}`);
|
||||
total += +(f[2] ?? 0) || 0;
|
||||
if (name == 'etc/config/dawnline')
|
||||
has_config = true;
|
||||
}
|
||||
if (!has_config)
|
||||
die('Backup does not contain /etc/config/dawnline.');
|
||||
if (total > MAX_UNPACKED)
|
||||
die('Backup is too large.');
|
||||
}
|
||||
|
||||
/** Put the files unpacked in `dir` in place, under the config lock. */
|
||||
function install_files(dir) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
let l = lock('config');
|
||||
for (let f in FILES) {
|
||||
let data = readfile(`${dir}/${f}`);
|
||||
if (data != null)
|
||||
write_file(`/${f}`, data, 0o600);
|
||||
}
|
||||
unlock(l);
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
}
|
||||
|
||||
export function backup_restore(name, path) {
|
||||
path ??= backup_path(name);
|
||||
check_archive(path);
|
||||
let dir = scratch('restore');
|
||||
try {
|
||||
let r = sh(`tar -xzf ${q(path)} -C ${q(dir)} ${join(' ', map(FILES, q))} 2>/dev/null; test -f ${q(dir + '/etc/config/dawnline')}`);
|
||||
if (r.code != 0)
|
||||
die('Not a valid backup archive.');
|
||||
check_config_dir(`${dir}/etc/config`);
|
||||
backup_create('pre-restore', name);
|
||||
install_files(dir);
|
||||
}
|
||||
catch (e) {
|
||||
system(`rm -rf ${q(dir)}`);
|
||||
die(e.message);
|
||||
}
|
||||
system(`rm -rf ${q(dir)}`);
|
||||
// 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 };
|
||||
};
|
||||
|
||||
/** An export as /etc/config/dawnline text; dies on anything that is not one. */
|
||||
function export_to_uci(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, circle: true };
|
||||
let esc = (x) => replace(`${x}`, "'", "'\\''");
|
||||
let lines = [];
|
||||
for (let s in data.sections) {
|
||||
if (type(s) != 'object' || !types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/))
|
||||
die(`Invalid section ${s?.['.name']}.`);
|
||||
push(lines, `config ${s['.type']} '${s['.name']}'`);
|
||||
for (let k, v in s) {
|
||||
if (substr(k, 0, 1) == '.')
|
||||
continue;
|
||||
if (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array'))
|
||||
die(`Invalid option ${k}.`);
|
||||
if (type(v) == 'array')
|
||||
for (let x in v) {
|
||||
if (type(x) != 'string')
|
||||
die(`Invalid option ${k}.`);
|
||||
push(lines, `\tlist ${k} '${esc(x)}'`);
|
||||
}
|
||||
else
|
||||
push(lines, `\toption ${k} '${esc(v)}'`);
|
||||
}
|
||||
push(lines, '');
|
||||
}
|
||||
return join('\n', lines);
|
||||
}
|
||||
|
||||
export function import_json(data) {
|
||||
let text = export_to_uci(data);
|
||||
let dir = scratch('import');
|
||||
try {
|
||||
write_file(`${dir}/dawnline`, text, 0o600);
|
||||
check_config_dir(dir);
|
||||
}
|
||||
catch (e) {
|
||||
system(`rm -rf ${q(dir)}`);
|
||||
die(e.message);
|
||||
}
|
||||
system(`rm -rf ${q(dir)}`);
|
||||
backup_create('pre-import');
|
||||
let l = lock('config');
|
||||
write_file('/etc/config/dawnline', text, 0o600);
|
||||
unlock(l);
|
||||
return apply.apply();
|
||||
};
|
||||
@@ -1,38 +1,34 @@
|
||||
// Dawnline — data model: reads /etc/config/dawnline, validates and mutates it,
|
||||
// allocates addresses, generates keys and renders client configurations.
|
||||
// Dawnline — data model: reads /etc/config/dawnline, validates and mutates it
|
||||
// and allocates addresses. Nothing here knows how the tunnel works: dawnline.awg
|
||||
// renders AmneziaWG configurations and runs the tunnels.
|
||||
|
||||
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
|
||||
valid_name, valid_key, valid_host, valid_date, slugify, parse_cidr, cidr_overlaps, int2ip, ip2int,
|
||||
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
|
||||
} from 'dawnline.util';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import { policy as updates_policy } from 'dawnline.updates';
|
||||
|
||||
export const CONFIG = 'dawnline';
|
||||
/**
|
||||
* Servers whose network interface Dawnline may not set up (the name belongs
|
||||
* to an interface it did not create, or is invalid): { id: why }. Written by
|
||||
* dawnline.netifd; such a server has no tunnel anywhere (firewall, access
|
||||
* table, "like a home device"), so nothing of Dawnline lands on that interface.
|
||||
*/
|
||||
export const BLOCKED = `${RUN_DIR}/netifd-blocked.json`;
|
||||
export const ACCESS = [ 'lan', 'internet', 'both' ];
|
||||
export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ];
|
||||
/** Devices of different people reaching each other: never, everyone with home access, or within a circle. */
|
||||
export const MESH = [ 'off', 'all', 'circles' ];
|
||||
/** Circle colours (index into the admin palette). */
|
||||
export const CIRCLE_COLORS = 8;
|
||||
/** AmneziaWG obfuscation options stored on a server (netifd uses `awg_<key>`; dawnline.awg renders them). */
|
||||
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;
|
||||
@@ -74,8 +70,6 @@ export function load(c) {
|
||||
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 != ''),
|
||||
@@ -95,6 +89,8 @@ export function load(c) {
|
||||
watchdog: bool(s.watchdog, 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'),
|
||||
// Settings → Updates (automatic checks and updates of the components).
|
||||
updates: updates_policy(s),
|
||||
// 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,
|
||||
@@ -109,6 +105,7 @@ export function load(c) {
|
||||
circles: {},
|
||||
};
|
||||
|
||||
let blocked = read_json(BLOCKED, {});
|
||||
c.foreach(CONFIG, 'server', (r) => {
|
||||
let id = r['.name'];
|
||||
let srv = {
|
||||
@@ -137,13 +134,16 @@ export function load(c) {
|
||||
// (Older configs: device_mesh 0/1.)
|
||||
mesh: index(MESH, r.mesh) >= 0 ? r.mesh : (bool(r.device_mesh, true) ? 'all' : 'off'),
|
||||
enabled: bool(r.enabled, true),
|
||||
// AmneziaWG disguise values, read by dawnline.awg.
|
||||
obf: {},
|
||||
};
|
||||
// A person's own devices reach each other whenever the mesh is not off.
|
||||
srv.device_mesh = srv.mesh != 'off';
|
||||
for (let k in OBF_KEYS)
|
||||
if (r[k] != null && r[k] != '')
|
||||
srv.obf[k] = `${r[k]}`;
|
||||
// A person's own devices reach each other whenever the mesh is not off.
|
||||
srv.device_mesh = srv.mesh != 'off';
|
||||
if (blocked[id])
|
||||
srv.blocked = blocked[id];
|
||||
m.servers[id] = srv;
|
||||
});
|
||||
|
||||
@@ -291,37 +291,43 @@ export function load_usage() {
|
||||
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} });
|
||||
};
|
||||
|
||||
/* ---------- keys ---------- */
|
||||
/* ---------- tunnels and addresses ---------- */
|
||||
|
||||
export function genkey() {
|
||||
return sh_out('awg genkey');
|
||||
/** A server's interface name: also a netifd section and an nft string, so nothing else. */
|
||||
export function valid_ifname(s) {
|
||||
return type(s) == 'string' && match(s, /^[a-z][a-z0-9_]{0,11}$/) != null;
|
||||
};
|
||||
|
||||
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). */
|
||||
/** Router address inside the AmneziaWG subnet (first host). */
|
||||
export function server_address(srv) {
|
||||
let c = parse_cidr(srv.subnet);
|
||||
return c ? int2ip(c.first) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The link a server's devices come in on: { ifname, subnet, address (the
|
||||
* router's) }, as a list so the access table, firewall zone, "like a home
|
||||
* device" and DNS treat every tunnel interface alike. None for a server
|
||||
* without keys, subnet or a valid interface name (an imported config), or
|
||||
* whose interface name is taken (BLOCKED).
|
||||
*/
|
||||
export function tunnels(srv) {
|
||||
let c = srv?.private_key && !srv.blocked && valid_ifname(srv.ifname) ? parse_cidr(srv.subnet) : null;
|
||||
return c ? [ { ifname: srv.ifname, subnet: srv.subnet, address: int2ip(c.first) } ] : [];
|
||||
};
|
||||
|
||||
/** The server's tunnel link, or null. */
|
||||
export function tunnel(srv) {
|
||||
return tunnels(srv)[0];
|
||||
};
|
||||
|
||||
/** The first free address in the server's subnet (the router has the first). */
|
||||
export function alloc_address(m, srv) {
|
||||
let c = parse_cidr(srv.subnet);
|
||||
if (!c)
|
||||
let t = parse_cidr(srv.subnet);
|
||||
if (!t)
|
||||
return null;
|
||||
let used = {};
|
||||
used[c.first] = true;
|
||||
used[t.first] = true;
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (p && p.server == srv.id) {
|
||||
@@ -330,124 +336,24 @@ export function alloc_address(m, srv) {
|
||||
used[n] = true;
|
||||
}
|
||||
}
|
||||
for (let n = c.first + 1; n <= c.last; n++)
|
||||
for (let n = t.first + 1; n <= t.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 ---------- */
|
||||
/* ---------- what clients get ---------- */
|
||||
|
||||
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.
|
||||
* DNS for a server's clients: the router's address in the tunnel subnet,
|
||||
* 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)
|
||||
@@ -459,10 +365,10 @@ export function dns_list(m, srv) {
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* DNS a device uses. 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')
|
||||
@@ -500,132 +406,6 @@ export function person_circle(m, p) {
|
||||
return c && c.server == p.server ? c : null;
|
||||
};
|
||||
|
||||
export function allowed_ips(m, srv, p) {
|
||||
if (p.access == 'lan') {
|
||||
let nets = person_home(srv, p).nets;
|
||||
// With devices reaching each other, the whole tunnel network (the router's
|
||||
// address is in it); otherwise only the router's own address.
|
||||
let a = server_address(srv);
|
||||
if (srv.device_mesh && srv.subnet)
|
||||
push(nets, srv.subnet);
|
||||
else 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. */
|
||||
/** True when the obfuscation settings change nothing on the wire (plain WireGuard). */
|
||||
export function obf_neutral(o) {
|
||||
for (let k in OBF_KEYS) {
|
||||
let v = o?.[k];
|
||||
if (v == null || v == '')
|
||||
continue;
|
||||
let want = { h1: '1', h2: '2', h3: '3', h4: '4' }[k] ?? '0';
|
||||
if (`${v}` != want)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
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}`);
|
||||
// "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left
|
||||
// out, so any WireGuard app accepts the file.
|
||||
if (!obf_neutral(srv.obf))
|
||||
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) {
|
||||
@@ -673,7 +453,9 @@ export function create_person(c, m, a) {
|
||||
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';
|
||||
// Any kind of section (store.id_taken, which imports this module).
|
||||
let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || m.circles[id] ||
|
||||
index([ 'settings', 'main', 'global', 'defaults' ], id) >= 0;
|
||||
let slug = base;
|
||||
for (let n = 2; taken(slug); n++) {
|
||||
if (n > 99)
|
||||
@@ -734,8 +516,9 @@ export function update_person(c, m, id, a) {
|
||||
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}.`);
|
||||
let have = length(p.devices);
|
||||
if (n < have)
|
||||
fail(`${p.name} already has ${have} devices. Remove one first to lower the limit to ${n}.`);
|
||||
set('device_limit', n);
|
||||
}
|
||||
if (a.expires != null) {
|
||||
@@ -808,9 +591,9 @@ export function update_person(c, m, id, a) {
|
||||
};
|
||||
|
||||
/**
|
||||
* 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).
|
||||
* Add a device for a person. `opts.keys` = { private_key?, public_key,
|
||||
* preshared_key } from dawnline.awg (or a public key the browser generated).
|
||||
* `opts.by` is 'admin' or 'portal'; the portal is held to the device limit.
|
||||
*/
|
||||
export function create_device(c, m, person_id, name, kind, opts) {
|
||||
opts ??= {};
|
||||
@@ -833,39 +616,29 @@ export function create_device(c, m, person_id, name, kind, opts) {
|
||||
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)
|
||||
let k = opts.keys ?? {};
|
||||
if (!valid_key(k.public_key))
|
||||
fail('Key generation failed (is amneziawg-tools installed?).');
|
||||
for (let id, d in m.devices)
|
||||
if (d.public_key == pub)
|
||||
for (let o, d in m.devices)
|
||||
if (d.public_key == k.public_key)
|
||||
fail('This key is already in use.');
|
||||
|
||||
let id = `d_${rand_hex(4)}`;
|
||||
let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '',
|
||||
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false };
|
||||
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');
|
||||
for (let f in [ 'public_key', 'private_key', 'preshared_key' ])
|
||||
if (dev[f])
|
||||
c.set(CONFIG, id, f, dev[f]);
|
||||
c.set(CONFIG, id, 'created', `${dev.created}`);
|
||||
c.set(CONFIG, id, 'created_by', dev.created_by);
|
||||
|
||||
// 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 };
|
||||
m.devices[id] = dev;
|
||||
push(p.devices, id);
|
||||
return id;
|
||||
};
|
||||
@@ -895,16 +668,17 @@ export function delete_device(c, m, id) {
|
||||
delete m.devices[id];
|
||||
};
|
||||
|
||||
export function rotate_device(c, m, id) {
|
||||
/** New keys from dawnline.awg (the caller makes them: the model does not run tools). */
|
||||
export function rotate_device(c, m, id, keys) {
|
||||
let d = m.devices[id];
|
||||
if (!d)
|
||||
fail('Unknown device.');
|
||||
let priv = genkey(), pub = pubkey(priv);
|
||||
if (!pub)
|
||||
if (!valid_key(keys?.public_key) || !keys?.private_key)
|
||||
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());
|
||||
c.set(CONFIG, id, 'private_key', keys.private_key);
|
||||
c.set(CONFIG, id, 'public_key', keys.public_key);
|
||||
if (keys.preshared_key)
|
||||
c.set(CONFIG, id, 'preshared_key', keys.preshared_key);
|
||||
};
|
||||
|
||||
export function delete_person(c, m, id) {
|
||||
@@ -919,7 +693,7 @@ export function delete_person(c, m, 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}$/))
|
||||
if (!valid_ifname(srv.ifname))
|
||||
push(errs, 'Interface name: 1-12 lowercase letters, digits or _.');
|
||||
if (srv.port < 1 || srv.port > 65535)
|
||||
push(errs, 'Port must be 1-65535.');
|
||||
@@ -934,7 +708,6 @@ export function server_errors(m, srv, others_subnets) {
|
||||
}
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -947,18 +720,14 @@ export function wan_port_taken(port) {
|
||||
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]))
|
||||
let m = match(p, /^(\d+)([-:](\d+))?$/);
|
||||
if (m && +m[1] <= port && port <= +(m[3] || 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 = [];
|
||||
@@ -978,17 +747,14 @@ 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. */
|
||||
/** The port in plain-HTTP links (the portal never takes 80 or 443 for itself). */
|
||||
export function portal_http_public(m) {
|
||||
return m.settings.portal_443 && !wan_port_taken(80) ? 80 : portal_http_port(m);
|
||||
return portal_http_port(m);
|
||||
};
|
||||
|
||||
/** The port in personal links: 443 when the portal also answers there. */
|
||||
/** The port in personal links: the portal's own. */
|
||||
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;
|
||||
return m.settings.portal_port;
|
||||
};
|
||||
|
||||
/** The link on one address: https for names, plain http for IP addresses. */
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// Dawnline — adding, changing, rotating and removing a person's devices: one
|
||||
// code path for the admin UI (rpcd) and the portal, with the config lock,
|
||||
// the runtime sync, the activity log and the "configuration issued" mark.
|
||||
//
|
||||
// opts = { by: 'admin' | 'portal', person?: the only person whose devices may
|
||||
// be touched (the portal), defer?: load new keys a moment later (the portal
|
||||
// page came through the device being rotated) }. The portal is held to the
|
||||
// device limit (dawnline.core) and cannot touch a device the admin turned off.
|
||||
|
||||
import { sh_bg } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as store from 'dawnline.store';
|
||||
|
||||
/** AmneziaWG is on the router, so device keys can be made and loaded. */
|
||||
export function ready() {
|
||||
return awg.installed();
|
||||
};
|
||||
|
||||
/** Dies with the admin's wording when AmneziaWG is missing. */
|
||||
export function need_awg() {
|
||||
if (!awg.installed()) {
|
||||
let miss = awg.state().missing ?? [];
|
||||
die(`AmneziaWG is not installed${length(miss) ? ` (${join(', ', miss)})` : ''}: install it in Dawnline → Components.`);
|
||||
}
|
||||
};
|
||||
|
||||
/** The device `id` as `opts` may touch it (inside a transaction's model). */
|
||||
function own(m, id, opts) {
|
||||
let d = m.devices[id];
|
||||
if (!d || (opts.person != null && d.person != opts.person))
|
||||
die(opts.person != null ? 'Device not found.' : 'Unknown device.');
|
||||
if (opts.by == 'portal' && d.disabled)
|
||||
die('The admin has turned this device off.');
|
||||
return d;
|
||||
}
|
||||
|
||||
/** New device with fresh keys (or the browser's public key): { id, config }. */
|
||||
export function add(person, name, kind, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind, { by, keys: awg.new_keys(opts.public_key || null) }));
|
||||
apply.sync();
|
||||
let m = core.load();
|
||||
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
|
||||
awg.mark_issued(m, id);
|
||||
return { id, config: awg.client_config(m, m.devices[id]) };
|
||||
};
|
||||
|
||||
/**
|
||||
* Rename and/or turn a device off or on (`ch` = { name?, disabled? }); only
|
||||
* the admin turns devices off. Returns the runtime sync.
|
||||
*/
|
||||
export function update(id, ch, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
if (ch.disabled != null && by != 'admin')
|
||||
die('Only the admin can turn devices off.');
|
||||
let d0 = store.transact((c, m) => {
|
||||
let d = own(m, id, opts);
|
||||
let was = { ...d };
|
||||
if (ch.name != null && ch.name != d.name)
|
||||
core.rename_device(c, m, id, ch.name);
|
||||
if (ch.disabled != null) {
|
||||
if (ch.disabled)
|
||||
c.set(core.CONFIG, id, 'disabled', '1');
|
||||
else
|
||||
c.delete(core.CONFIG, id, 'disabled');
|
||||
}
|
||||
return was;
|
||||
});
|
||||
let r = apply.sync();
|
||||
if (ch.disabled != null && !!ch.disabled != !!d0.disabled)
|
||||
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: ch.disabled ? 'turned off' : 'turned on', by });
|
||||
else if (ch.name != null && ch.name != d0.name)
|
||||
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: `renamed from ${d0.name}`, by });
|
||||
return r;
|
||||
};
|
||||
|
||||
/** New keys for a device: returns its new configuration. */
|
||||
export function rotate(id, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
store.transact((c, m) => {
|
||||
own(m, id, opts);
|
||||
core.rotate_device(c, m, id, awg.new_keys());
|
||||
});
|
||||
// The device a portal page came through would lose its tunnel before the
|
||||
// answer gets out: load the new key a moment after answering.
|
||||
if (opts.defer)
|
||||
sh_bg('sleep 3; /usr/bin/dawnline sync');
|
||||
else
|
||||
apply.sync();
|
||||
let m = core.load();
|
||||
let d = m.devices[id];
|
||||
live.add_event({ type: 'device_keys', person: d.person, device: id, detail: d.name, by });
|
||||
awg.mark_issued(m, id);
|
||||
return awg.client_config(m, d);
|
||||
};
|
||||
|
||||
/** Remove a device. Returns the runtime sync. */
|
||||
export function remove(id, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
let d = store.transact((c, m) => {
|
||||
let d = own(m, id, opts);
|
||||
core.delete_device(c, m, id);
|
||||
return d;
|
||||
});
|
||||
let r = apply.sync();
|
||||
live.add_event({ type: 'device_removed', person: d.person, device: id, detail: d.name, dname: d.name, dkind: d.kind, by });
|
||||
return r;
|
||||
};
|
||||
@@ -0,0 +1,177 @@
|
||||
// Dawnline — fw4 and routing around it: each tunnel's zone, its forwardings
|
||||
// to home and WAN, the WAN rules for the tunnels and the portal (named
|
||||
// sections dawnline_*), what the watchdog checks about them, and the reply
|
||||
// routes that keep Dawnline's own answers on the main table. Only sections
|
||||
// named dawnline_* are ever changed.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { sh, sh_out, uniq, uci_put, uci_section, ack_config } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
|
||||
const LOOP_ZONE = 'dl_loop';
|
||||
/*
|
||||
* 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 the router's own traffic (iif lo) from our listening
|
||||
* ports: forwarded traffic keeps whatever routing the router has for it.
|
||||
*/
|
||||
const PREF_REPLY = 90;
|
||||
|
||||
/** With `dry`, only says whether the firewall config differs from what Dawnline wants. */
|
||||
export function sync(m, dry) {
|
||||
let c = cursor();
|
||||
c.load('firewall');
|
||||
let changed = false, want = {};
|
||||
|
||||
let sec = (name, stype, opts) => {
|
||||
want[name] = true;
|
||||
changed = uci_section(c, 'firewall', name, stype) || changed;
|
||||
for (let k, v in opts)
|
||||
changed = uci_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 (!length(core.tunnels(srv)))
|
||||
continue;
|
||||
let z = `dawnline_${id}`;
|
||||
let sn = net.server_net(srv, snap);
|
||||
portal_zone ??= sn.wan.zone;
|
||||
sec(`${z}_zone`, 'zone', {
|
||||
// Forward within the zone (device to device) is decided by the inet dawnline table.
|
||||
name: srv.ifname, network: [ srv.ifname ],
|
||||
input: 'ACCEPT', output: 'ACCEPT', forward: 'ACCEPT',
|
||||
});
|
||||
// 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.
|
||||
// The home network may open connections to the devices too (a router
|
||||
// or a NAS on the tunnel); their answers pass the table as established.
|
||||
for (let i, zone in sn.zones)
|
||||
if (zone != sn.wan.zone && zone != srv.ifname) {
|
||||
let sfx = i == 0 ? '' : `_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`;
|
||||
sec(`${z}_lan${sfx}`, 'forwarding', { src: srv.ifname, dest: zone });
|
||||
sec(`${z}_from_lan${sfx}`, 'forwarding', { src: zone, dest: srv.ifname });
|
||||
}
|
||||
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' });
|
||||
}
|
||||
|
||||
// Never open SSH, DNS or the LuCI web server for the portal, whatever the settings say.
|
||||
let portal_port_ok = (p) => p >= 1 && p <= 65535 && index([ 22, 53, 80, 443 ], p) < 0;
|
||||
if (m.settings.portal_enabled && portal_port_ok(m.settings.portal_port)) {
|
||||
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) && portal_port_ok(core.portal_http_port(m))) {
|
||||
sec('dawnline_portal_http', 'rule', {
|
||||
name: 'Dawnline-Portal-HTTP', src: wan, proto: 'tcp',
|
||||
dest_port: core.portal_http_port(m), target: 'ACCEPT',
|
||||
});
|
||||
}
|
||||
// The portal keeps its own port: 80 and 443 stay with the LuCI web server.
|
||||
}
|
||||
|
||||
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 (dry)
|
||||
return changed;
|
||||
|
||||
if (changed) {
|
||||
c.commit('firewall');
|
||||
ack_config([ 'firewall' ]);
|
||||
system('fw4 -q reload');
|
||||
system("logger -t dawnline 'firewall updated'");
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
|
||||
/**
|
||||
* For the watchdog: what is wrong with Dawnline's firewall, or null.
|
||||
* 'off': fw4 is not running at all (not ours to start); 'changed': the config
|
||||
* lost or changed Dawnline's sections; 'not loaded': fw4 runs without them.
|
||||
*/
|
||||
export function drift(m) {
|
||||
let t = sh_out('nft -t list table inet fw4 2>/dev/null') ?? '';
|
||||
if (t == '')
|
||||
return 'off';
|
||||
if (sync(m, true))
|
||||
return 'changed';
|
||||
// Named rules show up in fw4's ruleset as comments.
|
||||
let names = [];
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.enabled && length(core.tunnels(srv)))
|
||||
push(names, `Dawnline-${srv.ifname}`);
|
||||
if (m.settings.portal_enabled)
|
||||
push(names, 'Dawnline-Portal');
|
||||
for (let n in names)
|
||||
if (index(t, `${n}"`) < 0)
|
||||
return 'not loaded';
|
||||
return null;
|
||||
};
|
||||
|
||||
/** Our reply rules of one family as `ip rule show` prints them: [{ proto, port, lo }]. */
|
||||
function reply_rules(fam) {
|
||||
let out = [];
|
||||
// "90: from all iif lo ipproto udp sport 51820 lookup main" (older versions: without "iif lo").
|
||||
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 ([0-9]+) lookup main/);
|
||||
if (mm)
|
||||
push(out, { proto: mm[1], port: mm[2], lo: index(line, ' iif lo ') >= 0 });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** One `iif lo ipproto <p> sport <port> lookup main` rule per listening port and family. */
|
||||
export 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' ]) {
|
||||
// Ours that are no longer wanted, and the older ones that also caught forwarded traffic.
|
||||
for (let r in reply_rules(fam))
|
||||
if (!r.lo || index(want, `${r.proto} ${r.port}`) < 0)
|
||||
sh(`ip ${fam} rule del priority ${PREF_REPLY}${r.lo ? ' iif lo' : ''} ipproto ${r.proto} sport ${r.port} lookup main 2>/dev/null`);
|
||||
let have = map(filter(reply_rules(fam), (r) => r.lo), (r) => `${r.proto} ${r.port}`);
|
||||
for (let w in want)
|
||||
if (index(have, w) < 0)
|
||||
sh(`ip ${fam} rule add priority ${PREF_REPLY} iif lo ipproto ${split(w, ' ')[0]} sport ${split(w, ' ')[1]} lookup main`);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,226 @@
|
||||
// Dawnline — GitHub for the updater and the Components tab: API calls with a
|
||||
// short cache, releases (with each asset's sha256), the changes between two
|
||||
// tags, and verified downloads.
|
||||
//
|
||||
// Trust: the API is only ever asked directly (TLS to api.github.com). Files
|
||||
// may come through a mirror when GitHub is unreachable, but only when their
|
||||
// sha256 is known from the API, and a file is kept only if it matches.
|
||||
|
||||
import { stat, popen, access } from 'fs';
|
||||
import { q, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
|
||||
|
||||
/** Prefixes that fetch github.com files when GitHub itself is unreachable. */
|
||||
export const MIRRORS = [ 'https://ghfast.top/', 'https://gh-proxy.com/', 'https://ghproxy.net/' ];
|
||||
|
||||
function run(cmd) {
|
||||
let p = popen(cmd + ' 2>&1', 'r');
|
||||
if (!p)
|
||||
return { code: 127, out: '' };
|
||||
let out = p.read('all') ?? '';
|
||||
return { code: p.close(), out };
|
||||
}
|
||||
|
||||
function have_curl() {
|
||||
return access('/usr/bin/curl', 'x');
|
||||
}
|
||||
|
||||
/**
|
||||
* GET a URL: { status, body } (status 0 when there was no answer). curl gives
|
||||
* the HTTP status, so a 403 rate limit is told apart from a dead network.
|
||||
*/
|
||||
function get(url, timeout) {
|
||||
timeout ??= 12;
|
||||
if (have_curl()) {
|
||||
let r = run(`curl -sSL --connect-timeout 6 --max-time ${+timeout} -H 'Accept: application/vnd.github+json' -A Dawnline -w '\\n%{http_code}' ${q(url)}`);
|
||||
// The body, then the status on the last line (-w).
|
||||
let i = rindex(r.out, '\n');
|
||||
let code = i < 0 ? '' : substr(r.out, i + 1);
|
||||
return match(code, /^[0-9][0-9][0-9]$/) ? { status: +code, body: substr(r.out, 0, i) } : { status: 0, body: '' };
|
||||
}
|
||||
let r = run(`uclient-fetch -q -T ${+timeout} -O - ${q(url)}`);
|
||||
return { status: r.code == 0 ? 200 : 0, body: r.code == 0 ? r.out : '' };
|
||||
}
|
||||
|
||||
/** JSON from the GitHub API, or null when GitHub did not answer; dies on a rate limit or another API error. */
|
||||
function api_json(url) {
|
||||
let r = get(url);
|
||||
if (r.status == 0)
|
||||
return null;
|
||||
let j = null;
|
||||
try {
|
||||
j = json(r.body);
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
if (r.status == 403 || r.status == 429 || (type(j) == 'object' && match(j.message ?? '', /rate limit/i)))
|
||||
die('GitHub API rate limit reached: try again in an hour.');
|
||||
if (r.status == 404)
|
||||
return null;
|
||||
if (r.status >= 400)
|
||||
die(`GitHub: ${j?.message ?? `HTTP ${r.status}`}`);
|
||||
return j;
|
||||
}
|
||||
|
||||
function cached(key, ttl, fn) {
|
||||
let path = `${RUN_DIR}/gh-${replace(key, /[^A-Za-z0-9_.-]/g, '_')}.json`;
|
||||
let c = read_json(path, null);
|
||||
if (c && time() - (c.at ?? 0) < ttl)
|
||||
return c.data;
|
||||
let data = fn();
|
||||
if (data != null) {
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(path, { at: time(), data });
|
||||
}
|
||||
return data ?? c?.data;
|
||||
}
|
||||
|
||||
/* ---------- releases ---------- */
|
||||
|
||||
function slim(x) {
|
||||
let digests = {};
|
||||
for (let a in x.assets ?? [])
|
||||
if (match(a.digest ?? '', /^sha256:[0-9a-f]{64}$/))
|
||||
digests[a.name] = substr(a.digest, 7);
|
||||
return {
|
||||
tag: x.tag_name, name: x.name ?? x.tag_name, published: x.published_at ?? null,
|
||||
prerelease: !!x.prerelease, url: x.html_url ?? null, body: substr(x.body ?? '', 0, 12000),
|
||||
assets: map(x.assets ?? [], (a) => a.name), digests,
|
||||
};
|
||||
}
|
||||
|
||||
/** Releases of a repository, newest first, five per page (drafts skipped). */
|
||||
export function releases(rp, page) {
|
||||
page = page ?? 1;
|
||||
return cached(`rel-${rp}-${page}`, 600, () => {
|
||||
let j = api_json(`https://api.github.com/repos/${rp}/releases?per_page=5&page=${+page}`);
|
||||
return type(j) == 'array' ? map(filter(j, (x) => !x.draft), slim) : null;
|
||||
}) ?? [];
|
||||
};
|
||||
|
||||
/** One release by tag (notes, assets and their sha256), or null. */
|
||||
export function release(rp, tag) {
|
||||
return cached(`tag-${rp}-${tag}`, 600, () => {
|
||||
let j = api_json(`https://api.github.com/repos/${rp}/releases/tags/${tag}`);
|
||||
return type(j) == 'object' && j.tag_name ? slim(j) : null;
|
||||
});
|
||||
};
|
||||
|
||||
/** The sha256 GitHub publishes for a release file, or null (unknown: no mirrors for it). */
|
||||
export function asset_sha256(rp, tag, name) {
|
||||
try {
|
||||
return release(rp, tag)?.digests?.[name] ?? null;
|
||||
}
|
||||
catch (e) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/** The latest stable release; the /releases/latest redirect when the API is out of reach. */
|
||||
export function latest(rp) {
|
||||
let r = null;
|
||||
try {
|
||||
r = cached(`latest-${rp}`, 300, () => {
|
||||
let j = api_json(`https://api.github.com/repos/${rp}/releases/latest`);
|
||||
return type(j) == 'object' && j.tag_name ? slim(j) : null;
|
||||
});
|
||||
}
|
||||
catch (e) {}
|
||||
if (r)
|
||||
return r;
|
||||
if (have_curl()) {
|
||||
let o = 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(o.out), /\/releases\/tag\/([^\/?#]+)$/);
|
||||
if (m)
|
||||
return { tag: m[1], name: m[1], published: null, prerelease: false, url: `https://github.com/${rp}/releases/tag/${m[1]}`, body: '', assets: [], digests: {} };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/* ---------- what changed ---------- */
|
||||
|
||||
/**
|
||||
* What changed in a commit message, as points: release commits ("Dawnline
|
||||
* 0.3.1") list their changes as "- " lines in the body; other commits are
|
||||
* their title. Wrapped points are joined back into one line.
|
||||
*/
|
||||
export function points(msg) {
|
||||
let lines = split(msg ?? '', '\n');
|
||||
let title = trim(lines[0] ?? '');
|
||||
if (match(title, /^Merge /))
|
||||
return [];
|
||||
let out = [], cur = null;
|
||||
for (let i = 1; i < length(lines); i++) {
|
||||
let m = match(lines[i], /^\s*[-*]\s+(.*)$/);
|
||||
if (m) {
|
||||
if (cur != null)
|
||||
push(out, cur);
|
||||
cur = trim(m[1]);
|
||||
}
|
||||
else if (cur != null && match(lines[i], /^\s+\S/))
|
||||
cur += ' ' + trim(lines[i]);
|
||||
else if (cur != null) {
|
||||
push(out, cur);
|
||||
cur = null;
|
||||
}
|
||||
}
|
||||
if (cur != null)
|
||||
push(out, cur);
|
||||
if (!length(out) && !match(title, /^(Dawnline )?v?[0-9]+\.[0-9]+(\.[0-9]+)?$/) && title != '')
|
||||
push(out, title);
|
||||
return out;
|
||||
};
|
||||
|
||||
/** The changes from one tag to another, newest first: commit by commit, or the release's own commit. */
|
||||
export function changes(rp, base, head) {
|
||||
return cached(`changes-${rp}-${base}-${head}`, 600, () => {
|
||||
let out = [];
|
||||
let j = base ? api_json(`https://api.github.com/repos/${rp}/compare/${base}...${head}`) : null;
|
||||
if (type(j?.commits) == 'array') {
|
||||
for (let i = length(j.commits) - 1; i >= 0; i--)
|
||||
for (let p in points(j.commits[i]?.commit?.message))
|
||||
push(out, p);
|
||||
return slice(out, 0, 20);
|
||||
}
|
||||
let c = api_json(`https://api.github.com/repos/${rp}/commits/${head}`);
|
||||
return c?.commit ? slice(points(c.commit.message), 0, 20) : null;
|
||||
}) ?? [];
|
||||
};
|
||||
|
||||
/* ---------- downloads ---------- */
|
||||
|
||||
export function sha256(path) {
|
||||
return match(run(`sha256sum ${q(path)}`).out, /^([0-9a-f]{64})/)?.[1];
|
||||
};
|
||||
|
||||
/**
|
||||
* Download to a file. o: { sha256, mirrors, log }. Direct first; mirrors
|
||||
* only when the sha256 is known (from the API) and mirrors are allowed. A
|
||||
* file that does not match the sha256 is thrown away and the next source is
|
||||
* tried. Returns the URL that worked, or null.
|
||||
*/
|
||||
export function download(url, dest, o) {
|
||||
o ??= {};
|
||||
let want = o.sha256 ? lc(o.sha256) : null;
|
||||
let tries = [ url ];
|
||||
if (want && o.mirrors && match(url, /^https:\/\/(github\.com|raw\.githubusercontent\.com)\//))
|
||||
for (let m in MIRRORS)
|
||||
push(tries, m + url);
|
||||
for (let i, u in tries) {
|
||||
let host = replace(u, /^https:\/\/([^\/]+)\/.*$/, '$1');
|
||||
if (i > 0)
|
||||
o.log?.(`Trying mirror ${host}`);
|
||||
let r = have_curl()
|
||||
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 1 -o ${q(dest)} ${q(u)}`)
|
||||
: run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(u)}`);
|
||||
if (r.code == 0 && (stat(dest)?.size ?? 0) > 0) {
|
||||
if (!want || sha256(dest) == want)
|
||||
return u;
|
||||
o.log?.(`Warning: ${host} sent a file that does not match GitHub's sha256, discarded`);
|
||||
}
|
||||
system(`rm -f ${q(dest)}`);
|
||||
if (i == 0 && length(tries) > 1)
|
||||
o.log?.('GitHub did not answer, trying mirrors');
|
||||
}
|
||||
return null;
|
||||
};
|
||||
@@ -0,0 +1,433 @@
|
||||
// Dawnline — Health: what the router has and lacks (packages, listeners,
|
||||
// networks), the checks shown on Diagnostics → Health, and their fixes.
|
||||
|
||||
import { readfile, stat, lsdir } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { q, sh, sh_out, parse_cidr, cidr_overlaps, ip2int, in_cidr, file_exists, cloudflare_ip } 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';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as lookup from 'dawnline.lookup';
|
||||
import * as pc from 'dawnline.portalcert';
|
||||
|
||||
/* ---------- what the router has ---------- */
|
||||
|
||||
/**
|
||||
* 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), awg
|
||||
* (AmneziaWG: the tools with netifd's protocol script, and the kernel module). 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 kmod = (name) => stat(`/sys/module/${name}`) != null || file_exists(`/lib/modules/${kver}/${name}.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' ], [ kmod('veth'), 'kmod-veth' ] ]),
|
||||
// amneziawg-tools ships both the awg tool and netifd's protocol script.
|
||||
awg: miss([ [ file_exists('/usr/bin/awg') && file_exists('/lib/netifd/proto/amneziawg.sh'), 'amneziawg-tools' ],
|
||||
[ kmod('amneziawg'), 'kmod-amneziawg' ] ]),
|
||||
};
|
||||
};
|
||||
|
||||
export 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;
|
||||
};
|
||||
|
||||
export 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;
|
||||
};
|
||||
|
||||
export function service_running(name, instance) {
|
||||
let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`);
|
||||
if (!s)
|
||||
return false;
|
||||
try {
|
||||
return !!json(s)?.[name]?.instances?.[instance]?.running;
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** IPv4 networks of netifd interfaces: [{ iface, cidr }], without the given server's tunnel. */
|
||||
function other_subnets(srv_id) {
|
||||
let out = [];
|
||||
let st = sh_out('ubus call network.interface dump 2>/dev/null');
|
||||
let d = null;
|
||||
try {
|
||||
d = st ? json(st) : null;
|
||||
}
|
||||
catch (e) {
|
||||
d = null;
|
||||
}
|
||||
let ours = {};
|
||||
for (let id, s in core.load().servers)
|
||||
ours[s.ifname] = id;
|
||||
for (let i in d?.interface ?? []) {
|
||||
if (srv_id != null && ours[i.interface] == srv_id)
|
||||
continue;
|
||||
if (srv_id === false && ours[i.interface] != null)
|
||||
continue;
|
||||
for (let a in i['ipv4-address'] ?? [])
|
||||
push(out, { iface: i.interface, cidr: `${a.address}/${a.mask}` });
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Subnets in use on the router except the given server's (null: all of them). */
|
||||
export function used_subnets(except_srv) {
|
||||
return map(other_subnets(except_srv), (x) => x.cidr);
|
||||
};
|
||||
|
||||
/** Subnets of interfaces that are not Dawnline tunnels (an imported config is checked against these). */
|
||||
export function foreign_subnets() {
|
||||
return used_subnets(false);
|
||||
};
|
||||
|
||||
/* ---------- checks ---------- */
|
||||
|
||||
/*
|
||||
* Checks are named for the healthy state ("Clock is set"); a failed one also
|
||||
* gets the problem in words for notices ("Clock isn't set"). Longest names
|
||||
* first; a server's name after the check name is kept.
|
||||
*/
|
||||
const PROBLEM = [
|
||||
[ 'AmneziaWG answers reach devices', 'AmneziaWG answers may not reach devices' ],
|
||||
[ 'AmneziaWG devices loaded', 'Not every device is loaded into AmneziaWG' ],
|
||||
[ 'AmneziaWG subnet is unique', 'AmneziaWG subnet overlaps another network' ],
|
||||
[ 'AmneziaWG port is free', 'AmneziaWG port is taken' ],
|
||||
[ 'AmneziaWG installed', 'AmneziaWG isn’t ready' ],
|
||||
[ 'AmneziaWG firewall', 'AmneziaWG firewall rules are missing' ],
|
||||
[ 'AmneziaWG running', 'AmneziaWG is down' ],
|
||||
[ 'Portal answers reach visitors', 'Portal answers may not reach visitors' ],
|
||||
[ 'Portal address points here', 'Portal address doesn’t point here' ],
|
||||
[ 'Portal address', 'Portal address isn’t set' ],
|
||||
[ 'Portal certificate', 'Portal certificate needs attention' ],
|
||||
[ 'Personal portal', 'Personal portal isn’t working' ],
|
||||
[ 'Plain HTTP links', 'Portal links use plain HTTP' ],
|
||||
[ 'Internet like a home device', 'Internet like a home device isn’t working' ],
|
||||
[ 'DNS for Home-only devices', 'DNS for Home-only devices isn’t working' ],
|
||||
[ 'Background agent running', 'Background agent isn’t running' ],
|
||||
[ 'Access rules loaded', 'Access rules aren’t loaded' ],
|
||||
[ 'Server configured', 'No server yet' ],
|
||||
[ 'Public address', 'Public address needs attention' ],
|
||||
[ 'Clock is set', 'Clock isn’t set' ],
|
||||
];
|
||||
|
||||
function problem_of(title) {
|
||||
for (let p in PROBLEM)
|
||||
if (substr(title, 0, length(p[0])) == p[0])
|
||||
return p[1] + substr(title, length(p[0]));
|
||||
return title;
|
||||
}
|
||||
|
||||
/** problem: the failed check in words, when the table's wording does not fit the case. */
|
||||
function check(id, title, status, detail, fix, problem) {
|
||||
let bad = status == 'warn' || status == 'error';
|
||||
return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? problem_of(title)) : null };
|
||||
}
|
||||
|
||||
/*
|
||||
* 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');
|
||||
}
|
||||
|
||||
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
|
||||
|
||||
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
|
||||
function endpoint_check(id, title, srv, host, proto_note) {
|
||||
if (!host)
|
||||
return check(id, title, 'error', 'No public address: devices will not know where to connect.');
|
||||
let ips = lookup.resolve(host);
|
||||
let wan = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
|
||||
let wc = wan ? ip2int(wan) : null;
|
||||
let cgnat = wc != null && length(filter(PRIVATE, (c) => in_cidr(wc, c))) > 0;
|
||||
if (!length(ips))
|
||||
return check(id, title, 'error', `${host} does not resolve.`);
|
||||
if (cgnat)
|
||||
return check(id, title, 'warn', `WAN address ${wan} is private: forward ${proto_note} on the upstream router, or devices cannot connect.`);
|
||||
if (length(filter(ips, (a) => cloudflare_ip(a))))
|
||||
return check(id, title, 'error', `${host} → ${join(', ', ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.`);
|
||||
if (wan && index(ips, wan) < 0)
|
||||
return check(id, title, 'warn', `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`);
|
||||
return check(id, title, 'ok', `${host} → ${join(', ', ips)}`);
|
||||
}
|
||||
|
||||
const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).";
|
||||
|
||||
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
|
||||
function awg_check() {
|
||||
let st = awg.state();
|
||||
let title = 'AmneziaWG installed';
|
||||
if (length(st.missing ?? []))
|
||||
return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg',
|
||||
'AmneziaWG isn’t installed');
|
||||
if (!st.loaded) {
|
||||
let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out);
|
||||
return check('awg', title, 'error',
|
||||
`The kernel module doesn't load${why ? `: ${why}` : '.'} Reinstall a build for this kernel in Components.`, 'updates',
|
||||
'AmneziaWG’s kernel module doesn’t load');
|
||||
}
|
||||
if (!st.handler)
|
||||
return check('awg', title, 'error', NO_PROTO, 'netrestart', 'The network doesn’t know AmneziaWG yet');
|
||||
return check('awg', title, 'ok', 'Kernel module, awg tool and the netifd protocol are present.');
|
||||
}
|
||||
|
||||
/** Checks of a server's AmneziaWG tunnel. */
|
||||
function awg_checks(m, id, srv, label, fwc, dmp, diverts) {
|
||||
let out = [];
|
||||
let st = live.iface_status(srv.ifname);
|
||||
let up = !!st?.up;
|
||||
let codes = map(st?.errors ?? [], (e) => e.code);
|
||||
if (!up && index(codes, 'INVALID_PROTO') >= 0)
|
||||
push(out, check(`up_${id}`, `AmneziaWG running${label}`, 'error', NO_PROTO, 'netrestart'));
|
||||
else
|
||||
push(out, check(`up_${id}`, `AmneziaWG running${label}`, up ? 'ok' : 'error',
|
||||
up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` :
|
||||
(st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${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) {
|
||||
let p = m.people[d.person];
|
||||
if (p?.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}`, `AmneziaWG 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}`, `AmneziaWG 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}`, `AmneziaWG answers reach devices${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}`, `AmneziaWG 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}`, `AmneziaWG subnet is unique${label}`, length(overlaps) ? 'error' : 'ok',
|
||||
length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The portal's checks: listening, its address, answers, plain HTTP and the certificate. */
|
||||
function portal_checks(m, need, diverts) {
|
||||
let out = [];
|
||||
let s = m.settings;
|
||||
if (length(need.https))
|
||||
return [ check('portal', 'Personal portal', 'error', `HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https') ];
|
||||
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 = lookup.resolve(s.portal_host), wan = lookup.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) ? 'ok' : 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.`));
|
||||
}
|
||||
if (ip2int(s.portal_host) != null) {
|
||||
push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.'));
|
||||
return out;
|
||||
}
|
||||
let cert = pc.portal_cert(s);
|
||||
let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0;
|
||||
let sans = cert.self_signed ? [] : pc.cert_names(cert.cert);
|
||||
let covers = !s.portal_host || cert.self_signed || length(filter(sans, (n) => pc.name_covers(n, s.portal_host))) > 0;
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }.
|
||||
* `fix` names an action accepted by fix(), or one the UI handles itself
|
||||
* (install:<feature>, updates).
|
||||
*/
|
||||
export function health(m) {
|
||||
let diverts = proxy_diverts();
|
||||
m ??= core.load();
|
||||
let out = [];
|
||||
let dmp = live.dump(m);
|
||||
let need = needs();
|
||||
|
||||
if (length(m.servers))
|
||||
push(out, awg_check());
|
||||
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.'));
|
||||
|
||||
let agent = service_running('dawnline', 'agent');
|
||||
push(out, check('agent', 'Background agent running', agent ? 'ok' : 'error',
|
||||
'Counts traffic and enforces end dates and quotas.', 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;
|
||||
}
|
||||
push(out, ...awg_checks(m, id, srv, label, fwc, dmp, diverts));
|
||||
push(out, endpoint_check(`ep_${id}`, `Public address${label}`, srv, core.endpoint_host(m, srv), `UDP ${srv.port}`));
|
||||
|
||||
if (srv.lan_like) {
|
||||
let ls = loop.status();
|
||||
let nh = need.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'));
|
||||
}
|
||||
|
||||
if (m.settings.portal_enabled)
|
||||
push(out, ...portal_checks(m, need, diverts));
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Run a fix named by a check. */
|
||||
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') };
|
||||
// netifd learns protocol handlers (amneziawg) only when it starts. In the
|
||||
// background: the answer goes out before the network blinks.
|
||||
if (id == 'netrestart') {
|
||||
system('( sleep 1; /etc/init.d/network restart ) >/dev/null 2>&1 </dev/null &');
|
||||
return { ok: true, background: true };
|
||||
}
|
||||
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.');
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
// Dawnline — live data: peer status from `awg show all dump`, traffic
|
||||
// Dawnline — live data: peer status from the tunnels (dawnline.awg), traffic
|
||||
// accounting and the connection/event log.
|
||||
//
|
||||
// Counters live in RUN_DIR (tmpfs) and are flushed to DATA_DIR at most once
|
||||
@@ -7,9 +7,10 @@
|
||||
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
|
||||
ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, day_key_ago, uniq,
|
||||
iface_status as util_iface_status, RUN_DIR, DATA_DIR
|
||||
} from 'dawnline.util';
|
||||
import * as awg from 'dawnline.awg';
|
||||
|
||||
export const ONLINE_WINDOW = 300;
|
||||
const KEEP_DAYS = 62;
|
||||
@@ -79,39 +80,18 @@ function trim_events(ev, pol) {
|
||||
return ev;
|
||||
}
|
||||
|
||||
/* ---------- awg dump ---------- */
|
||||
/* ---------- live peers ---------- */
|
||||
|
||||
/**
|
||||
* Parse `awg show all dump`. Returns { ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
|
||||
* Interface lines have many fields (AmneziaWG adds obfuscation values); peer
|
||||
* lines always have 9.
|
||||
* Peers of every tunnel: { ok, ifaces, peers: { public key: { ifname, endpoint,
|
||||
* handshake, rx, tx } } }. See dawnline.awg.
|
||||
*/
|
||||
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 dump(m) {
|
||||
return awg.dump();
|
||||
};
|
||||
|
||||
export function endpoint_ip(ep) {
|
||||
let m = match(ep ?? '', /^\[?([^\]]+?)\]?:[0-9]+$/);
|
||||
let m = match(ep ?? '', /^\[?([^\]]+)\]?:[0-9]+$/);
|
||||
return m ? m[1] : ep;
|
||||
};
|
||||
|
||||
@@ -122,7 +102,10 @@ function empty_usage() {
|
||||
}
|
||||
|
||||
export function load_usage() {
|
||||
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
|
||||
let u = read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
|
||||
// Per-app counters of earlier test builds are not kept.
|
||||
delete u.clients;
|
||||
return u;
|
||||
};
|
||||
|
||||
function add(bucket, key, rx, tx) {
|
||||
@@ -182,30 +165,41 @@ export function reset_usage(usage, m, scope, id) {
|
||||
for (let did in m.people[id]?.devices ?? [])
|
||||
wipe(usage.devices[did]);
|
||||
}
|
||||
else if (scope == 'device') {
|
||||
else if (scope == 'device')
|
||||
wipe(usage.devices[id]);
|
||||
}
|
||||
};
|
||||
|
||||
function offline(rec) {
|
||||
return { online: false, handshake: rec?.handshake ?? 0, endpoint: rec?.endpoint ?? '', present: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* A device missing from the dump had its counters reset only when its tunnel
|
||||
* was actually read: an interface the tool couldn't read says nothing, and
|
||||
* forgetting the last counters there would count them again on the next good
|
||||
* read. A failed read with nothing in it changes nothing at all.
|
||||
*/
|
||||
export function collect(m, usage, d) {
|
||||
d ??= dump();
|
||||
d ??= dump(m);
|
||||
let ts = time();
|
||||
let live = {};
|
||||
let by_key = {};
|
||||
for (let id, dev in m.devices)
|
||||
by_key[dev.public_key] = id;
|
||||
|
||||
if (d.ok === false && !length(d.peers)) {
|
||||
for (let id in keys(m.devices))
|
||||
live[id] = offline(usage.devices[id]);
|
||||
return live;
|
||||
}
|
||||
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 };
|
||||
let ifname = m.servers[m.people[dev.person]?.server]?.ifname;
|
||||
if (d.ok !== false || d.ifaces[ifname] != null)
|
||||
rec.raw = [ 0, 0 ];
|
||||
live[id] = offline(rec);
|
||||
continue;
|
||||
}
|
||||
let raw = rec.raw ?? [ 0, 0 ];
|
||||
@@ -260,9 +254,8 @@ export function save_usage(usage, persist) {
|
||||
/** 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)];
|
||||
let v = rec?.days?.[day_key_ago(i)];
|
||||
if (v) {
|
||||
out[0] += v[0];
|
||||
out[1] += v[1];
|
||||
@@ -278,9 +271,8 @@ export function month(rec) {
|
||||
/** 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 k = day_key_ago(i);
|
||||
let rx = 0, tx = 0;
|
||||
for (let r in recs) {
|
||||
let v = r?.days?.[k];
|
||||
@@ -409,17 +401,7 @@ export function clear_events(f) {
|
||||
/* ---------- 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;
|
||||
}
|
||||
return util_iface_status(ifname);
|
||||
};
|
||||
|
||||
export function uptime() {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// Dawnline — where names point and the router's public address, for Health
|
||||
// and the portal settings. Lookups are cached in RUN_DIR for a few minutes
|
||||
// and made in parallel with a short timeout: rpcd answers one call at a
|
||||
// time, so a slow DNS server must not hold up the whole admin UI.
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { q, sh, ensure_dir, read_json, write_json, ip2int, rand_hex, RUN_DIR } from 'dawnline.util';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as net from 'dawnline.net';
|
||||
|
||||
const CACHE = `${RUN_DIR}/resolve.json`;
|
||||
// Answers are kept 5 minutes, failures 1 minute.
|
||||
const TTL = 300;
|
||||
const TTL_FAIL = 60;
|
||||
const TIMEOUT = 2;
|
||||
const MAX_NAMES = 16;
|
||||
// Public resolvers first: local DNS often rewrites the router's own name to
|
||||
// its LAN address (split horizon).
|
||||
const SERVERS = [ '1.1.1.1', '8.8.8.8', '127.0.0.1' ];
|
||||
|
||||
function valid_name(h) {
|
||||
return type(h) == 'string' && length(h) <= 253 && match(h, /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$/) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* IPv4 addresses of each name: { host: [ ip, … ] } (empty when it does not
|
||||
* resolve). IP addresses map to themselves. Every uncached name is asked of
|
||||
* every server at once; the first server (in SERVERS order) that answers wins.
|
||||
*/
|
||||
export function resolve_all(hosts) {
|
||||
let out = {}, now = time(), todo = [];
|
||||
let cache = read_json(CACHE, {});
|
||||
for (let h in hosts) {
|
||||
if (h == null || out[h] != null)
|
||||
continue;
|
||||
if (ip2int(h) != null) {
|
||||
out[h] = [ h ];
|
||||
continue;
|
||||
}
|
||||
let c = cache[h];
|
||||
if (c && now - c.ts < (length(c.ips) ? TTL : TTL_FAIL))
|
||||
out[h] = c.ips;
|
||||
else if (valid_name(h) && length(todo) < MAX_NAMES) {
|
||||
out[h] = [];
|
||||
push(todo, h);
|
||||
}
|
||||
else
|
||||
out[h] = [];
|
||||
}
|
||||
if (!length(todo))
|
||||
return out;
|
||||
|
||||
ensure_dir(RUN_DIR);
|
||||
let dir = `${RUN_DIR}/resolve.${rand_hex(4)}`;
|
||||
let cmds = [];
|
||||
for (let i = 0; i < length(todo); i++)
|
||||
for (let j = 0; j < length(SERVERS); j++)
|
||||
push(cmds, `( timeout ${TIMEOUT} nslookup ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j} ) &`);
|
||||
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
|
||||
for (let i = 0; i < length(todo); i++) {
|
||||
let ips = [];
|
||||
for (let j = 0; j < length(SERVERS) && !length(ips); j++) {
|
||||
let r = readfile(`${dir}/${i}.${j}`) ?? '';
|
||||
ips = filter(split(trim(r), '\n'), (x) => ip2int(x) != null);
|
||||
}
|
||||
out[todo[i]] = ips;
|
||||
cache[todo[i]] = { ts: now, ips };
|
||||
}
|
||||
system(`rm -rf ${dir}`);
|
||||
// Only what is still fresh is kept.
|
||||
for (let h, c in cache)
|
||||
if (now - c.ts >= TTL)
|
||||
delete cache[h];
|
||||
write_json(CACHE, cache, 0o644);
|
||||
return out;
|
||||
};
|
||||
|
||||
/** IPv4 addresses of one name (see resolve_all). */
|
||||
export function resolve(host) {
|
||||
return resolve_all([ host ])[host] ?? [];
|
||||
};
|
||||
|
||||
/** The IPv4 address of a netifd interface (a zone name for older configs). */
|
||||
export 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). */
|
||||
export 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');
|
||||
};
|
||||
@@ -14,12 +14,11 @@
|
||||
// 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.
|
||||
// Separately, people with Home-only access get a plain resolver
|
||||
// (dawnline.resolver). While the netns exists it runs inside it and sends its
|
||||
// upstream queries back out through the transit link as forwarded traffic —
|
||||
// not as the router's own traffic and not from the LAN — so tools that
|
||||
// capture either leave it alone. This module says where it runs.
|
||||
//
|
||||
// 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
|
||||
@@ -27,18 +26,19 @@
|
||||
|
||||
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, slog, RUN_DIR } from 'dawnline.util';
|
||||
import {
|
||||
sh, sh_out, q, ip2int, int2ip, parse_cidr, cidr_any, ensure_dir, read_json, write_json, slog, RUN_DIR
|
||||
} from 'dawnline.util';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as resolver from 'dawnline.resolver';
|
||||
|
||||
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';
|
||||
export const RESOLVER_CONF = resolver.CONF;
|
||||
const STATE = `${RUN_DIR}/loop.json`;
|
||||
const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ];
|
||||
|
||||
const WHO = 'Internet like a home device';
|
||||
|
||||
@@ -60,17 +60,6 @@ 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. */
|
||||
@@ -160,12 +149,8 @@ function pick_transit(saved) {
|
||||
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)
|
||||
let c = cidr_any(b);
|
||||
if (c && base < c.net + c.size && c.net < base + 4)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -203,9 +188,14 @@ function settings() {
|
||||
return c.get_all('dawnline', 'settings') ?? {};
|
||||
}
|
||||
|
||||
/** Servers that want "like a home device" (default on). */
|
||||
/** Servers that want "like a home device" (default on) and run a core. */
|
||||
function wanted(m) {
|
||||
return filter(values(m.servers), (s) => s.private_key && s.enabled && s.lan_like);
|
||||
return filter(values(m.servers), (s) => length(core.tunnels(s)) && s.enabled && s.lan_like);
|
||||
}
|
||||
|
||||
/** Every server's interface, for rules. */
|
||||
function all_ifnames(m) {
|
||||
return map(values(m.servers), (s) => s.ifname);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -223,7 +213,7 @@ export function plan(m) {
|
||||
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]);
|
||||
let lan = parse_cidr(d.addrs[0]);
|
||||
if (!lan)
|
||||
return { error: `${dev} has no IPv4 address.` };
|
||||
let facts = dhcp_facts(d.logical, lan);
|
||||
@@ -241,7 +231,8 @@ export function plan(m) {
|
||||
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 ]) });
|
||||
for (let t in core.tunnels(srv))
|
||||
push(servers, { ifname: t.ifname, subnet: t.subnet, direct: net.collapse([ t.subnet, ...sn.nets ]) });
|
||||
}
|
||||
return {
|
||||
dev,
|
||||
@@ -332,7 +323,9 @@ function tunnel_ifnames() {
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let out = [];
|
||||
c.foreach('dawnline', 'server', (s) => push(out, s.ifname ?? s['.name']));
|
||||
c.foreach('dawnline', 'server', (s) => {
|
||||
push(out, s.ifname ?? s['.name']);
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -360,13 +353,14 @@ export function remove(ifnames) {
|
||||
* 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 ifnames = all_ifnames(m);
|
||||
let p = plan(m);
|
||||
if (p.off || p.error) {
|
||||
if (stat(STATE) || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames)))
|
||||
// Read before remove(), which deletes it: the error is logged once, not every tick.
|
||||
let was = read_json(STATE, {});
|
||||
if (was.plan || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames)))
|
||||
remove(ifnames);
|
||||
ensure_dir(RUN_DIR);
|
||||
let was = read_json(STATE, {});
|
||||
write_json(STATE, { error: p.error, off: !!p.off }, 0o644);
|
||||
if (p.error && p.error != was.error)
|
||||
log('is off', 'error', p.error);
|
||||
@@ -423,15 +417,6 @@ export function ensure(m, force) {
|
||||
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);
|
||||
if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
|
||||
@@ -441,6 +426,20 @@ export function ensure(m, force) {
|
||||
return p;
|
||||
};
|
||||
|
||||
/**
|
||||
* Keep the chosen LAN address stable across restarts (settings.lan_address).
|
||||
* Called by dawnline.apply once its own lock is released: the config lock is
|
||||
* never taken inside it.
|
||||
*/
|
||||
export function remember(p) {
|
||||
if (!p?.address || settings().lan_address == p.address)
|
||||
return;
|
||||
store.transact((c, m) => {
|
||||
c.set('dawnline', 'settings', 'settings');
|
||||
c.set('dawnline', 'settings', 'lan_address', p.address);
|
||||
});
|
||||
};
|
||||
|
||||
/** Last applied state for views and health checks. */
|
||||
export function status() {
|
||||
let s = read_json(STATE, {});
|
||||
@@ -461,33 +460,6 @@ export function client_dns() {
|
||||
|
||||
/* ---------- 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();
|
||||
@@ -496,7 +468,10 @@ export function lan_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;
|
||||
if (!a)
|
||||
return null;
|
||||
let lan = parse_cidr(a);
|
||||
return (lan ? dhcp_facts(d.logical, lan).dns : null) ?? split(a, '/')[0];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -505,62 +480,17 @@ export function lan_dns() {
|
||||
*/
|
||||
export function resolver_target() {
|
||||
let st = status();
|
||||
return st.active && st.transit ? { mode: 'ns', address: st.transit, port: 53 } : { mode: 'root', port: RESOLVER_PORT };
|
||||
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.
|
||||
*/
|
||||
/** Write the resolver config where it should run now; true when it changed (see dawnline.resolver). */
|
||||
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;
|
||||
return resolver.sync(m, resolver_target(), lan_dns());
|
||||
};
|
||||
|
||||
/** 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;
|
||||
return resolver.running();
|
||||
};
|
||||
|
||||
export const RESOLVER = { port: RESOLVER_PORT, conf: RESOLVER_CONF };
|
||||
export const RESOLVER = { port: resolver.PORT, conf: resolver.CONF };
|
||||
@@ -0,0 +1,64 @@
|
||||
// Dawnline — one-time steps for routers set up by older versions. Each one
|
||||
// checks first and writes nothing when there is nothing to do; dawnline.apply
|
||||
// runs them before it takes its own lock (changes to /etc/config/dawnline go
|
||||
// through dawnline.store and its config lock).
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { stat, unlink } from 'fs';
|
||||
import { q, slog } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as store from 'dawnline.store';
|
||||
|
||||
const LAN_CGI = '/www/cgi-bin/dawnline-portal';
|
||||
const LAN_CGI_URL = '/cgi-bin/dawnline-portal';
|
||||
|
||||
/** Every personal code is a word code; older random ones are replaced (their links stop working). */
|
||||
function word_codes() {
|
||||
let old = (s) => s.code != null && !match(s.code, core.WORD_CODE);
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let any = false;
|
||||
c.foreach('dawnline', 'person', (s) => {
|
||||
if (old(s))
|
||||
any = true;
|
||||
});
|
||||
if (!any)
|
||||
return;
|
||||
store.transact((w, m) => {
|
||||
w.foreach('dawnline', 'person', (s) => {
|
||||
if (old(s)) {
|
||||
w.set('dawnline', s['.name'], 'code', core.new_code());
|
||||
w.delete('dawnline', s['.name'], 'words');
|
||||
}
|
||||
});
|
||||
});
|
||||
slog('dawnline', 'info', 'moved to word codes', null, 'Personal links');
|
||||
}
|
||||
|
||||
/*
|
||||
* Older versions answered on 443 at home through LuCI's web server (its error
|
||||
* page ran the portal CGI). The portal now keeps its own port: remove that.
|
||||
*/
|
||||
export function uhttpd() {
|
||||
let c = cursor();
|
||||
c.load('uhttpd');
|
||||
if (c.get('uhttpd', 'main', 'error_page') == LAN_CGI_URL) {
|
||||
c.delete('uhttpd', 'main', 'error_page');
|
||||
c.commit('uhttpd');
|
||||
system('/etc/init.d/uhttpd reload >/dev/null 2>&1');
|
||||
system(`logger -t dawnline ${q('portal removed from the LuCI web server')}`);
|
||||
}
|
||||
if (stat(LAN_CGI))
|
||||
unlink(LAN_CGI);
|
||||
// The old setting itself.
|
||||
let d = cursor();
|
||||
d.load('dawnline');
|
||||
if (d.get('dawnline', 'settings', 'portal_443') != null)
|
||||
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
|
||||
};
|
||||
|
||||
/** All of them, in order. */
|
||||
export function run() {
|
||||
word_codes();
|
||||
uhttpd();
|
||||
};
|
||||
@@ -14,12 +14,17 @@
|
||||
|
||||
import { readfile, readlink, lsdir, stat } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { sh_out, ip2int, int2ip, uniq } from 'dawnline.util';
|
||||
import { sh_out, ip2int, int2ip, cidr_any, 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' ];
|
||||
const VPN_NAMES = /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/;
|
||||
// Never the WAN while another default route exists: VPN clients. (PPTP and
|
||||
// L2TP stay eligible: some ISPs connect the WAN with them.)
|
||||
const NOT_WAN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc' ];
|
||||
const NOT_WAN_NAMES = /^(wg|awg|tun|tap|ovpn)/;
|
||||
// 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 ] ];
|
||||
@@ -48,16 +53,8 @@ function ubus_json(path, method) {
|
||||
|
||||
/** "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 };
|
||||
let c = cidr_any(s);
|
||||
return c && c.prefix >= 1 ? c : null;
|
||||
}
|
||||
|
||||
function net_str(n) {
|
||||
@@ -107,12 +104,12 @@ export function snapshot(fresh) {
|
||||
return cache;
|
||||
|
||||
// Networks reachable through each device (main table, IPv4).
|
||||
let routes = {}, wan_dev = null;
|
||||
let routes = {}, defaults = [];
|
||||
for (let r in ip_json('-4 route show table main')) {
|
||||
if (!r.dev)
|
||||
continue;
|
||||
if (r.dst == 'default') {
|
||||
wan_dev ??= r.dev;
|
||||
push(defaults, r);
|
||||
continue;
|
||||
}
|
||||
push(routes[r.dev] ??= [], r.dst);
|
||||
@@ -130,6 +127,19 @@ export function snapshot(fresh) {
|
||||
if (dev && !logical[dev])
|
||||
logical[dev] = { name: i.interface, proto: i.proto, up: i.up };
|
||||
}
|
||||
// The WAN: the default route with the lowest metric that does not go into
|
||||
// a VPN client (its default route is not where the tunnels listen); only
|
||||
// VPN routes: the lowest of them.
|
||||
let vpn = (dev) => index(NOT_WAN_PROTOS, logical[dev]?.proto) >= 0 || match(dev, NOT_WAN_NAMES) != null;
|
||||
let wan_dev = null, wan_metric = null, wan_vpn = true;
|
||||
for (let r in defaults) {
|
||||
let v = vpn(r.dev), metric = r.metric ?? 0;
|
||||
if (wan_dev == null || (wan_vpn && !v) || (wan_vpn == v && metric < wan_metric)) {
|
||||
wan_dev = r.dev;
|
||||
wan_metric = metric;
|
||||
wan_vpn = v;
|
||||
}
|
||||
}
|
||||
let zone_by_net = {}, zone_by_dev = {}, zones = [];
|
||||
let fc = cursor();
|
||||
fc.load('firewall');
|
||||
@@ -163,7 +173,7 @@ export function snapshot(fresh) {
|
||||
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)/))
|
||||
else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, VPN_NAMES))
|
||||
cat = 'vpn';
|
||||
else if (kind == 1 || bridge)
|
||||
cat = 'ethernet';
|
||||
@@ -238,7 +248,9 @@ export function server_net(srv, snap) {
|
||||
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 };
|
||||
// The detected LAN missing for a moment (bridge recreated) keeps its zone,
|
||||
// so its forwardings are not removed meanwhile.
|
||||
let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? (p[1] ? srv.lan_zone : null), missing: !d };
|
||||
push(home, h);
|
||||
push(nets, ...h.nets);
|
||||
if (h.zone)
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
// Dawnline — netifd: one AmneziaWG interface per server, named after its
|
||||
// ifname and marked `_dawnline` = server id. Only interfaces Dawnline created
|
||||
// are changed or removed: a name already used by another interface (`lan`, a
|
||||
// tunnel of your own, one from an imported config) is left alone and the
|
||||
// server is reported instead.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { stat, unlink, writefile } from 'fs';
|
||||
import { q, uci_put, uci_section, ack_config, iface_intent, ensure_dir, read_json, write_json, slog, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
|
||||
// Set while AmneziaWG is missing and that was logged (once until it is back).
|
||||
const NO_AWG = `${RUN_DIR}/netifd-no-awg`;
|
||||
|
||||
function log(who, msg, level, detail) {
|
||||
slog('dawnline', level ?? 'info', msg, detail, who);
|
||||
}
|
||||
|
||||
/** The server id that owns network.<ifname>: null when the section is free, '' when someone else's. */
|
||||
export function owner(ifname, c) {
|
||||
if (!c) {
|
||||
c = cursor();
|
||||
c.load('network');
|
||||
}
|
||||
if (c.get('network', ifname) == null)
|
||||
return null;
|
||||
return c.get('network', ifname, '_dawnline') ?? '';
|
||||
};
|
||||
|
||||
/** Bring network config in line with the servers; true when it changed. */
|
||||
export function sync(m) {
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
let changed = false, touched = [], want = {};
|
||||
// Servers whose interface can't be set up (core.BLOCKED), each logged once while it lasts.
|
||||
let was = read_json(core.BLOCKED, {}), blocked = {};
|
||||
let block = (srv, msg, detail) => {
|
||||
blocked[srv.id] = msg;
|
||||
// The rest of this apply works from the same model: no tunnel for it there either.
|
||||
srv.blocked = msg;
|
||||
if (was[srv.id] != msg)
|
||||
log(srv.name, msg, 'error', detail);
|
||||
};
|
||||
|
||||
// Without amneziawg-tools there is no protocol script: changing or bringing
|
||||
// up an interface would only stop a tunnel that is still running.
|
||||
let tools = awg.state().tools;
|
||||
if (tools && stat(NO_AWG))
|
||||
unlink(NO_AWG);
|
||||
else if (!tools && length(filter(values(m.servers), (s) => s.private_key)) && !stat(NO_AWG)) {
|
||||
log('AmneziaWG', "isn't installed: tunnels were left as they are", 'error', 'Install it in Dawnline → Components.');
|
||||
ensure_dir(RUN_DIR);
|
||||
writefile(NO_AWG, `${time()}`);
|
||||
}
|
||||
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.private_key)
|
||||
continue;
|
||||
let ifn = srv.ifname;
|
||||
if (!core.valid_ifname(ifn)) {
|
||||
block(srv, `has an invalid interface name "${ifn}"`, 'Interface name: 1-12 lowercase letters, digits or _.');
|
||||
continue;
|
||||
}
|
||||
let own = owner(ifn, c);
|
||||
if (own != null && own != id) {
|
||||
block(srv, `can't use the network interface ${ifn}: it exists and isn't Dawnline's`,
|
||||
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
|
||||
continue;
|
||||
}
|
||||
delete srv.blocked;
|
||||
want[ifn] = true;
|
||||
if (!tools)
|
||||
continue;
|
||||
// Per server: with several, each changed one has to be brought up again.
|
||||
let mine = uci_section(c, 'network', ifn, 'interface');
|
||||
let set = (opt, val) => {
|
||||
if (uci_put(c, 'network', ifn, opt, val))
|
||||
mine = true;
|
||||
};
|
||||
for (let k, v in awg.netifd_options(srv))
|
||||
set(k, v);
|
||||
set('disabled', srv.enabled ? null : '1');
|
||||
set('auto', srv.enabled ? null : '0');
|
||||
set('_dawnline', id);
|
||||
// For the log once the server is gone.
|
||||
set('_dawnline_name', srv.name);
|
||||
if (mine) {
|
||||
changed = true;
|
||||
push(touched, ifn);
|
||||
// The hotplug log says why the tunnel goes down (not a failure).
|
||||
iface_intent(ifn, srv.enabled ? 'settings' : 'off', srv.name);
|
||||
}
|
||||
}
|
||||
|
||||
if (sprintf('%J', blocked) != sprintf('%J', was)) {
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(core.BLOCKED, blocked, 0o644);
|
||||
}
|
||||
|
||||
// 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) {
|
||||
iface_intent(ifn, 'removed', c.get('network', ifn, '_dawnline_name') ?? ifn);
|
||||
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)}`);
|
||||
// Each tunnel's own line (restarting, turned off, removed) comes from hotplug.
|
||||
system(`logger -t dawnline ${q('network updated: ' + join(', ', [ ...touched, ...stale ]))}`);
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
@@ -0,0 +1,225 @@
|
||||
// Dawnline — the nft table `inet dawnline`: each person's access, enforced
|
||||
// on the tunnel interfaces before anything else on the router sees the
|
||||
// traffic, and where tunnel DNS goes. Its shape follows the servers and their
|
||||
// home networks (rebuild); who is in which set follows people's state and
|
||||
// changes often (update, one atomic transaction).
|
||||
|
||||
import { unlink } from 'fs';
|
||||
import { sh, ensure_dir, write_file, rand_hex, ip2int, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
|
||||
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' ];
|
||||
/** The sets whose members change at run time (update replaces them together). */
|
||||
const SETS = [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'svc_host', 'dns_real' ];
|
||||
|
||||
function ip4(a) {
|
||||
return ip2int(a ?? '') != null;
|
||||
}
|
||||
|
||||
/** Per-person runtime membership: which tunnel addresses may reach what. */
|
||||
export function access_sets(m, usage, states) {
|
||||
// lan_ok: home access (the router itself, the mesh); lan_all: every home
|
||||
// network; lan_part: device . network for people limited to some networks;
|
||||
// mesh_pairs: device . device within a circle (or one person's own devices);
|
||||
// svc_ok: device . service . port; svc_host: device . service with no ports (all of them).
|
||||
let sets = {};
|
||||
for (let k in SETS)
|
||||
sets[k] = [];
|
||||
let snap = net.snapshot();
|
||||
let homes = {}, groups = {};
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
// Off: paused, ended, over quota or out of hours. Addresses go into nft as they are: IPv4 only.
|
||||
if (!p || d.disabled || !ip4(d.address) || states[p.id] != 'active')
|
||||
continue;
|
||||
// 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);
|
||||
let srv = m.servers[p.server];
|
||||
let h = homes[p.id] ??= srv ? core.person_home(srv, p, snap) : { all: true, nets: [] };
|
||||
if (h.all)
|
||||
push(sets.lan_all, d.address);
|
||||
else
|
||||
for (let n in h.nets)
|
||||
push(sets.lan_part, `${d.address} . ${n}`);
|
||||
// Who this device may reach directly: its circle, or at least its owner's devices.
|
||||
if (srv?.mesh == 'circles') {
|
||||
let ci = core.person_circle(m, p);
|
||||
push(groups[ci ? `c:${ci.id}` : `p:${p.id}`] ??= [], d.address);
|
||||
}
|
||||
}
|
||||
else if (p.access == 'lan')
|
||||
for (let sid in p.services) {
|
||||
let s = m.services[sid];
|
||||
if (!s || !ip4(s.address))
|
||||
continue;
|
||||
if (!length(s.ports))
|
||||
push(sets.svc_host, `${d.address} . ${s.address}`);
|
||||
for (let port in s.ports)
|
||||
if (match(port, /^[0-9]+$/))
|
||||
push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`);
|
||||
}
|
||||
}
|
||||
for (let g, addrs in groups)
|
||||
for (let a in addrs)
|
||||
for (let b in addrs)
|
||||
if (a != b)
|
||||
push(sets.mesh_pairs, `${a} . ${b}`);
|
||||
return sets;
|
||||
};
|
||||
|
||||
function set_elems(arr) {
|
||||
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
|
||||
}
|
||||
|
||||
function table(m, sets) {
|
||||
let ifs = [], lan = [], tun = [];
|
||||
let dns_addr = loop.client_dns();
|
||||
if (!ip4(dns_addr))
|
||||
dns_addr = null;
|
||||
let rt = loop.resolver_target();
|
||||
let snap = net.snapshot();
|
||||
for (let id, srv in m.servers) {
|
||||
// Only valid interface names reach here (core.tunnels): they are written into the rules as strings.
|
||||
let tns = core.tunnels(srv);
|
||||
for (let t in tns) {
|
||||
push(ifs, `"${t.ifname}"`);
|
||||
push(tun, t.subnet);
|
||||
}
|
||||
if (length(tns))
|
||||
push(lan, ...net.server_net(srv, snap).nets);
|
||||
}
|
||||
lan = net.collapse(lan);
|
||||
tun = net.collapse(tun);
|
||||
let t = [];
|
||||
push(t, 'table inet dawnline {');
|
||||
push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`);
|
||||
// Tunnel subnets are never "home", even inside a wider route to the LAN.
|
||||
push(t, ` set tun_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(tun)} }`);
|
||||
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
|
||||
push(t, ` set lan_all { type ipv4_addr; ${set_elems(sets.lan_all)} }`);
|
||||
push(t, ` set lan_part { type ipv4_addr . ipv4_addr; flags interval; ${set_elems(sets.lan_part)} }`);
|
||||
push(t, ` set mesh_pairs { type ipv4_addr . ipv4_addr; ${set_elems(sets.mesh_pairs)} }`);
|
||||
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 svc_host { type ipv4_addr . ipv4_addr; ${set_elems(sets.svc_host)} }`);
|
||||
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 daddr != @tun_nets ip saddr @lan_all accept');
|
||||
push(t, ' ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept');
|
||||
// Devices with home access are part of home: they reach each other, where the
|
||||
// server allows it (everyone, or within circles). Within one server: the
|
||||
// firewall has no forwarding between different servers' zones.
|
||||
for (let id, srv in m.servers)
|
||||
for (let tn in core.tunnels(srv))
|
||||
if (srv.mesh == 'all')
|
||||
push(t, ` iifname "${tn.ifname}" ip saddr @lan_ok ip daddr @lan_ok accept`);
|
||||
else if (srv.mesh == 'circles')
|
||||
push(t, ` iifname "${tn.ifname}" ip saddr . ip daddr @mesh_pairs accept`);
|
||||
push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept');
|
||||
push(t, ' ip saddr . ip daddr @svc_host accept');
|
||||
push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`);
|
||||
push(t, ' ip saddr @inet_ok accept');
|
||||
push(t, ' counter drop');
|
||||
push(t, ' }');
|
||||
// The other way: fw4 lets the server's home zones reach the tunnel; here
|
||||
// only connections from its home networks to people with home access pass
|
||||
// (paused, ended and internet-only people are not reachable). The admin's
|
||||
// own port forwards (DNAT) stay with fw4.
|
||||
push(t, ' chain inbound {');
|
||||
push(t, ' type filter hook forward priority filter - 5; policy accept;');
|
||||
if (length(ifs))
|
||||
push(t, ` oifname { ${join(', ', ifs)} } iifname != { ${join(', ', ifs)} } ct state new jump to_device`);
|
||||
push(t, ' }');
|
||||
push(t, ' chain to_device {');
|
||||
push(t, ' meta nfproto ipv6 drop');
|
||||
push(t, ' ct status dnat accept');
|
||||
push(t, ' ip saddr @lan_nets ip saddr != @tun_nets ip daddr @lan_all accept');
|
||||
push(t, ' ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept');
|
||||
push(t, ' counter reject with icmpx admin-prohibited');
|
||||
push(t, ' }');
|
||||
// Devices ask the tunnel address; send each query where it belongs.
|
||||
let to_resolver = rt.mode == 'ns' && ip4(rt.address) ? `dnat ip to ${rt.address}:53` : `redirect to :${+rt.port}`;
|
||||
let lan_dns = loop.lan_dns();
|
||||
if (!ip4(lan_dns))
|
||||
lan_dns = null;
|
||||
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)
|
||||
for (let tn in core.tunnels(srv)) {
|
||||
// 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 "${tn.ifname}" ip daddr ${tn.address} meta l4proto { tcp, udp } th dport 53 ${target}`);
|
||||
}
|
||||
push(t, ' }');
|
||||
push(t, '}');
|
||||
return join('\n', t) + '\n';
|
||||
}
|
||||
|
||||
/** Run an nft script (one transaction); null when it loaded, else what nft said. */
|
||||
function load(script) {
|
||||
ensure_dir(RUN_DIR);
|
||||
// A file of its own: two writers must never load each other's script.
|
||||
let f = `${RUN_DIR}/nft.${rand_hex(4)}.rules`;
|
||||
if (!write_file(f, script))
|
||||
return `couldn't write ${f}`;
|
||||
let r = sh(`nft -f ${f}`);
|
||||
unlink(f);
|
||||
if (r.code == 0)
|
||||
return null;
|
||||
// Without the random file name, so the same failure reads the same every time.
|
||||
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
|
||||
}
|
||||
|
||||
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
|
||||
export function rebuild(m, sets) {
|
||||
return load('table inet dawnline\ndelete table inet dawnline\n' + table(m, sets));
|
||||
};
|
||||
|
||||
/**
|
||||
* Replace the members of every runtime set at once; null or the error. Fails
|
||||
* as a whole when the table or one of its sets is missing (not loaded yet,
|
||||
* or an older shape): the caller then rebuilds.
|
||||
*/
|
||||
export function update(sets) {
|
||||
let s = '';
|
||||
for (let name in SETS) {
|
||||
s += `flush set inet dawnline ${name}\n`;
|
||||
if (length(sets[name]))
|
||||
s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`;
|
||||
}
|
||||
return load(s);
|
||||
};
|
||||
|
||||
/** Is the table loaded (watchdog). */
|
||||
export function present() {
|
||||
return system('nft list table inet dawnline >/dev/null 2>&1') == 0;
|
||||
};
|
||||
|
||||
export function remove() {
|
||||
system('nft delete table inet dawnline 2>/dev/null');
|
||||
};
|
||||
@@ -1,689 +0,0 @@
|
||||
// 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' ] ]),
|
||||
};
|
||||
};
|
||||
|
||||
/** True while OpenWrt's mDNS daemon answers on ubus. */
|
||||
export function mdns_running() {
|
||||
return index(split(sh_out('ubus list umdns 2>/dev/null') ?? '', '\n'), 'umdns') >= 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Services announced on the home networks (Bonjour), from umdns:
|
||||
* [{ type: '_airplay._tcp', name, host, address, port, txt }].
|
||||
*/
|
||||
export function mdns_services() {
|
||||
if (!mdns_running())
|
||||
return [];
|
||||
let r = {};
|
||||
try {
|
||||
r = json(sh_out(`ubus call umdns browse '{"address":true,"array":true}' 2>/dev/null`) || '{}') ?? {};
|
||||
}
|
||||
catch (e) {
|
||||
r = {};
|
||||
}
|
||||
let out = [];
|
||||
for (let t, insts in r)
|
||||
for (let name, i in insts) {
|
||||
let addr = type(i.ipv4) == 'array' ? i.ipv4[0] : i.ipv4;
|
||||
if (addr)
|
||||
push(out, { type: t, name, host: replace(i.host ?? '', /\.local\.?$/, ''), address: addr, port: i.port ?? 0, txt: i.txt ?? [] });
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** 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 };
|
||||
}
|
||||
|
||||
export 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;
|
||||
};
|
||||
|
||||
export 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));
|
||||
};
|
||||
|
||||
export 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 (length(filter(ips, (a) => cloudflare_ip(a))))
|
||||
det = `${host} → ${join(', ', ips)} (Cloudflare). The tunnel is UDP: it reaches the router only if this name is DNS-only there.`;
|
||||
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) ? 'ok' : 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,120 @@
|
||||
// Dawnline — one interface over the router's package manager: opkg on
|
||||
// OpenWrt 24.10, apk on 25.12. Commands that change packages take a log(line)
|
||||
// callback, which gets their output line by line.
|
||||
|
||||
import { access, popen } from 'fs';
|
||||
import { q } from 'dawnline.util';
|
||||
|
||||
function run(cmd) {
|
||||
let p = popen(cmd + ' 2>&1', 'r');
|
||||
if (!p)
|
||||
return { code: 127, out: '' };
|
||||
let out = p.read('all') ?? '';
|
||||
return { code: p.close(), out };
|
||||
}
|
||||
|
||||
function logged(cmd, log) {
|
||||
let r = run(cmd);
|
||||
for (let line in split(trim(r.out), '\n'))
|
||||
if (length(trim(line)))
|
||||
log?.(` ${line}`);
|
||||
return r;
|
||||
}
|
||||
|
||||
export function is_apk() {
|
||||
return access('/usr/bin/apk', 'x');
|
||||
};
|
||||
|
||||
export function ext() {
|
||||
return is_apk() ? 'apk' : 'ipk';
|
||||
};
|
||||
|
||||
/** The installed version of a package, or null. */
|
||||
export function 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;
|
||||
};
|
||||
|
||||
/** The version inside a package file, or null. */
|
||||
export function 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];
|
||||
};
|
||||
|
||||
/**
|
||||
* Compare two package versions the way the package manager does (so -r10 is
|
||||
* newer than -r9 and ~rc before the release): -1, 0 or 1; null when unknown.
|
||||
*/
|
||||
export function cmp(a, b) {
|
||||
if (a == null || b == null)
|
||||
return null;
|
||||
if (a == b)
|
||||
return 0;
|
||||
if (is_apk()) {
|
||||
let r = trim(run(`apk version -t ${q(a)} ${q(b)}`).out);
|
||||
return r == '<' ? -1 : r == '>' ? 1 : r == '=' ? 0 : null;
|
||||
}
|
||||
if (run(`opkg compare-versions ${q(a)} '<<' ${q(b)}`).code == 0)
|
||||
return -1;
|
||||
if (run(`opkg compare-versions ${q(a)} '>>' ${q(b)}`).code == 0)
|
||||
return 1;
|
||||
return 0;
|
||||
};
|
||||
|
||||
export function refresh(log) {
|
||||
return logged(is_apk() ? 'apk update' : 'opkg update', log).code == 0;
|
||||
};
|
||||
|
||||
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
|
||||
export function install_files(files, force, log) {
|
||||
let args = join(' ', map(files, q));
|
||||
return logged(is_apk()
|
||||
? `apk add --allow-untrusted ${args}`
|
||||
: `opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
|
||||
};
|
||||
|
||||
/** Packages by name from the feeds. */
|
||||
export function add(names, log) {
|
||||
return logged(is_apk() ? `apk add ${join(' ', map(names, q))}` : `opkg install ${join(' ', map(names, q))}`, log).code == 0;
|
||||
};
|
||||
|
||||
export function upgrade(names, log) {
|
||||
return logged(is_apk() ? `apk upgrade ${join(' ', map(names, q))}` : `opkg upgrade ${join(' ', map(names, q))}`, log).code == 0;
|
||||
};
|
||||
|
||||
export function remove(names, log) {
|
||||
return logged(is_apk() ? `apk del ${join(' ', map(names, q))}` : `opkg remove ${join(' ', map(names, q))}`, log).code == 0;
|
||||
};
|
||||
|
||||
/** Installed packages with a newer version in the feeds: { name: latest }. */
|
||||
export function upgradable() {
|
||||
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;
|
||||
};
|
||||
@@ -0,0 +1,463 @@
|
||||
// Dawnline — the personal portal.
|
||||
//
|
||||
// GET /<code> the app shell
|
||||
// GET /<code>/assets/<file> its script, styles and 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|rotate|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 client
|
||||
// (blocked clients get the same 404 even with the right code): per IPv4
|
||||
// address or IPv6 /64; behind Cloudflare per visitor (CF-Connecting-IP), with
|
||||
// a higher ceiling for all Cloudflare visitors together.
|
||||
// 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 limits, and not those the admin turned off (dawnline.devices).
|
||||
//
|
||||
// handle() serves one request: `io` = { env, headers, read(n), write(s) }; the
|
||||
// CGI script (www/cgi-bin/portal) is its wrapper.
|
||||
|
||||
import { stat, readfile } from 'fs';
|
||||
import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as view from 'dawnline.view';
|
||||
import * as schema from 'dawnline.schema';
|
||||
import * as devices from 'dawnline.devices';
|
||||
|
||||
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', png: 'image/png' };
|
||||
const FAIL_LIMIT = 8;
|
||||
const FAIL_WINDOW = 900;
|
||||
// All Cloudflare visitors together (three-word codes can't be guessed anyway).
|
||||
const SHARED_LIMIT = FAIL_LIMIT * 25;
|
||||
const SHARED_KEY = 'cloudflare';
|
||||
// Clients remembered at most (the oldest go first).
|
||||
const RATE_MAX = 2000;
|
||||
const BODY_MAX = 8192;
|
||||
// The early end of a request (a response was written).
|
||||
const DONE = '__dawnline_done__';
|
||||
|
||||
const SECURITY_HEADERS = {
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
'X-Frame-Options': 'DENY',
|
||||
'Cache-Control': 'no-store',
|
||||
};
|
||||
|
||||
const NOT_READY = "Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.";
|
||||
|
||||
function html_escape(s) {
|
||||
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
||||
}
|
||||
|
||||
/* ---------- answering ---------- */
|
||||
|
||||
function headers(r, status, extra) {
|
||||
let h = `Status: ${status}\r\n`;
|
||||
let all = { ...SECURITY_HEADERS, ...(extra ?? {}) };
|
||||
// HSTS pins the whole name: only when the visitor is on the standard port.
|
||||
if (r.hsts)
|
||||
all['Strict-Transport-Security'] = 'max-age=31536000';
|
||||
for (let k, v in all)
|
||||
h += `${k}: ${v}\r\n`;
|
||||
r.io.write(h + '\r\n');
|
||||
}
|
||||
|
||||
function finish() {
|
||||
die(DONE);
|
||||
}
|
||||
|
||||
function send_json(r, status, obj) {
|
||||
headers(r, status, { 'Content-Type': 'application/json' });
|
||||
r.io.write(sprintf('%J', obj));
|
||||
finish();
|
||||
}
|
||||
|
||||
function fail(r, status, msg) {
|
||||
send_json(r, status, { error: msg });
|
||||
}
|
||||
|
||||
/**
|
||||
* The one answer for anything without a valid code: a bare 404, or the redirect from Settings.
|
||||
* Files always get the 404: a missing asset must not turn into someone's website.
|
||||
*/
|
||||
function not_found(r) {
|
||||
let redirect = r.m.settings.portal_redirect;
|
||||
let parts = split(r.path, '/');
|
||||
let file = match(r.path, /^\/(luci-static|cgi-bin|ubus)(\/|$)/) || match(parts[length(parts) - 1], /\./);
|
||||
if (redirect && !file) {
|
||||
headers(r, '302 Found', { 'Location': redirect, 'Cache-Control': 'no-store', 'Content-Type': 'text/plain' });
|
||||
r.io.write('Moved\n');
|
||||
}
|
||||
else {
|
||||
headers(r, '404 Not Found', { 'Content-Type': 'text/plain' });
|
||||
r.io.write('Not found\n');
|
||||
}
|
||||
finish();
|
||||
}
|
||||
|
||||
/** The JSON object a POST carries ({} without a body). */
|
||||
function body(r) {
|
||||
let len = +(r.env.CONTENT_LENGTH ?? 0);
|
||||
if (len <= 0)
|
||||
return {};
|
||||
if (len > BODY_MAX)
|
||||
fail(r, '413 Payload Too Large', 'Request too large.');
|
||||
let raw = '';
|
||||
while (length(raw) < len) {
|
||||
let chunk = r.io.read(len - length(raw));
|
||||
if (chunk == null || chunk == '')
|
||||
break;
|
||||
raw += chunk;
|
||||
}
|
||||
try {
|
||||
let j = json(raw);
|
||||
return type(j) == 'object' ? j : {};
|
||||
}
|
||||
catch (e) {
|
||||
fail(r, '400 Bad Request', 'Invalid JSON.');
|
||||
}
|
||||
}
|
||||
|
||||
/** Run a change; what it refuses becomes a 400 with its message. */
|
||||
function guard(r, fn) {
|
||||
try {
|
||||
return fn();
|
||||
}
|
||||
catch (e) {
|
||||
if (e.message == DONE)
|
||||
die(DONE);
|
||||
fail(r, '400 Bad Request', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- rate limiting ---------- */
|
||||
|
||||
/** The rate-limit key of an address: an IPv4 address, or the /64 of an IPv6 one. */
|
||||
function addr_key(a) {
|
||||
if (schema.ipv4(a))
|
||||
return a;
|
||||
let g = schema.ipv6_groups(a);
|
||||
if (!g)
|
||||
return null;
|
||||
// An IPv4 address seen through an IPv6 socket.
|
||||
if (g[0] == 0 && g[1] == 0 && g[2] == 0 && g[3] == 0 && g[4] == 0 && g[5] == 0xffff)
|
||||
return sprintf('%d.%d.%d.%d', g[6] >> 8, g[6] & 255, g[7] >> 8, g[7] & 255);
|
||||
return sprintf('%x:%x:%x:%x::/64', g[0], g[1], g[2], g[3]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The buckets a request counts against, [{ key, limit }]: its client, and
|
||||
* behind Cloudflare (the only proxy whose CF-Connecting-IP is believed) also
|
||||
* the bucket all Cloudflare visitors share.
|
||||
*/
|
||||
function buckets(env) {
|
||||
let peer = env.REMOTE_ADDR ?? '';
|
||||
if (!cloudflare_ip(peer))
|
||||
return [ { key: addr_key(peer) ?? peer, limit: FAIL_LIMIT } ];
|
||||
let out = [ { key: SHARED_KEY, limit: SHARED_LIMIT } ];
|
||||
let visitor = addr_key(trim(env.HTTP_CF_CONNECTING_IP ?? ''));
|
||||
if (visitor && !cloudflare_ip(visitor))
|
||||
unshift(out, { key: visitor, limit: FAIL_LIMIT });
|
||||
return out;
|
||||
}
|
||||
|
||||
function rate_state() {
|
||||
let st = read_json(RATE, {});
|
||||
let now = time();
|
||||
for (let k, v in st)
|
||||
if (type(v) != 'object' || now - v.first > FAIL_WINDOW)
|
||||
delete st[k];
|
||||
return st;
|
||||
}
|
||||
|
||||
function rate_blocked(r) {
|
||||
let st = rate_state();
|
||||
return length(filter(r.buckets, (b) => (st[b.key]?.count ?? 0) >= b.limit)) > 0;
|
||||
}
|
||||
|
||||
function rate_fail(r) {
|
||||
let l = lock('portal-rate');
|
||||
let st = rate_state();
|
||||
let now = time();
|
||||
let hit = [];
|
||||
for (let b in r.buckets) {
|
||||
let v = st[b.key] ?? { first: now, count: 0 };
|
||||
v.count++;
|
||||
st[b.key] = v;
|
||||
if (v.count == b.limit)
|
||||
push(hit, b.key);
|
||||
}
|
||||
// Bounded: an attacker with many addresses cannot grow the file without end.
|
||||
let all = keys(st);
|
||||
if (length(all) > RATE_MAX) {
|
||||
all = sort(all, (a, b) => st[a].first - st[b].first);
|
||||
for (let i = 0; i < length(all) - RATE_MAX; i++)
|
||||
delete st[all[i]];
|
||||
}
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(RATE, st, 0o600);
|
||||
unlock(l);
|
||||
for (let k in hit)
|
||||
live.add_event({ type: 'portal_blocked', detail: k == SHARED_KEY ? 'all Cloudflare visitors' : k });
|
||||
}
|
||||
|
||||
/* ---------- pages ---------- */
|
||||
|
||||
/** The app shell; it reads the code from its own URL and sends it along. */
|
||||
function shell(r) {
|
||||
// The build's time joins the version so every update busts the hour-long asset cache.
|
||||
let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
|
||||
let base = r.base, title = r.title;
|
||||
headers(r, '200 OK', {
|
||||
'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'",
|
||||
});
|
||||
r.io.write(`<!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${v}" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="${base}/assets/portal.css${v}">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" data-base="${html_escape(base)}" data-title="${html_escape(title)}"></div>
|
||||
<script src="${base}/assets/portal.js${v}" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
`);
|
||||
finish();
|
||||
}
|
||||
|
||||
/** Script, styles, icon and fonts (kept outside the web root). */
|
||||
function asset(r, name) {
|
||||
let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2|png)$/)?.[1];
|
||||
let data = ext ? readfile(`${ASSETS}/${name}`) : null;
|
||||
if (data == null)
|
||||
not_found(r);
|
||||
headers(r, '200 OK', { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=3600' });
|
||||
r.io.write(data);
|
||||
finish();
|
||||
}
|
||||
|
||||
/* ---------- the API ---------- */
|
||||
|
||||
/** The model again after a change. */
|
||||
function reload(r) {
|
||||
r.m = core.load();
|
||||
r.person = r.m.people[r.person.id];
|
||||
if (!r.person)
|
||||
not_found(r);
|
||||
}
|
||||
|
||||
/** Everything the page shows. */
|
||||
function state(r) {
|
||||
let m = r.m, person = r.person;
|
||||
let usage = core.load_usage();
|
||||
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
|
||||
let srv = m.servers[person.server];
|
||||
// The device this page was opened from, when it came through the tunnel.
|
||||
let here = null;
|
||||
for (let id, d in m.devices)
|
||||
if (d.person == person.id && d.address == r.peer)
|
||||
here = id;
|
||||
return {
|
||||
title: r.title,
|
||||
person: v,
|
||||
here,
|
||||
server: {
|
||||
name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh,
|
||||
// AmneziaWG with the disguise off is plain WireGuard (any WireGuard app).
|
||||
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
|
||||
},
|
||||
can_add: length(person.devices) < person.device_limit,
|
||||
kinds: core.KINDS,
|
||||
// The router's day: access ends and usage days follow its clock, not the browser's.
|
||||
today: today(),
|
||||
version: VERSION,
|
||||
};
|
||||
}
|
||||
|
||||
/** One of the person's own devices, or a 404. */
|
||||
function own_device(r, id) {
|
||||
let d = r.m.devices[id];
|
||||
if (!d || d.person != r.person.id)
|
||||
fail(r, '404 Not Found', 'Device not found.');
|
||||
return d;
|
||||
}
|
||||
|
||||
function api_state(r) {
|
||||
send_json(r, '200 OK', state(r));
|
||||
}
|
||||
|
||||
function api_add(r) {
|
||||
let b = body(r);
|
||||
if (!devices.ready())
|
||||
fail(r, '503 Service Unavailable', NOT_READY);
|
||||
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
|
||||
reload(r);
|
||||
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
|
||||
}
|
||||
|
||||
function api_config(r, id) {
|
||||
let d = own_device(r, id);
|
||||
awg.mark_issued(r.m, d.id);
|
||||
send_json(r, '200 OK', awg.client_config(r.m, d));
|
||||
}
|
||||
|
||||
/** POST /devices/<id> { action }: what each action does; the answer carries the new state. */
|
||||
const ACTIONS = {
|
||||
rename: (r, d, b) => {
|
||||
guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id }));
|
||||
return {};
|
||||
},
|
||||
rotate: (r, d, b) => {
|
||||
if (!devices.ready())
|
||||
fail(r, '503 Service Unavailable', NOT_READY);
|
||||
let config = guard(r, () => devices.rotate(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
|
||||
return { config };
|
||||
},
|
||||
'delete': (r, d, b) => {
|
||||
guard(r, () => devices.remove(d.id, { by: 'portal', person: r.person.id }));
|
||||
return {};
|
||||
},
|
||||
};
|
||||
|
||||
function api_device(r, id) {
|
||||
let d = own_device(r, id);
|
||||
let b = body(r);
|
||||
let act = ACTIONS[b.action];
|
||||
if (!act)
|
||||
fail(r, '400 Bad Request', 'Unknown action.');
|
||||
let res = act(r, d, b);
|
||||
reload(r);
|
||||
send_json(r, '200 OK', { ok: true, ...res, state: state(r) });
|
||||
}
|
||||
|
||||
/** API routes: method, path under /<code>/api ('*' matches one segment, passed to run). */
|
||||
const API = [
|
||||
{ method: 'GET', path: [ 'state' ], run: api_state },
|
||||
{ method: 'POST', path: [ 'devices' ], run: api_add },
|
||||
{ method: 'GET', path: [ 'devices', '*', 'config' ], run: api_config },
|
||||
{ method: 'POST', path: [ 'devices', '*' ], run: api_device },
|
||||
];
|
||||
|
||||
/** The route for a request: { run, args } or null (routes take at most one '*'). */
|
||||
function route(table, method, segs) {
|
||||
for (let rt in table) {
|
||||
if (rt.method != method || length(rt.path) != length(segs))
|
||||
continue;
|
||||
let args = [], ok = true;
|
||||
for (let i = 0; i < length(segs) && ok; i++)
|
||||
if (rt.path[i] == '*')
|
||||
push(args, segs[i]);
|
||||
else if (rt.path[i] != segs[i])
|
||||
ok = false;
|
||||
if (ok)
|
||||
return { run: rt.run, args };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ---------- one request ---------- */
|
||||
|
||||
export function handle(io) {
|
||||
let env = io.env ?? {};
|
||||
// Header names arrive lower-case from uhttpd; CGI has only HTTP_* variables.
|
||||
let hdr = {};
|
||||
for (let k, v in io.headers ?? {})
|
||||
hdr[lc(k)] = v;
|
||||
let header = (name) => hdr[name] ?? env[`HTTP_${uc(replace(name, /-/g, '_'))}`];
|
||||
let uri = env.REQUEST_URI ?? '/';
|
||||
let qpos = index(uri, '?');
|
||||
let path = qpos >= 0 ? substr(uri, 0, qpos) : uri;
|
||||
let https = env.HTTPS == 'on';
|
||||
let host = header('host') ?? '';
|
||||
let m = core.load();
|
||||
let r = {
|
||||
io, env, m, path, https,
|
||||
method: env.REQUEST_METHOD ?? 'GET',
|
||||
peer: env.REMOTE_ADDR ?? '',
|
||||
buckets: buckets(env),
|
||||
title: m.settings.portal_title || 'Dawnline',
|
||||
// The port in the visitor's address bar ([v6]:port, name:port, or the default).
|
||||
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
|
||||
person: null,
|
||||
base: '',
|
||||
};
|
||||
let segs = filter(split(path, '/'), (s) => s != '');
|
||||
|
||||
// Plain HTTP only for an IP address chosen in Settings (no certificate exists
|
||||
// for it); names stay HTTPS-only.
|
||||
if (!https) {
|
||||
let h = match(host, /^\[/) ? host : split(host, ':')[0];
|
||||
if (ip2int(h) == null || index(core.portal_hosts(m), h) < 0)
|
||||
not_found(r);
|
||||
}
|
||||
// The link is /<word-code>[/assets/…|/api/…]: the code is the address.
|
||||
if (length(segs) < 1 || !match(segs[0], core.WORD_CODE))
|
||||
not_found(r);
|
||||
let code = segs[0];
|
||||
for (let id, p in m.people)
|
||||
if (p.code == code)
|
||||
r.person = p;
|
||||
|
||||
// A wrong code or a blocked client: indistinguishable from a path that does
|
||||
// not exist. Only well-formed guesses count towards the limit.
|
||||
if (rate_blocked(r))
|
||||
not_found(r);
|
||||
if (r.person == null) {
|
||||
rate_fail(r);
|
||||
not_found(r);
|
||||
}
|
||||
r.base = `/${code}`;
|
||||
let rest = slice(segs, 1);
|
||||
|
||||
if (length(rest) == 0 && r.method == 'GET')
|
||||
shell(r);
|
||||
if (rest[0] == 'assets' && length(rest) == 2 && r.method == 'GET')
|
||||
asset(r, rest[1]);
|
||||
if (rest[0] != 'api')
|
||||
not_found(r);
|
||||
|
||||
// CSRF: only same-origin JSON requests (a cross-site page cannot send
|
||||
// application/json without CORS, and it would need the code anyway).
|
||||
if (r.method == 'POST') {
|
||||
let origin = header('origin');
|
||||
if (!match(env.CONTENT_TYPE ?? '', /^application\/json/) ||
|
||||
(origin != null && origin != `${https ? 'https' : 'http'}://${host}`))
|
||||
fail(r, '403 Forbidden', 'Cross-site request refused.');
|
||||
}
|
||||
else if (r.method != 'GET')
|
||||
fail(r, '405 Method Not Allowed', 'Method not allowed.');
|
||||
|
||||
let rt = route(API, r.method, slice(rest, 1));
|
||||
if (!rt)
|
||||
fail(r, '404 Not Found', 'Not found.');
|
||||
rt.run(r, rt.args[0]);
|
||||
fail(r, '404 Not Found', 'Not found.');
|
||||
};
|
||||
|
||||
/** Run handle() and swallow its early end. */
|
||||
export function serve(io) {
|
||||
try {
|
||||
handle(io);
|
||||
}
|
||||
catch (e) {
|
||||
if (e.message != DONE)
|
||||
io.write(`Status: 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\nError\n`);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
// Dawnline — the portal's certificate (configured, ACME or self-signed) and
|
||||
// the addresses its links could use.
|
||||
|
||||
import { lsdir } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { q, sh, sh_out, ensure_dir, file_exists, valid_host, ip2int, cloudflare_ip, DATA_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as lookup from 'dawnline.lookup';
|
||||
|
||||
/** The DNS names a certificate file covers. */
|
||||
export function cert_names(path) {
|
||||
let sans = sh_out(`openssl x509 -in ${q(path)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '';
|
||||
return filter(split(replace(sans, /DNS:/g, ''), /[ \t\r\n]+/), (x) => x != '');
|
||||
};
|
||||
|
||||
/** A certificate name covers host: the same name, or a wildcard one level up. */
|
||||
export function name_covers(name, host) {
|
||||
if (name == host)
|
||||
return true;
|
||||
let dot = index(host ?? '', '.');
|
||||
return substr(name, 0, 2) == '*.' && dot > 0 && substr(host, dot) == substr(name, 1);
|
||||
};
|
||||
|
||||
/** ACME certificates on the router and the names each covers. */
|
||||
export function acme_certs() {
|
||||
let out = [];
|
||||
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
|
||||
let m = match(f, /^(.+)\.fullchain\.crt$/);
|
||||
if (!m)
|
||||
continue;
|
||||
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
|
||||
if (file_exists(k))
|
||||
push(out, { cert: c, key: k, names: cert_names(c) });
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** The ACME certificate that covers host (exact name or a wildcard), if any. */
|
||||
export function acme_cert_for(host) {
|
||||
for (let a in acme_certs())
|
||||
for (let n in a.names)
|
||||
if (name_covers(n, host))
|
||||
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 };
|
||||
};
|
||||
|
||||
/*
|
||||
* 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 = lookup.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);
|
||||
};
|
||||
let certs = acme_certs();
|
||||
for (let a in 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 found = lookup.resolve_all(names);
|
||||
let covered = (h) => length(filter(certs, (a) => length(filter(a.names, (n) => name_covers(n, h))) > 0)) > 0;
|
||||
let out = [];
|
||||
for (let h in names) {
|
||||
let ips = found[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: covered(h) });
|
||||
}
|
||||
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));
|
||||
};
|
||||
@@ -0,0 +1,99 @@
|
||||
// Dawnline — the plain resolver for people with Home-only access: 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. dawnline.loop
|
||||
// says where it runs (inside the netns while it exists, otherwise on the
|
||||
// tunnel interfaces); procd runs dnsmasq through /usr/libexec/dawnline/resolver.
|
||||
|
||||
import { readfile, writefile, stat } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { ensure_dir, iface_status, uniq } from 'dawnline.util';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as core from 'dawnline.core';
|
||||
|
||||
/** Port on the tunnel addresses while it runs on the router itself. */
|
||||
export const PORT = 5354;
|
||||
export const CONF = '/var/etc/dawnline-dns.conf';
|
||||
const RESOLV = '/var/etc/dawnline-dns.resolv';
|
||||
const PID = '/var/run/dawnline-dns.pid';
|
||||
const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ];
|
||||
|
||||
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;
|
||||
for (let a in iface_status(name)?.['dns-server'] ?? [])
|
||||
if (match(a, /^[0-9.]+$/))
|
||||
push(out, a);
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
/** True when the resolver process is alive. */
|
||||
export function running() {
|
||||
let pid = trim(readfile(PID) ?? '');
|
||||
return match(pid, /^[0-9]+$/) != null && stat(`/proc/${pid}`) != null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Write the config for `target` (dawnline.loop resolver_target) with home
|
||||
* names from `lan` (the LAN's DNS); 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(m, target, lan) {
|
||||
ensure_dir('/var/etc');
|
||||
let ifs = [];
|
||||
for (let id, s in m.servers)
|
||||
for (let t in core.tunnels(s))
|
||||
push(ifs, t.ifname);
|
||||
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=${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 {
|
||||
// No tunnel yet: loopback only (without any interface= line dnsmasq would answer everywhere).
|
||||
push(lines, 'bind-dynamic', ...(length(ifs) ? map(ifs, (i) => `interface=${i}`) : [ 'listen-address=127.0.0.1' ]), `resolv-file=${RESOLV}`);
|
||||
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
|
||||
if ((readfile(RESOLV) ?? '') != resolv) {
|
||||
writefile(RESOLV, resolv);
|
||||
system(`chmod 644 ${RESOLV}`);
|
||||
}
|
||||
}
|
||||
if (lan)
|
||||
for (let d in lan_domain(m))
|
||||
push(lines, `server=/${d}/${lan}`);
|
||||
let conf = join('\n', lines) + '\n';
|
||||
if ((readfile(CONF) ?? '') == conf)
|
||||
return false;
|
||||
writefile(CONF, conf);
|
||||
system(`chmod 644 ${CONF}`);
|
||||
let pid = trim(readfile(PID) ?? '');
|
||||
if (match(pid, /^[0-9]+$/))
|
||||
system(`kill ${pid} 2>/dev/null`);
|
||||
return true;
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
// Dawnline — what the rpcd method modules (dawnline.rpc.*) share: the call
|
||||
// wrapper, argument helpers, the disguise check and the portal port check.
|
||||
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as schema from 'dawnline.schema';
|
||||
|
||||
/**
|
||||
* An rpcd handler from fn(args): an object result is passed on, anything else
|
||||
* is wrapped as { result }, and a failure becomes { error } (the UI shows it).
|
||||
*/
|
||||
export function wrap(fn) {
|
||||
return function(req) {
|
||||
try {
|
||||
let r = fn(req.args ?? {});
|
||||
return type(r) == 'object' ? r : { result: r };
|
||||
}
|
||||
catch (e) {
|
||||
return { error: e.message ?? `${e}` };
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/** An argument as a trimmed string ('' for null). */
|
||||
export function str(v) {
|
||||
return v == null ? '' : trim(`${v}`);
|
||||
};
|
||||
|
||||
/** Days of history a caller may ask for: 1–400, default 30. */
|
||||
export function clamp_days(v) {
|
||||
let n = +(v ?? 30);
|
||||
return n >= 1 ? (n > 400 ? 400 : int(n)) : 30;
|
||||
};
|
||||
|
||||
export const METHODS = [ 'off', 'standard', 'strong', 'max' ];
|
||||
|
||||
/** A disguise method the installed AmneziaWG can run. */
|
||||
export function check_method(name) {
|
||||
if (index(METHODS, name) < 0)
|
||||
die('Unknown disguise method.');
|
||||
if (name == 'max' && !awg.caps().v3)
|
||||
die(awg.installed()
|
||||
? 'Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1): install a 3.1 build in Dawnline → Components.'
|
||||
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Maximum.');
|
||||
return name;
|
||||
};
|
||||
|
||||
/**
|
||||
* The portal's ports in the final configuration `m` (compared with `was`,
|
||||
* before the change) are acceptable: its HTTPS port and, when links on IP
|
||||
* addresses use plain HTTP, the next port too — both get a WAN ACCEPT rule.
|
||||
* Neither may be 22, 53, 80 or 443, beyond 65535, or taken by another program.
|
||||
*/
|
||||
export function check_portal(m, was) {
|
||||
let s = m.settings;
|
||||
if (!s.portal_enabled)
|
||||
return;
|
||||
let port = s.portal_port;
|
||||
if (!schema.valid_port(port) || index(schema.RESERVED_PORTS, port) >= 0)
|
||||
die('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).');
|
||||
let ports = [ port ];
|
||||
if (core.portal_http(m)) {
|
||||
let hp = core.portal_http_port(m);
|
||||
if (!schema.valid_port(hp) || index(schema.RESERVED_PORTS, hp) >= 0)
|
||||
die(`Links on IP addresses use plain HTTP on the next port (${hp}), which the portal cannot take. Choose another portal port.`);
|
||||
push(ports, hp);
|
||||
}
|
||||
// Only ports the portal does not hold already: our own uhttpd is not an owner anyway.
|
||||
let held = [];
|
||||
if (was?.settings?.portal_enabled) {
|
||||
push(held, was.settings.portal_port);
|
||||
if (core.portal_http(was))
|
||||
push(held, core.portal_http_port(was));
|
||||
}
|
||||
for (let p in ports) {
|
||||
if (index(held, p) >= 0)
|
||||
continue;
|
||||
let owners = health.tcp_port_owners(p);
|
||||
if (length(owners))
|
||||
die(`TCP ${p} is already used by ${join(', ', owners)}.${p != port ? ' Links on IP addresses use plain HTTP on the port after the portal\'s.' : ''} Choose another portal port.`);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,214 @@
|
||||
// Dawnline rpcd methods: what people reach at home — services (home
|
||||
// devices and ports), circles (who reaches whom), the devices found at home,
|
||||
// and "Check access".
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { sh_out, ip2int, rand_int, rand_hex, admin_log } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as access from 'dawnline.access';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as schema from 'dawnline.schema';
|
||||
import { wrap, str } from 'dawnline.rpc.common';
|
||||
|
||||
/* ---------- services ---------- */
|
||||
|
||||
/** A new id from make() that no section has yet. */
|
||||
function new_id(m, make) {
|
||||
for (let i = 0; i < 20; i++) {
|
||||
let id = make();
|
||||
if (!store.id_taken(m, id))
|
||||
return id;
|
||||
}
|
||||
die('Could not find a free id, try again.');
|
||||
}
|
||||
|
||||
function service_set(a) {
|
||||
let name = str(a.name);
|
||||
if (name == '' || length(name) > 48)
|
||||
die('Enter a service name.');
|
||||
let address = str(a.address);
|
||||
if (!schema.ipv4(address))
|
||||
die('Address must be an IPv4 address.');
|
||||
let ports = filter(map(type(a.ports) == 'array' ? a.ports : split(str(a.ports), /[ ,]+/), str), (x) => x != '');
|
||||
for (let pt in ports)
|
||||
if (!schema.valid_port(pt))
|
||||
die(`Invalid port ${pt}.`);
|
||||
let id = store.transact((c, m) => {
|
||||
let id = str(a.id);
|
||||
if (id == '')
|
||||
id = new_id(m, () => `svc_${rand_int(100000, 999999)}`);
|
||||
else if (!match(id, /^[A-Za-z0-9_]{1,32}$/))
|
||||
die('Invalid service id.');
|
||||
// Never turn a person, device, server, circle or the settings into a service.
|
||||
else if (!m.services[id] && store.id_taken(m, id))
|
||||
die('That id is taken.');
|
||||
c.set(core.CONFIG, id, 'service');
|
||||
c.set(core.CONFIG, id, 'name', name);
|
||||
c.set(core.CONFIG, id, 'address', address);
|
||||
if (length(ports))
|
||||
c.set(core.CONFIG, id, 'port', ports);
|
||||
else
|
||||
c.delete(core.CONFIG, id, 'port');
|
||||
return id;
|
||||
});
|
||||
apply.sync();
|
||||
return { id };
|
||||
}
|
||||
|
||||
function service_delete(a) {
|
||||
store.transact((c, m) => {
|
||||
if (!m.services[a.id])
|
||||
die('Unknown service.');
|
||||
c.delete(core.CONFIG, a.id);
|
||||
for (let pid, p in m.people)
|
||||
if (index(p.services, a.id) >= 0) {
|
||||
let rest = filter(p.services, (x) => x != a.id);
|
||||
if (length(rest))
|
||||
c.set(core.CONFIG, pid, 'service', rest);
|
||||
else
|
||||
c.delete(core.CONFIG, pid, 'service');
|
||||
}
|
||||
});
|
||||
apply.sync();
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/* ---------- circles ---------- */
|
||||
|
||||
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
|
||||
function circle_set(a) {
|
||||
let name = str(a.name);
|
||||
if (name == '' || length(name) > 32)
|
||||
die('Enter a circle name (up to 32 characters).');
|
||||
let res = store.transact((c, m) => {
|
||||
let ci = a.id ? m.circles[a.id] : null;
|
||||
if (a.id && !ci)
|
||||
die('Unknown circle.');
|
||||
let server = ci?.server ?? a.server;
|
||||
if (!m.servers[server])
|
||||
die('Unknown server.');
|
||||
for (let id, o in m.circles)
|
||||
if (id != a.id && o.server == server && lc(o.name) == lc(name))
|
||||
die(`${name} already exists.`);
|
||||
let id = ci?.id ?? new_id(m, () => `c_${rand_hex(4)}`);
|
||||
let n = core.CIRCLE_COLORS;
|
||||
c.set(core.CONFIG, id, 'circle');
|
||||
c.set(core.CONFIG, id, 'server', server);
|
||||
c.set(core.CONFIG, id, 'name', name);
|
||||
c.set(core.CONFIG, id, 'color', `${((int(a.color) || 0) % n + n) % n}`);
|
||||
if (type(a.members) == 'array') {
|
||||
let want = {};
|
||||
for (let pid in a.members)
|
||||
if (m.people[pid]?.server == server)
|
||||
want[pid] = true;
|
||||
for (let pid, p in m.people)
|
||||
if (want[pid])
|
||||
c.set(core.CONFIG, pid, 'circle', id);
|
||||
else if (p.circle == id)
|
||||
c.delete(core.CONFIG, pid, 'circle');
|
||||
}
|
||||
return { id, edit: !!ci, server: m.servers[server].name };
|
||||
});
|
||||
apply.sync();
|
||||
admin_log('awg', res.edit ? 'changed' : 'added', 'circle', name, res.server);
|
||||
return { id: res.id, circles: values(core.load().circles) };
|
||||
}
|
||||
|
||||
function circle_delete(a) {
|
||||
let res = store.transact((c, m) => {
|
||||
let ci = m.circles[a.id];
|
||||
if (!ci)
|
||||
die('Unknown circle.');
|
||||
c.delete(core.CONFIG, a.id);
|
||||
for (let pid, p in m.people)
|
||||
if (p.circle == a.id)
|
||||
c.delete(core.CONFIG, pid, 'circle');
|
||||
return { name: ci.name, server: m.servers[ci.server]?.name };
|
||||
});
|
||||
apply.sync();
|
||||
admin_log('awg', 'removed', 'circle', res.name, res.server);
|
||||
return { circles: values(core.load().circles) };
|
||||
}
|
||||
|
||||
/* ---------- devices at home ---------- */
|
||||
|
||||
/** True while OpenWrt's mDNS daemon answers on ubus. */
|
||||
function mdns_running() {
|
||||
return index(split(sh_out('ubus list umdns 2>/dev/null') ?? '', '\n'), 'umdns') >= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Services announced on the home networks (Bonjour), from umdns:
|
||||
* [{ type: '_airplay._tcp', name, host, address, port, txt }].
|
||||
*/
|
||||
function mdns_services() {
|
||||
if (!mdns_running())
|
||||
return [];
|
||||
let r = {};
|
||||
try {
|
||||
r = json(sh_out(`ubus call umdns browse '{"address":true,"array":true}' 2>/dev/null`) || '{}') ?? {};
|
||||
}
|
||||
catch (e) {
|
||||
r = {};
|
||||
}
|
||||
let out = [];
|
||||
for (let t, insts in r)
|
||||
for (let name, i in insts) {
|
||||
let addr = type(i.ipv4) == 'array' ? i.ipv4[0] : i.ipv4;
|
||||
if (addr)
|
||||
push(out, { type: t, name, host: replace(i.host ?? '', /\.local\.?$/, ''), address: addr, port: i.port ?? 0, txt: i.txt ?? [] });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Devices at home for the Home services picker: DHCP leases and static hosts
|
||||
* in the server's home networks, with the services they announce (Bonjour,
|
||||
* when umdns runs).
|
||||
*/
|
||||
function home_hosts(a) {
|
||||
let m = core.load();
|
||||
let srv = m.servers[a.id] ?? values(m.servers)[0];
|
||||
if (!srv)
|
||||
die('No server yet.');
|
||||
let nets = [];
|
||||
for (let cidr in net.server_net(srv).nets) {
|
||||
let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/);
|
||||
if (x && ip2int(x[1]) != null)
|
||||
push(nets, [ ip2int(x[1]), 1 << (32 - +x[2]) ]);
|
||||
}
|
||||
let inside = (ip) => {
|
||||
let n = ip2int(ip);
|
||||
return n != null && length(filter(nets, (r) => n >= r[0] && n < r[0] + r[1])) > 0;
|
||||
};
|
||||
let hosts = {};
|
||||
for (let line in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) {
|
||||
let f = split(line, ' ');
|
||||
if (length(f) >= 4 && inside(f[2]))
|
||||
hosts[f[2]] = { address: f[2], name: f[3] == '*' ? '' : f[3], mac: f[1], services: [] };
|
||||
}
|
||||
let c = cursor();
|
||||
if (c.load('dhcp'))
|
||||
c.foreach('dhcp', 'host', (h) => {
|
||||
if (h.ip && inside(h.ip))
|
||||
hosts[h.ip] ??= { address: h.ip, name: h.name ?? '', mac: type(h.mac) == 'array' ? h.mac[0] : h.mac ?? '', services: [] };
|
||||
});
|
||||
for (let s in mdns_services())
|
||||
if (hosts[s.address])
|
||||
push(hosts[s.address].services, { type: s.type, name: s.name, port: s.port });
|
||||
else if (inside(s.address))
|
||||
hosts[s.address] = { address: s.address, name: s.host ?? '', mac: '', services: [ { type: s.type, name: s.name, port: s.port } ] };
|
||||
return { hosts: sort(values(hosts), (x, y) => ip2int(x.address) - ip2int(y.address)), mdns: mdns_running() };
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
service_set: { args: { id: '', name: '', address: '', ports: [] }, call: wrap(service_set) },
|
||||
service_delete: { args: { id: '' }, call: wrap(service_delete) },
|
||||
circle_set: { args: { id: '', server: '', name: '', color: 0, members: [] }, call: wrap(circle_set) },
|
||||
circle_delete: { args: { id: '' }, call: wrap(circle_delete) },
|
||||
home_hosts: { args: { id: '' }, call: wrap(home_hosts) },
|
||||
access_check: { args: { from: '', to: '' }, call: wrap((a) => access.check(core.load(), a.from, a.to)) },
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
// Dawnline rpcd methods: Diagnostics (Health, the service log), backups,
|
||||
// export / import, and removing Dawnline.
|
||||
|
||||
import { slog_clear, admin_log } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as watchdog from 'dawnline.watchdog';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as backup from 'dawnline.backup';
|
||||
import { wrap } from 'dawnline.rpc.common';
|
||||
|
||||
function health_view(extra) {
|
||||
return { ...(extra ?? {}), checks: health.health(), ...watchdog.view(core.load()) };
|
||||
}
|
||||
|
||||
function service_log_clear(a) {
|
||||
let removed = slog_clear(+a.older_days || 0);
|
||||
if (removed)
|
||||
admin_log('dawnline', 'cleared', null, 'the service log', `${removed} entr${removed == 1 ? 'y' : 'ies'}${+a.older_days ? ` older than ${a.older_days} days` : ''}`);
|
||||
return { removed };
|
||||
}
|
||||
|
||||
function backup_restore(a) {
|
||||
let r = backup.backup_restore(a.name);
|
||||
admin_log('dawnline', 'restored', 'backup', a.name);
|
||||
return r;
|
||||
}
|
||||
|
||||
function backup_upload(a) {
|
||||
let r = backup.backup_upload(a.data);
|
||||
admin_log('dawnline', 'restored', 'backup', 'from a file');
|
||||
return r;
|
||||
}
|
||||
|
||||
function export_all(a) {
|
||||
let r = backup.export_json();
|
||||
admin_log('dawnline', 'exported', null, 'all settings', 'the file holds private keys');
|
||||
return r;
|
||||
}
|
||||
|
||||
function import_all(a) {
|
||||
let r = backup.import_json(a.data);
|
||||
admin_log('dawnline', 'imported', null, 'settings from a file');
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Remove Dawnline's state from the router (the package is removed by the UI afterwards). */
|
||||
function uninstall(a) {
|
||||
if (a.confirm != 'remove')
|
||||
die('Type "remove" to confirm.');
|
||||
// Not in the middle of an update (opkg/apk may be installing Dawnline itself).
|
||||
if (upd.busy())
|
||||
die('An update is running: wait for it to finish, then remove Dawnline.');
|
||||
backup.backup_create('pre-remove');
|
||||
// Stop first: the agent would put back what teardown removes, and could start an automatic update.
|
||||
system('/etc/init.d/dawnline stop >/dev/null 2>&1; /etc/init.d/dawnline disable >/dev/null 2>&1');
|
||||
apply.teardown();
|
||||
store.transact((c, m) => {
|
||||
let rm = [];
|
||||
c.foreach(core.CONFIG, null, (s) => {
|
||||
if (s['.type'] != 'settings')
|
||||
push(rm, s['.name']);
|
||||
});
|
||||
for (let n in rm)
|
||||
c.delete(core.CONFIG, n);
|
||||
c.set(core.CONFIG, 'settings', 'settings');
|
||||
c.set(core.CONFIG, 'settings', 'portal_enabled', '0');
|
||||
});
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
apply: { call: wrap((a) => apply.apply()) },
|
||||
health: { call: wrap((a) => health_view()) },
|
||||
health_fix: { args: { id: '' }, call: wrap((a) => health_view({ result: health.fix(a.id) })) },
|
||||
service_log: { call: wrap((a) => watchdog.view(core.load())) },
|
||||
service_log_clear: { args: { older_days: '' }, call: wrap(service_log_clear) },
|
||||
backup_list: { call: wrap((a) => ({ backups: backup.backup_list() })) },
|
||||
backup_create: { call: wrap((a) => ({ name: backup.backup_create(null) })) },
|
||||
backup_restore: { args: { name: '' }, call: wrap(backup_restore) },
|
||||
backup_delete: { args: { name: '' }, call: wrap((a) => ({ ok: backup.backup_delete(a.name) })) },
|
||||
backup_read: { args: { name: '' }, call: wrap((a) => ({ data: backup.backup_read(a.name) })) },
|
||||
backup_upload: { args: { data: '' }, call: wrap(backup_upload) },
|
||||
'export': { call: wrap(export_all) },
|
||||
'import': { args: { data: {} }, call: wrap(import_all) },
|
||||
uninstall: { args: { confirm: '' }, call: wrap(uninstall) },
|
||||
};
|
||||
@@ -0,0 +1,164 @@
|
||||
// Dawnline rpcd methods: people (adding, editing, pausing, their personal
|
||||
// links and traffic) and their devices.
|
||||
|
||||
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 awg from 'dawnline.awg';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as devices from 'dawnline.devices';
|
||||
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
|
||||
|
||||
const PERSON_FIELDS = [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period',
|
||||
'bonus_gb', 'hours', 'note', 'dns_mode' ];
|
||||
|
||||
/* ---------- people ---------- */
|
||||
|
||||
function person_create(a) {
|
||||
let id = store.transact((c, m) => core.create_person(c, m, {
|
||||
name: str(a.name), slug: str(a.slug) || null, server: str(a.server) || null, access: a.access,
|
||||
device_limit: str(a.device_limit), expires: str(a.expires), quota_gb: str(a.quota_gb), quota_period: a.quota_period,
|
||||
}));
|
||||
let m = core.load();
|
||||
live.add_event({ type: 'person_added', person: id, detail: m.people[id].name, by: 'admin' });
|
||||
return { id, link: core.portal_url(m, m.people[id]) };
|
||||
}
|
||||
|
||||
/** Immediate edits from the person's page; returns the person as the page shows them. */
|
||||
function person_update(a) {
|
||||
let fields = {};
|
||||
for (let k in PERSON_FIELDS)
|
||||
if (a[k] != null)
|
||||
fields[k] = a[k];
|
||||
if (a.paused != null)
|
||||
fields.paused = a.paused;
|
||||
if (type(a.services) == 'array')
|
||||
fields.services = a.services;
|
||||
if (a.circle != null)
|
||||
fields.circle = a.circle;
|
||||
if (type(a.home_nets) == 'array')
|
||||
fields.home_nets = a.home_nets;
|
||||
let before = store.transact((c, m) => {
|
||||
let p = m.people[a.id];
|
||||
core.update_person(c, m, a.id, fields);
|
||||
return p;
|
||||
});
|
||||
let changes = join(', ', filter(keys(fields), (k) => k != 'note'));
|
||||
if (changes)
|
||||
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
|
||||
// Access changes affect the nft sets and client AllowedIPs.
|
||||
apply.sync();
|
||||
let m = core.load();
|
||||
let u = core.load_usage();
|
||||
return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access };
|
||||
}
|
||||
|
||||
function person_pause(a) {
|
||||
store.transact((c, m) => {
|
||||
if (!m.people[a.id])
|
||||
die('Unknown person.');
|
||||
if (a.paused)
|
||||
c.set(core.CONFIG, a.id, 'paused', '1');
|
||||
else
|
||||
c.delete(core.CONFIG, a.id, 'paused');
|
||||
});
|
||||
live.add_event({ type: a.paused ? 'paused' : 'resumed', person: a.id, by: 'admin' });
|
||||
return apply.sync();
|
||||
}
|
||||
|
||||
/** A new personal link: the old one stops working at once (every portal request carries the code). */
|
||||
function person_regen(a) {
|
||||
store.transact((c, m) => {
|
||||
if (!m.people[a.id])
|
||||
die('Unknown person.');
|
||||
c.set(core.CONFIG, a.id, 'code', core.new_code());
|
||||
});
|
||||
live.add_event({ type: 'link_changed', person: a.id, by: 'admin' });
|
||||
let m = core.load();
|
||||
return { link: core.portal_url(m, m.people[a.id]) };
|
||||
}
|
||||
|
||||
/** The personal code and links (Copy link, QR, invite): admins only, unlike status. */
|
||||
function person_links(a) {
|
||||
let m = core.load();
|
||||
let p = m.people[a.id];
|
||||
if (!p)
|
||||
die('Unknown person.');
|
||||
return { code: p.code, link: core.portal_url(m, p), links: core.portal_urls(m, p) };
|
||||
}
|
||||
|
||||
function person_delete(a) {
|
||||
let name = store.transact((c, m) => {
|
||||
let name = m.people[a.id]?.name;
|
||||
core.delete_person(c, m, a.id);
|
||||
return name;
|
||||
});
|
||||
live.add_event({ type: 'person_removed', person: a.id, detail: name, pname: name, by: 'admin' });
|
||||
return apply.sync();
|
||||
}
|
||||
|
||||
function person_usage(a) {
|
||||
let usage = core.load_usage();
|
||||
let m = core.load();
|
||||
let p = m.people[a.id];
|
||||
if (!p)
|
||||
die('Unknown person.');
|
||||
let days = clamp_days(a.days);
|
||||
let devs = {};
|
||||
for (let d in p.devices)
|
||||
devs[d] = live.series([ usage.devices?.[d] ], days);
|
||||
return { person: live.series([ usage.people?.[a.id] ], days), devices: devs };
|
||||
}
|
||||
|
||||
function pause_all(a) {
|
||||
store.transact((c, m) => {
|
||||
c.set(core.CONFIG, 'settings', 'settings');
|
||||
c.set(core.CONFIG, 'settings', 'paused_all', a.paused ? '1' : '0');
|
||||
});
|
||||
live.add_event({ type: a.paused ? 'paused_all' : 'resumed_all', by: 'admin' });
|
||||
return apply.sync();
|
||||
}
|
||||
|
||||
/* ---------- devices ---------- */
|
||||
|
||||
function device_create(a) {
|
||||
devices.need_awg();
|
||||
return devices.add(a.person, a.name, a.kind, { by: 'admin' });
|
||||
}
|
||||
|
||||
function device_config(a) {
|
||||
let m = core.load();
|
||||
let d = m.devices[a.id];
|
||||
if (!d)
|
||||
die('Unknown device.');
|
||||
awg.mark_issued(m, d.id);
|
||||
return awg.client_config(m, d);
|
||||
}
|
||||
|
||||
function device_update(a) {
|
||||
return devices.update(a.id, { name: a.name, disabled: a.disabled }, { by: 'admin' });
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
person_create: {
|
||||
args: { name: '', slug: '', server: '', access: '', device_limit: '', expires: '', quota_gb: '', quota_period: '' },
|
||||
call: wrap(person_create),
|
||||
},
|
||||
person_update: {
|
||||
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
|
||||
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [] },
|
||||
call: wrap(person_update),
|
||||
},
|
||||
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
|
||||
person_regen: { args: { id: '' }, call: wrap(person_regen) },
|
||||
person_links: { args: { id: '' }, call: wrap(person_links) },
|
||||
person_delete: { args: { id: '' }, call: wrap(person_delete) },
|
||||
person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) },
|
||||
pause_all: { args: { paused: false }, call: wrap(pause_all) },
|
||||
device_create: { args: { person: '', name: '', kind: '' }, call: wrap(device_create) },
|
||||
device_config: { args: { id: '' }, call: wrap(device_config) },
|
||||
device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) },
|
||||
device_delete: { args: { id: '' }, call: wrap((a) => devices.remove(a.id, { by: 'admin' })) },
|
||||
device_rotate: { args: { id: '' }, call: wrap((a) => devices.rotate(a.id, { by: 'admin' })) },
|
||||
};
|
||||
@@ -0,0 +1,531 @@
|
||||
// Dawnline rpcd methods: setting up a server, its General / Network /
|
||||
// Interfaces settings, its disguise, and removing it.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, rand_int, uniq, admin_log } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as schema from 'dawnline.schema';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as backup from 'dawnline.backup';
|
||||
import * as devices from 'dawnline.devices';
|
||||
import { wrap, str, check_method, check_portal } from 'dawnline.rpc.common';
|
||||
|
||||
/** Server ids that would shadow a portal path. */
|
||||
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
|
||||
|
||||
const MESH_WORDS = { off: 'devices kept apart', all: 'devices reach each other', circles: 'devices reach each other in circles' };
|
||||
|
||||
/* ---------- free names, ports and subnets ---------- */
|
||||
|
||||
function free_port(m) {
|
||||
let used = {};
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
nc.foreach('network', 'interface', (s) => {
|
||||
if (s.listen_port)
|
||||
used[+s.listen_port] = true;
|
||||
});
|
||||
for (let id, srv in m.servers)
|
||||
used[srv.port] = true;
|
||||
for (let i = 0; i < 50; i++) {
|
||||
let p = rand_int(40000, 60000);
|
||||
if (!used[p])
|
||||
return p;
|
||||
}
|
||||
return 51830;
|
||||
}
|
||||
|
||||
function free_subnet(taken) {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
let cand = parse_cidr(sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)));
|
||||
let bad = false;
|
||||
for (let t in taken) {
|
||||
let tc = parse_cidr(t);
|
||||
if (tc && cidr_overlaps(cand, tc)) {
|
||||
bad = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!bad)
|
||||
return cidr_str(cand);
|
||||
}
|
||||
return '10.77.0.0/24';
|
||||
}
|
||||
|
||||
function free_portal_port(cur) {
|
||||
for (let p in uniq([ cur || 8443, 8443, 9443, 10443, 7443, 4443 ]))
|
||||
if (!length(health.tcp_port_owners(p)) && !length(health.tcp_port_owners(p + 1)))
|
||||
return p;
|
||||
return 9443;
|
||||
}
|
||||
|
||||
/** A network section name nothing uses: not the router's, not Dawnline's own links, not another server's. */
|
||||
function ifname_free(m, nc, n) {
|
||||
if (nc.get('network', n) != null || index(values(net.INTERNAL), n) >= 0)
|
||||
return false;
|
||||
for (let id, s in m.servers)
|
||||
if (s.ifname == n)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function free_ifname(m) {
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
for (let i = 0; i < 10; i++)
|
||||
if (ifname_free(m, nc, `dawn${i}`))
|
||||
return `dawn${i}`;
|
||||
return 'dawnx';
|
||||
}
|
||||
|
||||
function id_free(m, id) {
|
||||
return !store.id_taken(m, id) && index(PORTAL_PATHS, id) < 0;
|
||||
}
|
||||
|
||||
/** A free server id: home, then server2, server3, … (never an id anything else has). */
|
||||
function free_server_id(m) {
|
||||
if (id_free(m, 'home'))
|
||||
return 'home';
|
||||
for (let n = 2; ; n++)
|
||||
if (id_free(m, `server${n}`))
|
||||
return `server${n}`;
|
||||
}
|
||||
|
||||
/** Subnets a new server must not overlap: the router's networks and the other servers. */
|
||||
function taken_subnets(m) {
|
||||
let taken = health.used_subnets(null);
|
||||
for (let id, s in m.servers)
|
||||
push(taken, s.subnet);
|
||||
return taken;
|
||||
}
|
||||
|
||||
/* ---------- setup ---------- */
|
||||
|
||||
function setup_defaults(a) {
|
||||
let m = core.load();
|
||||
let taken = taken_subnets(m);
|
||||
let zones = [];
|
||||
let fc = cursor();
|
||||
fc.load('firewall');
|
||||
fc.foreach('firewall', 'zone', (z) => push(zones, z.name));
|
||||
let host = m.settings.portal_host;
|
||||
if (!host) {
|
||||
// Prefer a DDNS name, then an ACME certificate's, then the WAN address.
|
||||
let dc = cursor();
|
||||
if (dc.load('ddns'))
|
||||
dc.foreach('ddns', 'service', (s) => {
|
||||
if (!host && s.lookup_host && s.enabled == '1')
|
||||
host = s.lookup_host;
|
||||
});
|
||||
if (!host)
|
||||
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
|
||||
if (!host)
|
||||
host = live.iface_status('wan')?.['ipv4-address']?.[0]?.address ?? '';
|
||||
}
|
||||
return {
|
||||
id: free_server_id(m),
|
||||
name: length(m.servers) ? `Server ${length(m.servers) + 1}` : 'Home',
|
||||
ifname: free_ifname(m),
|
||||
port: free_port(m),
|
||||
subnet: free_subnet(taken),
|
||||
endpoint: host,
|
||||
mtu: 1380,
|
||||
zones,
|
||||
lan_zone: index(zones, 'lan') >= 0 ? 'lan' : zones[0],
|
||||
wan_zone: index(zones, 'wan') >= 0 ? 'wan' : zones[1],
|
||||
portal_port: free_portal_port(m.settings.portal_port),
|
||||
awg: awg.caps(),
|
||||
awg_state: awg.state(),
|
||||
taken,
|
||||
};
|
||||
}
|
||||
|
||||
/** AmneziaWG can run a server: installed, and its kernel module loads. */
|
||||
function need_awg_loaded() {
|
||||
devices.need_awg();
|
||||
if (awg.state().loaded)
|
||||
return;
|
||||
system('modprobe amneziawg >/dev/null 2>&1');
|
||||
if (!awg.state().loaded)
|
||||
die("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components.");
|
||||
}
|
||||
|
||||
/** An MTU as typed: '' (the default) or 1280-1500. */
|
||||
function check_mtu(v) {
|
||||
let s = str(v);
|
||||
if (s != '' && (!match(s, /^[0-9]{1,4}$/) || +s < 1280 || +s > 1500))
|
||||
die('MTU must be 1280-1500.');
|
||||
return s;
|
||||
}
|
||||
|
||||
function server_create(a) {
|
||||
need_awg_loaded();
|
||||
let snap = net.snapshot(true);
|
||||
let router_subnets = health.used_subnets(null);
|
||||
let id = store.transact((c, m) => {
|
||||
let id = str(a.id) || 'home';
|
||||
// A UCI section name: a dash would make uci drop it silently.
|
||||
if (!match(id, /^[a-z][a-z0-9_]{0,23}$/))
|
||||
die('Server ID may use lowercase letters, digits and underscores.');
|
||||
if (!id_free(m, id))
|
||||
die(`"${id}" is already taken.`);
|
||||
let nc = cursor();
|
||||
nc.load('network');
|
||||
let ifname = str(a.ifname) || free_ifname(m);
|
||||
if (!ifname_free(m, nc, ifname))
|
||||
die(`Network interface ${ifname} already exists.`);
|
||||
let port = free_port(m);
|
||||
if (a.port != null && str(a.port) != '' && str(a.port) != '0') {
|
||||
if (!schema.valid_port(a.port))
|
||||
die('UDP port must be 1-65535.');
|
||||
port = +str(a.port);
|
||||
}
|
||||
for (let sid, o in m.servers)
|
||||
if (o.port == port)
|
||||
die(`UDP ${port} is used by ${o.name}.`);
|
||||
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu) || '1380';
|
||||
let preset = str(a.preset) || 'standard';
|
||||
let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) };
|
||||
let pc = parse_cidr(srv.subnet);
|
||||
if (pc)
|
||||
srv.subnet = cidr_str(pc);
|
||||
let taken = [ ...router_subnets ];
|
||||
for (let sid, o in m.servers)
|
||||
push(taken, o.subnet);
|
||||
let errs = core.server_errors(m, srv, taken);
|
||||
push(errs, ...awg.obf_errors(srv.obf));
|
||||
if (length(errs))
|
||||
die(join(' ', errs));
|
||||
|
||||
let set = (k, v) => c.set(core.CONFIG, id, k, v);
|
||||
c.set(core.CONFIG, 'settings', 'settings');
|
||||
c.set(core.CONFIG, id, 'server');
|
||||
set('name', str(a.name) || 'Home');
|
||||
set('ifname', ifname);
|
||||
set('port', `${port}`);
|
||||
set('subnet', srv.subnet);
|
||||
if (srv.endpoint)
|
||||
set('endpoint', srv.endpoint);
|
||||
set('mtu', mtu);
|
||||
set('keepalive', '25');
|
||||
let kp = awg.server_keys();
|
||||
set('private_key', kp.private_key);
|
||||
set('public_key', kp.public_key);
|
||||
set('preset', preset);
|
||||
for (let ok, ov in srv.obf)
|
||||
set(ok, ov);
|
||||
set('lan_zone', str(a.lan_zone) || 'lan');
|
||||
set('wan_zone', str(a.wan_zone) || 'wan');
|
||||
set('auto_wan', '1');
|
||||
set('auto_lan', '1');
|
||||
if (snap.wan)
|
||||
set('detected_wan', snap.wan);
|
||||
if (snap.lan)
|
||||
set('detected_lan', snap.lan);
|
||||
set('lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
|
||||
set('enabled', '1');
|
||||
if (a.portal_enabled != null) {
|
||||
let on = a.portal_enabled === true || a.portal_enabled === 1 || a.portal_enabled === '1';
|
||||
c.set(core.CONFIG, 'settings', 'portal_enabled', on ? '1' : '0');
|
||||
if (a.portal_port != null && str(a.portal_port) != '' && str(a.portal_port) != '0') {
|
||||
if (!schema.valid_port(a.portal_port))
|
||||
die('Portal port must be 1-65535.');
|
||||
c.set(core.CONFIG, 'settings', 'portal_port', `${+str(a.portal_port)}`);
|
||||
}
|
||||
}
|
||||
if (srv.endpoint && !c.get(core.CONFIG, 'settings', 'portal_host') && valid_host(srv.endpoint))
|
||||
c.set(core.CONFIG, 'settings', 'portal_host', srv.endpoint);
|
||||
// The portal as it will be, whatever this call changed.
|
||||
check_portal(core.load(c), m);
|
||||
return id;
|
||||
});
|
||||
let r = apply.apply();
|
||||
system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable');
|
||||
let made = core.load().servers[id];
|
||||
admin_log('dawnline', 'created', 'server', made?.name ?? id, made ? `UDP ${made.port}` : null);
|
||||
sh_bg('/etc/init.d/dawnline restart');
|
||||
return { id, applied: r };
|
||||
}
|
||||
|
||||
/* ---------- interfaces ---------- */
|
||||
|
||||
/** Interfaces card on the Server page: what exists, what is detected, what the server uses. */
|
||||
function interfaces_view(m, srv, snap) {
|
||||
let sn = net.server_net(srv, snap);
|
||||
let home = {};
|
||||
for (let h in sn.home)
|
||||
home[h.dev] = h;
|
||||
let devs = [];
|
||||
for (let dev, d in snap.devices)
|
||||
push(devs, {
|
||||
...d,
|
||||
own: dev == srv.ifname,
|
||||
home: !!home[dev],
|
||||
auto: !!home[dev]?.auto,
|
||||
});
|
||||
// Saved names that no longer exist still show, so they can be removed.
|
||||
for (let h in sn.home)
|
||||
if (h.missing)
|
||||
push(devs, { name: h.dev, category: 'other', kind: 'other', missing: true, nets: [], addrs: [], members: [], home: true, auto: h.auto });
|
||||
let lan_only = 0;
|
||||
for (let id, p in m.people)
|
||||
if (p.server == srv.id && p.access == 'lan')
|
||||
lan_only++;
|
||||
return {
|
||||
server: srv.id,
|
||||
ifname: srv.ifname,
|
||||
detected: { wan: snap.wan, lan: snap.lan },
|
||||
saved: { wan: srv.detected_wan, lan: srv.detected_lan },
|
||||
config: { auto_wan: srv.auto_wan, wan_device: srv.wan_device, auto_lan: srv.auto_lan, lan_devices: srv.lan_devices, lan_like: srv.lan_like,
|
||||
device_mesh: srv.device_mesh, mesh: srv.mesh },
|
||||
like_home: loop.status(),
|
||||
needs: health.needs().home,
|
||||
effective: sn,
|
||||
zones: snap.zones,
|
||||
devices: devs,
|
||||
lan_only,
|
||||
};
|
||||
}
|
||||
|
||||
function interfaces_get(a) {
|
||||
let m = core.load();
|
||||
let srv = m.servers[a.id] ?? values(m.servers)[0];
|
||||
if (!srv)
|
||||
die('No server yet.');
|
||||
return interfaces_view(m, srv, net.snapshot(true));
|
||||
}
|
||||
|
||||
function server_interfaces(a) {
|
||||
let snap = net.snapshot(true);
|
||||
let auto_wan = a.auto_wan != false && a.auto_wan != '0';
|
||||
let auto_lan = a.auto_lan != false && a.auto_lan != '0';
|
||||
let wan_dev = str(a.wan_device);
|
||||
let res = store.transact((c, m) => {
|
||||
let srv = m.servers[a.id];
|
||||
if (!srv)
|
||||
die('Unknown server.');
|
||||
if (!auto_wan) {
|
||||
if (!snap.devices[wan_dev])
|
||||
die('Choose the interface that leads to the internet.');
|
||||
if (!snap.devices[wan_dev].zone)
|
||||
die(`${wan_dev} is not in a firewall zone, so the server port cannot be opened on it.`);
|
||||
}
|
||||
let lans = [];
|
||||
for (let d in (type(a.lan_devices) == 'array' ? a.lan_devices : [])) {
|
||||
d = str(d);
|
||||
// Unknown names are kept only if they were saved before (interface down right now).
|
||||
if (d == '' || d == srv.ifname || (!snap.devices[d] && index(srv.lan_devices, d) < 0))
|
||||
continue;
|
||||
if (snap.devices[d]?.master)
|
||||
die(`${d} is part of ${snap.devices[d].master}; choose ${snap.devices[d].master} instead.`);
|
||||
if (d == (auto_wan ? snap.wan : wan_dev))
|
||||
die(`${d} is the WAN.`);
|
||||
push(lans, d);
|
||||
}
|
||||
lans = uniq(lans);
|
||||
let id = srv.id;
|
||||
if (a.lan_like != null)
|
||||
c.set(core.CONFIG, id, 'lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
|
||||
let mesh = index(core.MESH, a.mesh) >= 0 ? a.mesh
|
||||
: a.device_mesh == null ? srv.mesh : (a.device_mesh === false || a.device_mesh === '0' ? 'off' : 'all');
|
||||
c.set(core.CONFIG, id, 'mesh', mesh);
|
||||
c.delete(core.CONFIG, id, 'device_mesh');
|
||||
c.set(core.CONFIG, id, 'auto_wan', auto_wan ? '1' : '0');
|
||||
c.set(core.CONFIG, id, 'auto_lan', auto_lan ? '1' : '0');
|
||||
if (auto_wan || wan_dev == '')
|
||||
c.delete(core.CONFIG, id, 'wan_device');
|
||||
else
|
||||
c.set(core.CONFIG, id, 'wan_device', wan_dev);
|
||||
if (length(lans))
|
||||
c.set(core.CONFIG, id, 'lan_device', lans);
|
||||
else
|
||||
c.delete(core.CONFIG, id, 'lan_device');
|
||||
// Remember what was detected, as the fallback while an interface is down.
|
||||
if (snap.wan)
|
||||
c.set(core.CONFIG, id, 'detected_wan', snap.wan);
|
||||
if (snap.lan)
|
||||
c.set(core.CONFIG, id, 'detected_lan', snap.lan);
|
||||
// Keep the legacy zone options in step (older code paths, health checks).
|
||||
let now = core.load(c).servers[id];
|
||||
let sn = net.server_net(now, snap);
|
||||
if (sn.wan.zone)
|
||||
c.set(core.CONFIG, id, 'wan_zone', sn.wan.zone);
|
||||
if (length(sn.zones))
|
||||
c.set(core.CONFIG, id, 'lan_zone', sn.zones[0]);
|
||||
return { was: srv, now: core.load(c).servers[id], mesh };
|
||||
});
|
||||
let srv = res.was;
|
||||
// What the admin changed here: the networks, and/or whether devices reach each other.
|
||||
let sig = (x) => {
|
||||
let sn = net.server_net(x, snap);
|
||||
return `${join(',', sn.nets)}|${sn.wan.dev}|${x.lan_like}`;
|
||||
};
|
||||
let what = [];
|
||||
if (sig(res.now) != sig(srv))
|
||||
push(what, 'home network and internet path');
|
||||
if (res.mesh != srv.mesh)
|
||||
push(what, MESH_WORDS[res.mesh]);
|
||||
if (length(what))
|
||||
admin_log('awg', 'changed', 'server', srv.name, join(', ', what));
|
||||
let before = join(',', net.server_net(srv, snap).nets);
|
||||
apply.apply();
|
||||
let m = core.load();
|
||||
let v = interfaces_view(m, m.servers[srv.id], net.snapshot(true));
|
||||
v.nets_changed = before != join(',', v.effective.nets);
|
||||
return v;
|
||||
}
|
||||
|
||||
/* ---------- settings ---------- */
|
||||
|
||||
/** A list of DNS servers as typed (array or "a, b"): each an IPv4 or IPv6 address. */
|
||||
function dns_list(v) {
|
||||
let list = filter(map(type(v) == 'array' ? v : split(str(v), /[ ,]+/), str), (x) => x != '');
|
||||
for (let d in list)
|
||||
if (!schema.ip(d))
|
||||
die(`${d} is not an IP address.`);
|
||||
return list;
|
||||
}
|
||||
|
||||
/** Server settings from the General and Network tabs; applied at once. */
|
||||
function server_update(a) {
|
||||
let v = a.values ?? {};
|
||||
if (v.device_mesh != null && v.mesh == null)
|
||||
v.mesh = v.device_mesh === true || v.device_mesh == '1' ? 'all' : 'off';
|
||||
let srv = store.transact((c, m) => {
|
||||
let srv = m.servers[a.id];
|
||||
if (!srv)
|
||||
die('Unknown server.');
|
||||
let set = (k, val) => (val == null || val == '') ? c.delete(core.CONFIG, srv.id, k) : c.set(core.CONFIG, srv.id, k, val);
|
||||
if (v.name != null) {
|
||||
if (str(v.name) == '')
|
||||
die('Name cannot be empty.');
|
||||
set('name', str(v.name));
|
||||
}
|
||||
if (v.endpoint != null) {
|
||||
if (str(v.endpoint) == '' || !valid_host(str(v.endpoint)))
|
||||
die('Public address must be a hostname or IP address.');
|
||||
set('endpoint', str(v.endpoint));
|
||||
}
|
||||
if (v.port != null) {
|
||||
if (!schema.valid_port(v.port))
|
||||
die('UDP port must be 1-65535.');
|
||||
let n = +str(v.port);
|
||||
for (let id, o in m.servers)
|
||||
if (id != srv.id && o.port == n)
|
||||
die(`UDP ${n} is used by ${o.name}.`);
|
||||
set('port', `${n}`);
|
||||
}
|
||||
if (v.enabled != null)
|
||||
set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0');
|
||||
if (v.mesh != null) {
|
||||
if (index(core.MESH, v.mesh) < 0)
|
||||
die('Unknown choice for devices reaching each other.');
|
||||
set('mesh', v.mesh);
|
||||
set('device_mesh', null);
|
||||
}
|
||||
if (v.mtu != null)
|
||||
set('mtu', check_mtu(v.mtu));
|
||||
if (v.keepalive != null) {
|
||||
if (str(v.keepalive) != '' && (!match(str(v.keepalive), /^[0-9]{1,3}$/) || +v.keepalive > 600))
|
||||
die('Keep-alive must be 0-600 seconds.');
|
||||
set('keepalive', str(v.keepalive));
|
||||
}
|
||||
if (v.dns != null) {
|
||||
let list = dns_list(v.dns);
|
||||
if (length(list))
|
||||
c.set(core.CONFIG, srv.id, 'dns', list);
|
||||
else
|
||||
c.delete(core.CONFIG, srv.id, 'dns');
|
||||
}
|
||||
return srv;
|
||||
});
|
||||
// For the log: what changed, in words. Turning on or off is its own line.
|
||||
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS' };
|
||||
let what = [];
|
||||
for (let k, label in labels) {
|
||||
if (v[k] == null)
|
||||
continue;
|
||||
let was = k == 'dns' ? join(' ', srv.dns ?? []) : `${srv[k] ?? ''}`;
|
||||
let now = k == 'dns' ? join(' ', dns_list(v.dns)) : str(v[k]);
|
||||
if (trim(was) != trim(now))
|
||||
push(what, label);
|
||||
}
|
||||
let turned = v.enabled == null ? null : (v.enabled === true || v.enabled == '1');
|
||||
let name = v.name != null ? str(v.name) : srv.name;
|
||||
let r = apply.apply();
|
||||
if (turned != null && turned != srv.enabled)
|
||||
admin_log('dawnline', turned ? 'turned on' : 'turned off', 'server', name);
|
||||
if (length(what))
|
||||
admin_log('dawnline', 'changed', 'server', name, join(', ', what));
|
||||
if (v.mesh != null && v.mesh != srv.mesh)
|
||||
admin_log('dawnline', 'changed', 'server', name, MESH_WORDS[v.mesh]);
|
||||
return r;
|
||||
}
|
||||
|
||||
function server_obfuscation(a) {
|
||||
let preset = str(a.preset) || 'standard';
|
||||
let o = awg.obf_preset(check_method(preset));
|
||||
let srv = store.transact((c, m) => {
|
||||
let srv = m.servers[a.id];
|
||||
if (!srv)
|
||||
die('Unknown server.');
|
||||
for (let k in core.OBF_KEYS)
|
||||
c.delete(core.CONFIG, srv.id, k);
|
||||
for (let k, v in o)
|
||||
c.set(core.CONFIG, srv.id, k, v);
|
||||
c.set(core.CONFIG, srv.id, 'preset', preset);
|
||||
return srv;
|
||||
});
|
||||
let r = apply.apply();
|
||||
admin_log('awg', 'changed', 'server', srv.name, `disguise: ${preset}`);
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Remove a server with its people, their devices and its circles (a backup is made first). */
|
||||
function server_delete(a) {
|
||||
if (!core.load().servers[a.id])
|
||||
die('Unknown server.');
|
||||
backup.backup_create('pre-delete');
|
||||
let res = store.transact((c, m) => {
|
||||
let srv = m.servers[a.id];
|
||||
if (!srv)
|
||||
die('Unknown server.');
|
||||
let gone = 0;
|
||||
for (let pid, p in m.people)
|
||||
if (p.server == srv.id) {
|
||||
core.delete_person(c, m, pid);
|
||||
gone++;
|
||||
}
|
||||
for (let cid, ci in m.circles)
|
||||
if (ci.server == srv.id)
|
||||
c.delete(core.CONFIG, cid);
|
||||
c.delete(core.CONFIG, srv.id);
|
||||
return { name: srv.name, gone };
|
||||
});
|
||||
let r = apply.apply();
|
||||
admin_log('awg', 'removed', 'server', res.name, res.gone ? `with ${res.gone} ${res.gone == 1 ? 'person' : 'people'}` : null);
|
||||
return r;
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
setup_defaults: { call: wrap(setup_defaults) },
|
||||
server_create: {
|
||||
args: { id: '', name: '', ifname: '', port: 0, subnet: '', endpoint: '', mtu: 0, preset: '', lan_zone: '', wan_zone: '',
|
||||
lan_like: true, portal_enabled: false, portal_port: 0 },
|
||||
call: wrap(server_create),
|
||||
},
|
||||
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
|
||||
server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
|
||||
interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
|
||||
server_interfaces: {
|
||||
args: { id: '', auto_wan: false, wan_device: '', auto_lan: false, lan_devices: [], lan_like: false, device_mesh: true, mesh: '' },
|
||||
call: wrap(server_interfaces),
|
||||
},
|
||||
server_delete: { args: { id: '' }, call: wrap(server_delete) },
|
||||
};
|
||||
@@ -0,0 +1,150 @@
|
||||
// Dawnline rpcd methods: the Settings page (the portal, defaults, logs and
|
||||
// history, updates). What may be saved is dawnline.schema's.
|
||||
|
||||
import { stat } from 'fs';
|
||||
import { q, sh_out, admin_log, 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 geo from 'dawnline.geo';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as schema from 'dawnline.schema';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as pc from 'dawnline.portalcert';
|
||||
import { wrap, check_portal } from 'dawnline.rpc.common';
|
||||
|
||||
/** The portal's own checks from Health, shown next to its settings. */
|
||||
const PORTAL_CHECKS = [ 'portal', 'portal_dns', 'portal_reply', 'portal_http', 'cert' ];
|
||||
|
||||
function file_size(path) {
|
||||
return stat(path)?.size ?? 0;
|
||||
}
|
||||
|
||||
/** What the log and traffic history hold right now (Settings → Logs & history). */
|
||||
function logs_info(m) {
|
||||
let ev = live.load_events();
|
||||
let by = {};
|
||||
for (let cat in live.CATEGORIES)
|
||||
by[cat] = 0;
|
||||
for (let e in ev)
|
||||
by[live.category_of(e.type)]++;
|
||||
let usage = core.load_usage();
|
||||
let days = {};
|
||||
for (let grp in [ usage?.devices ?? {}, usage?.people ?? {} ])
|
||||
for (let id, rec in grp)
|
||||
for (let k in keys(rec.days ?? {}))
|
||||
days[k] = true;
|
||||
let dk = sort(keys(days));
|
||||
return {
|
||||
policy: live.policy(m.settings.retention),
|
||||
events: length(ev),
|
||||
oldest: length(ev) ? ev[0].ts : 0,
|
||||
by_category: by,
|
||||
log_ram: file_size(`${RUN_DIR}/events.json`),
|
||||
log_flash: file_size(`${DATA_DIR}/events.json`),
|
||||
usage_flash: file_size(`${DATA_DIR}/usage.json`),
|
||||
usage_since: length(dk) ? dk[0] : '',
|
||||
usage_days: length(dk),
|
||||
geo_flash: file_size(`${DATA_DIR}/geo.json`),
|
||||
};
|
||||
}
|
||||
|
||||
function settings_get(a) {
|
||||
let c = core.open_cursor();
|
||||
let raw = c.get_all(core.CONFIG, 'settings') ?? {};
|
||||
let m = core.load(c);
|
||||
let out = {};
|
||||
for (let k in keys(schema.SETTINGS))
|
||||
out[k] = raw[k] ?? '';
|
||||
out.log_category = live.policy(m.settings.retention).categories;
|
||||
let cert = m.settings.portal_enabled ? pc.portal_cert(m.settings) : null;
|
||||
return {
|
||||
settings: out,
|
||||
needs: health.needs(),
|
||||
effective: m.settings,
|
||||
services: values(m.services),
|
||||
cert: cert ? { path: cert.cert, self_signed: cert.self_signed,
|
||||
expires: sh_out(`openssl x509 -enddate -noout -in ${q(cert.cert)} 2>/dev/null | cut -d= -f2`) } : null,
|
||||
port_owners: m.settings.portal_enabled ? [] : health.tcp_port_owners(m.settings.portal_port),
|
||||
portal_public_port: core.portal_public_port(m),
|
||||
geo_cached: length(keys(geo.load().ips)),
|
||||
logs: logs_info(m),
|
||||
};
|
||||
}
|
||||
|
||||
/*
|
||||
* The slow part of the portal settings (DNS lookups and the Health checks),
|
||||
* fetched after the page shows.
|
||||
*/
|
||||
function portal_info(a) {
|
||||
let m = core.load();
|
||||
return {
|
||||
candidates: pc.portal_candidates(m),
|
||||
checks: filter(health.health(m), (x) => index(PORTAL_CHECKS, x.id) >= 0),
|
||||
};
|
||||
}
|
||||
|
||||
function same(a, b) {
|
||||
return (type(a) == 'array' ? join('\n', a) : a ?? '') == (type(b) == 'array' ? join('\n', b) : b ?? '');
|
||||
}
|
||||
|
||||
/** Save settings (`values`: key → value, '' back to the default); the portal is checked as it will be. */
|
||||
function settings_update(a) {
|
||||
let v = a.values ?? {};
|
||||
if (type(v) != 'object')
|
||||
die('Nothing to save.');
|
||||
let res = store.transact((c, m) => {
|
||||
let restart = false;
|
||||
c.set(core.CONFIG, 'settings', 'settings');
|
||||
for (let k, val in v) {
|
||||
if (k == 'log_category') {
|
||||
let lst = filter(type(val) == 'array' ? val : [], (x) => index(live.CATEGORIES, x) >= 0);
|
||||
c.set(core.CONFIG, 'settings', 'log_category', length(lst) ? lst : [ '' ]);
|
||||
// Superseded by the category list.
|
||||
c.delete(core.CONFIG, 'settings', 'log_connections');
|
||||
continue;
|
||||
}
|
||||
let nv = schema.validate(k, val);
|
||||
if (schema.SETTINGS[k].restart && !same(nv, c.get(core.CONFIG, 'settings', k)))
|
||||
restart = true;
|
||||
if (nv == null)
|
||||
c.delete(core.CONFIG, 'settings', k);
|
||||
else
|
||||
c.set(core.CONFIG, 'settings', k, nv);
|
||||
}
|
||||
check_portal(core.load(c), m);
|
||||
return { restart, was: m.settings };
|
||||
});
|
||||
if (res.restart)
|
||||
system('/etc/init.d/dawnline reload >/dev/null 2>&1');
|
||||
else
|
||||
apply.sync();
|
||||
// The changes worth a line: the portal and the watchdog (other settings are housekeeping).
|
||||
let now = core.load().settings, was = res.was;
|
||||
if (now.portal_enabled != was.portal_enabled)
|
||||
admin_log('portal', now.portal_enabled ? 'turned on' : 'turned off', null, 'the personal portal', now.portal_enabled ? `port ${now.portal_port}` : null);
|
||||
else if (now.portal_enabled) {
|
||||
let what = [];
|
||||
if (now.portal_port != was.portal_port)
|
||||
push(what, `port ${now.portal_port}`);
|
||||
if (now.portal_host != was.portal_host)
|
||||
push(what, `address ${now.portal_host}`);
|
||||
if (join(' ', now.portal_alt) != join(' ', was.portal_alt))
|
||||
push(what, 'other addresses');
|
||||
if (now.portal_cert != was.portal_cert || now.portal_key != was.portal_key)
|
||||
push(what, 'certificate');
|
||||
if (now.portal_redirect != was.portal_redirect)
|
||||
push(what, 'redirect');
|
||||
if (length(what))
|
||||
admin_log('portal', 'changed', null, 'the personal portal', join(', ', what));
|
||||
}
|
||||
if (now.watchdog != was.watchdog)
|
||||
admin_log('dawnline', now.watchdog ? 'turned on' : 'turned off', null, 'the watchdog', now.watchdog ? null : 'problems are only logged, nothing is repaired');
|
||||
return settings_get({});
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
settings_get: { call: wrap(settings_get) },
|
||||
portal_info: { call: wrap(portal_info) },
|
||||
settings_update: { args: { values: {} }, call: wrap(settings_update) },
|
||||
};
|
||||
@@ -0,0 +1,230 @@
|
||||
// Dawnline rpcd methods: the Overview status (servers, people, totals, map,
|
||||
// recent activity), the activity log and traffic history.
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { read_json, write_json, ensure_dir, lock, unlock, admin_log, VERSION, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as view from 'dawnline.view';
|
||||
import * as geo from 'dawnline.geo';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import { wrap, clamp_days } from 'dawnline.rpc.common';
|
||||
|
||||
/** Router location plus one point per (device, recent client address). */
|
||||
function geo_view(m, usage, dmp) {
|
||||
if (!m.settings.geo_enabled)
|
||||
return { enabled: false, home: null, points: [] };
|
||||
let cache = geo.load();
|
||||
let points = [];
|
||||
let now = time();
|
||||
for (let id, d in m.devices) {
|
||||
let rec = usage.devices?.[id];
|
||||
let peer = dmp.peers[d.public_key];
|
||||
let cur = live.endpoint_ip(peer?.endpoint);
|
||||
let online = !!(peer && peer.handshake > 0 && now - peer.handshake < live.ONLINE_WINDOW);
|
||||
for (let ip, ts in rec?.ips ?? {}) {
|
||||
// Local (LAN / CGNAT) client addresses are not shown on the map.
|
||||
let pl = geo.is_public(ip) ? geo.place(cache, ip) : null;
|
||||
if (!pl)
|
||||
continue;
|
||||
push(points, {
|
||||
person: d.person, device: id, ip, ts,
|
||||
online: online && ip == cur,
|
||||
lat: pl.lat, lon: pl.lon, city: pl.city, country: pl.country, cc: pl.cc,
|
||||
asn: pl.asn ?? 0, org: pl.org ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
let h = cache.home;
|
||||
return {
|
||||
enabled: true,
|
||||
provider: m.settings.geo_provider,
|
||||
cached: length(keys(cache.ips)),
|
||||
home: (h && h.lat != null) ? { lat: h.lat, lon: h.lon, city: h.city, country: h.country, cc: h.cc, asn: h.asn ?? 0, org: h.org ?? '' } : null,
|
||||
points,
|
||||
};
|
||||
}
|
||||
|
||||
/** Older connections from home get the DHCP name their address has now. */
|
||||
function with_hosts(ev) {
|
||||
let names = null;
|
||||
for (let e in ev)
|
||||
if ((e.type == 'connect' || e.type == 'roam') && !e.hosts) {
|
||||
let h = net.event_hosts(e, names ??= net.lan_names());
|
||||
if (h)
|
||||
e.hosts = h;
|
||||
}
|
||||
return ev;
|
||||
}
|
||||
|
||||
function server_view(m, srv, usage, dmp, rates, days) {
|
||||
let online = 0, peers = 0, now = time();
|
||||
let links = map(core.tunnels(srv), (t) => t.ifname);
|
||||
for (let k, p in dmp.peers)
|
||||
if (index(links, p.ifname) >= 0) {
|
||||
peers++;
|
||||
if (p.handshake > 0 && now - p.handshake < live.ONLINE_WINDOW)
|
||||
online++;
|
||||
}
|
||||
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
|
||||
return {
|
||||
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet,
|
||||
endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled,
|
||||
lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
|
||||
address: core.server_address(srv), up: !!st.up, uptime: st.uptime ?? 0,
|
||||
// Why the tunnel cannot run (its interface name belongs to another network section), or null.
|
||||
blocked: srv.blocked ?? null,
|
||||
// Home networks (interfaces) for the per-person picker.
|
||||
home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })),
|
||||
peers, online, obf: srv.obf,
|
||||
// Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices).
|
||||
rate: rates[srv.id] ?? [],
|
||||
// Daily traffic of the people on this server (its Overview chart).
|
||||
series: live.series(map(filter(keys(m.people), (pid) => m.people[pid].server == srv.id), (pid) => usage.people?.[pid]), days),
|
||||
};
|
||||
}
|
||||
|
||||
/*
|
||||
* Everything the pages show at once. Readable by read-only users: no personal
|
||||
* codes or links here (person_links has them).
|
||||
*/
|
||||
function status(a) {
|
||||
let m = core.load();
|
||||
let usage = core.load_usage();
|
||||
let dmp = live.dump(m);
|
||||
let states = view.states(m, usage);
|
||||
let days = clamp_days(a.days);
|
||||
|
||||
let servers = [];
|
||||
let rates = read_json(`${RUN_DIR}/rate.json`, {});
|
||||
let prates = read_json(`${RUN_DIR}/rate_people.json`, {});
|
||||
for (let id, srv in m.servers)
|
||||
push(servers, server_view(m, srv, usage, dmp, rates, days));
|
||||
|
||||
let people = [];
|
||||
for (let id, p in m.people) {
|
||||
let pv = view.person_view(m, p, usage, dmp, states, { admin: true });
|
||||
pv.rate = type(prates[p.id]?.[0]) == 'array' ? prates[p.id] : [];
|
||||
push(people, pv);
|
||||
}
|
||||
people = sort(people, (a, b) => (b.online - a.online) || (b.last_seen - a.last_seen) || (a.name < b.name ? -1 : 1));
|
||||
|
||||
let totals = { people: length(people), devices: 0, online: 0, active: 0 };
|
||||
for (let p in people) {
|
||||
totals.devices += length(p.devices);
|
||||
totals.online += p.online;
|
||||
if (p.state == 'active')
|
||||
totals.active++;
|
||||
}
|
||||
let recs = values(usage.people ?? {});
|
||||
let day = live.series(recs, 1)[0];
|
||||
totals.today = [ day.rx, day.tx ];
|
||||
let mon = [ 0, 0 ];
|
||||
for (let r in recs) {
|
||||
let v = live.month(r);
|
||||
mon[0] += v[0];
|
||||
mon[1] += v[1];
|
||||
}
|
||||
totals.month = mon;
|
||||
|
||||
let events = live.load_events();
|
||||
let s = m.settings;
|
||||
return {
|
||||
geo: geo_view(m, usage, dmp),
|
||||
version: VERSION,
|
||||
now: time(),
|
||||
hostname: trim(readfile('/proc/sys/kernel/hostname') ?? ''),
|
||||
settings: {
|
||||
portal_enabled: s.portal_enabled, portal_port: s.portal_port, portal_host: s.portal_host,
|
||||
portal_public_port: core.portal_public_port(m),
|
||||
paused_all: s.paused_all, default_device_limit: s.default_device_limit, domain: s.domain,
|
||||
hostnames: s.hostnames, geo_enabled: s.geo_enabled, home_dns_fallback: s.home_dns_fallback,
|
||||
},
|
||||
servers,
|
||||
people,
|
||||
services: values(m.services),
|
||||
circles: values(m.circles),
|
||||
totals,
|
||||
series: live.series(recs, days),
|
||||
events: with_hosts(slice(events, length(events) > 60 ? length(events) - 60 : 0)),
|
||||
like_home: loop.status(),
|
||||
awg: awg.caps(),
|
||||
awg_state: awg.state(),
|
||||
};
|
||||
}
|
||||
|
||||
function events_list(a) {
|
||||
// Tunnel down/up events of older versions: the service log tells it better (names, reasons).
|
||||
let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up');
|
||||
let n = +a.limit || 300;
|
||||
return { events: with_hosts(slice(ev, length(ev) > n ? length(ev) - n : 0)), total: length(ev), policy: live.policy() };
|
||||
}
|
||||
|
||||
/** Remove activity by person, device, category and/or age; nothing given clears it all. */
|
||||
function logs_clear(a) {
|
||||
let m = core.load();
|
||||
let f = {};
|
||||
if (a.person) {
|
||||
if (!m.people[a.person])
|
||||
die('Unknown person.');
|
||||
f.person = a.person;
|
||||
}
|
||||
if (a.device)
|
||||
f.device = a.device;
|
||||
if (a.category) {
|
||||
if (index(live.CATEGORIES, a.category) < 0)
|
||||
die('Unknown category.');
|
||||
f.category = a.category;
|
||||
}
|
||||
if (a.older_days) {
|
||||
if (!match(a.older_days, /^[1-9][0-9]{0,3}$/))
|
||||
die('Older than must be a number of days.');
|
||||
f.before = time() - +a.older_days * 86400;
|
||||
}
|
||||
let removed = live.clear_events(f);
|
||||
if (removed)
|
||||
admin_log('dawnline', 'cleared', null, 'the activity log',
|
||||
join(' · ', filter([ `${removed} event${removed == 1 ? '' : 's'}`, f.category, f.person ? m.people[f.person].name : null,
|
||||
a.older_days ? `older than ${a.older_days} days` : null ], (x) => x)));
|
||||
return { ok: true, removed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset traffic history (all | person | device). The agent owns the live
|
||||
* counters, so it gets a marker; the tmpfs copy is edited too so the UI
|
||||
* shows the result straight away.
|
||||
*/
|
||||
function usage_clear(a) {
|
||||
let m = core.load();
|
||||
if (index([ 'all', 'person', 'device' ], a.scope) < 0)
|
||||
die('Unknown scope.');
|
||||
if (a.scope == 'person' && !m.people[a.id])
|
||||
die('Unknown person.');
|
||||
if (a.scope == 'device' && !m.devices[a.id])
|
||||
die('Unknown device.');
|
||||
let req = { scope: a.scope, id: a.id, ts: time() };
|
||||
ensure_dir(RUN_DIR);
|
||||
let l = lock('usage-reset');
|
||||
let pending = read_json(`${RUN_DIR}/usage.reset`, []);
|
||||
push(pending, req);
|
||||
write_json(`${RUN_DIR}/usage.reset`, pending, 0o600);
|
||||
unlock(l);
|
||||
let usage = core.load_usage();
|
||||
if (usage) {
|
||||
live.reset_usage(usage, m, a.scope, a.id);
|
||||
write_json(`${RUN_DIR}/usage.json`, usage, 0o600);
|
||||
}
|
||||
admin_log('dawnline', 'reset traffic history', null,
|
||||
a.scope == 'all' ? 'for everyone' : a.scope == 'person' ? `for ${m.people[a.id].name}` : `for ${m.devices[a.id].name} (${m.people[m.devices[a.id].person]?.name})`);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
status: { args: { days: 30 }, call: wrap(status) },
|
||||
events: { args: { limit: 300 }, call: wrap(events_list) },
|
||||
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
|
||||
usage_clear: { args: { scope: '', id: '' }, call: wrap(usage_clear) },
|
||||
geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) },
|
||||
};
|
||||
@@ -0,0 +1,139 @@
|
||||
// Dawnline rpcd methods for the Components tab: status, starting update jobs
|
||||
// (the updater does the work in the background), releases, release notes
|
||||
// and the changes between two releases. luci.dawnline merges `methods`.
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { read_json, ensure_dir, VERSION, REPO, RUN_DIR } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as gh from 'dawnline.github';
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
import { NAMES as PKG_NAMES } from 'dawnline.upd_pkgs';
|
||||
|
||||
const TAG = /^v?[0-9][0-9A-Za-z.+~-]{0,40}$/;
|
||||
// check[:app|amneziawg|packages] | app[@tag|:reinstall|:rollback]
|
||||
// | amneziawg[:auto|slava|grey[:ru]|:rollback] | pkgs:<name,…> (only packages Dawnline manages)
|
||||
const TARGET = /^(check(:(app|amneziawg|packages))?|app(@v?[0-9][0-9A-Za-z.+~-]{0,40}|:reinstall|:rollback)?|amneziawg(:rollback|:(auto|slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/;
|
||||
|
||||
function wrap(fn) {
|
||||
return function(req) {
|
||||
try {
|
||||
let r = fn(req.args ?? {});
|
||||
return type(r) == 'object' ? r : { result: r };
|
||||
}
|
||||
catch (e) {
|
||||
return { error: e.message ?? `${e}` };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** AmneziaWG interfaces by name: switching builds restarts them. */
|
||||
function awg_tunnels() {
|
||||
let out = [];
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
c.foreach('network', 'interface', (s) => {
|
||||
if (s.proto == 'amneziawg' && s.disabled != '1')
|
||||
push(out, s._dawnline_name ?? s['.name']);
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function status(a) {
|
||||
let m = core.load();
|
||||
let rel = {};
|
||||
for (let line in split(readfile('/etc/openwrt_release') ?? '', '\n')) {
|
||||
let x = match(line, /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/);
|
||||
if (x)
|
||||
rel[lc(x[1])] = x[2];
|
||||
}
|
||||
return {
|
||||
version: VERSION,
|
||||
firmware: { version: rel.release ?? '', target: rel.target ?? '', arch: rel.arch ?? '' },
|
||||
portal: m.settings.portal_enabled,
|
||||
home: length(filter(values(m.servers), (x) => x.lan_like)) > 0,
|
||||
needs: health.needs(),
|
||||
check: read_json(upd.CHECK_FILE, null),
|
||||
job: upd.job(),
|
||||
now: time(),
|
||||
repo: REPO,
|
||||
policy: m.settings.updates,
|
||||
auto: upd.auto_state(),
|
||||
kept: upd.kept_all(builds.firmware()?.postfix),
|
||||
history: slice(upd.history(), 0, 12),
|
||||
tunnels: awg_tunnels(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Releases for the Versions list (Dawnline), five per page. */
|
||||
function releases(a) {
|
||||
let page = +(a.page ?? 1);
|
||||
if (page != int(page) || page < 1 || page > 50)
|
||||
die('Unknown page.');
|
||||
return { releases: map(gh.releases(REPO, page), (x) => ({ ...x, body: null, digests: null })), page };
|
||||
}
|
||||
|
||||
/** Release notes for What's new: Dawnline by tag, or an AmneziaWG build's release. */
|
||||
function notes(a) {
|
||||
let rp = a.component == 'amneziawg' ? builds.SOURCES[a.build || 'slava']?.repo : REPO;
|
||||
let tag = a.tag ?? '';
|
||||
if (!rp || !match(tag, TAG))
|
||||
die('Unknown release.');
|
||||
let r = gh.release(rp, tag);
|
||||
if (!r && a.component != 'amneziawg' && substr(tag, 0, 1) != 'v')
|
||||
r = gh.release(rp, `v${tag}`);
|
||||
if (!r)
|
||||
die(`No release ${tag} in ${rp}.`);
|
||||
return { ...r, digests: null, repo: rp };
|
||||
}
|
||||
|
||||
/** What changed between the installed Dawnline and a release (points for the Components tab). */
|
||||
function changes(a) {
|
||||
let to = a.to ?? '', from = a.from ?? '';
|
||||
if (!match(to, TAG) || (from != '' && !match(from, TAG)))
|
||||
die('Unknown release.');
|
||||
// The installed version as a tag when it was released (a build ahead of the releases has none).
|
||||
let base = null;
|
||||
for (let t in (from != '' ? [ `v${replace(from, /^v/, '')}`, replace(from, /^v/, '') ] : []))
|
||||
if (!base && gh.release(REPO, t))
|
||||
base = t;
|
||||
return { items: gh.changes(REPO, base, to) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Start an update job. Returns the new job once its worker has written it,
|
||||
* else null (the caller follows updates_status); never an older job.
|
||||
*/
|
||||
function run(a) {
|
||||
let what = a.what ?? 'check';
|
||||
if (length(what) > 400 || !match(what, TARGET))
|
||||
die('Unknown update target.');
|
||||
// Checked here too, so a wrong name never becomes a failed job in the history.
|
||||
if (substr(what, 0, 5) == 'pkgs:')
|
||||
for (let n in split(substr(what, 5), ','))
|
||||
if (index(PKG_NAMES, n) < 0)
|
||||
die(n == '' ? 'Unknown update target.' : `${n} is not a package Dawnline manages.`);
|
||||
if (upd.busy())
|
||||
die('Another component action is already running.');
|
||||
ensure_dir(RUN_DIR);
|
||||
let t0 = time();
|
||||
let args = substr(what, 0, 5) == 'check' ? `check ${substr(what, 6)}` : `install ${what}`;
|
||||
system(`start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${args}`);
|
||||
for (let i = 0; i < 20; i++) {
|
||||
let j = read_json(upd.JOB_FILE, null);
|
||||
if (j?.state == 'running' && j.started >= t0)
|
||||
return { started: true, job: j };
|
||||
system('usleep 100000 2>/dev/null || sleep 1');
|
||||
}
|
||||
return { started: true, job: null };
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
updates_status: { call: wrap(status) },
|
||||
updates_run: { args: { what: '' }, call: wrap(run) },
|
||||
updates_releases: { args: { page: 1 }, call: wrap(releases) },
|
||||
updates_notes: { args: { component: '', tag: '', build: '' }, call: wrap(notes) },
|
||||
updates_changes: { args: { from: '', to: '' }, call: wrap(changes) },
|
||||
};
|
||||
@@ -0,0 +1,254 @@
|
||||
// Dawnline — what the settings section may hold: one entry per option with
|
||||
// its type, default and range, used to validate what the admin saves and to
|
||||
// parse what is stored. Also the address checks the rest of the code shares.
|
||||
//
|
||||
// Booleans are stored as '1' / '0' only, and parsed the way the init script's
|
||||
// config_get_bool does, so the service and the code never disagree.
|
||||
|
||||
import { stat } from 'fs';
|
||||
import { ip2int, valid_host } from 'dawnline.util';
|
||||
import { INTERVALS, TARGETS } from 'dawnline.updates';
|
||||
|
||||
/* ---------- addresses ---------- */
|
||||
|
||||
/** An IPv4 address in dotted form. */
|
||||
export function ipv4(s) {
|
||||
return type(s) == 'string' && ip2int(s) != null;
|
||||
};
|
||||
|
||||
/**
|
||||
* An IPv6 address → its eight 16-bit groups, or null. Accepts '::' and an
|
||||
* embedded IPv4 at the end (::ffff:192.0.2.1); no zone ids or prefixes.
|
||||
*/
|
||||
export function ipv6_groups(s) {
|
||||
if (type(s) != 'string' || length(s) < 2 || length(s) > 45 || !match(s, /^[0-9A-Fa-f:.]+$/))
|
||||
return null;
|
||||
let tail = [];
|
||||
let v4 = match(s, /^(.*:)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/);
|
||||
if (v4) {
|
||||
let n = ip2int(v4[2]);
|
||||
if (n == null)
|
||||
return null;
|
||||
tail = [ (n >> 16) & 0xffff, n & 0xffff ];
|
||||
s = substr(v4[1], -2) == '::' ? v4[1] : substr(v4[1], 0, length(v4[1]) - 1);
|
||||
}
|
||||
else if (index(s, '.') >= 0)
|
||||
return null;
|
||||
let halves = split(s, '::');
|
||||
if (length(halves) > 2)
|
||||
return null;
|
||||
let groups = (part) => {
|
||||
let out = [];
|
||||
if (part == '')
|
||||
return out;
|
||||
for (let g in split(part, ':')) {
|
||||
if (!match(g, /^[0-9A-Fa-f]{1,4}$/))
|
||||
return null;
|
||||
push(out, hex(g));
|
||||
}
|
||||
return out;
|
||||
};
|
||||
let head = groups(halves[0]);
|
||||
let rest = length(halves) == 2 ? groups(halves[1]) : [];
|
||||
if (head == null || rest == null)
|
||||
return null;
|
||||
if (length(halves) == 1) {
|
||||
push(head, ...tail);
|
||||
return length(head) == 8 ? head : null;
|
||||
}
|
||||
push(rest, ...tail);
|
||||
let gap = 8 - length(head) - length(rest);
|
||||
if (gap < 1)
|
||||
return null;
|
||||
let out = [ ...head ];
|
||||
for (let i = 0; i < gap; i++)
|
||||
push(out, 0);
|
||||
push(out, ...rest);
|
||||
return out;
|
||||
};
|
||||
|
||||
/** An IPv6 address (any valid notation). */
|
||||
export function ipv6(s) {
|
||||
return ipv6_groups(s) != null;
|
||||
};
|
||||
|
||||
/** An IPv4 or IPv6 address. */
|
||||
export function ip(s) {
|
||||
return ipv4(s) || ipv6(s);
|
||||
};
|
||||
|
||||
/** A TCP/UDP port as typed: 1-5 digits, 1-65535. */
|
||||
export function valid_port(v) {
|
||||
let s = trim(`${v ?? ''}`);
|
||||
return match(s, /^[0-9]{1,5}$/) != null && +s >= 1 && +s <= 65535;
|
||||
};
|
||||
|
||||
/* ---------- parsing stored values ---------- */
|
||||
|
||||
/** A stored boolean, as the init script's config_get_bool reads it. */
|
||||
export function bool(v, dflt) {
|
||||
v = lc(trim(`${v ?? ''}`));
|
||||
if (index([ '1', 'on', 'true', 'yes', 'enabled' ], v) >= 0)
|
||||
return true;
|
||||
if (index([ '0', 'off', 'false', 'no', 'disabled' ], v) >= 0)
|
||||
return false;
|
||||
return dflt;
|
||||
};
|
||||
|
||||
/** A stored whole number within [min, max], else the default. */
|
||||
export function to_int(v, dflt, lo, hi) {
|
||||
let s = trim(`${v ?? ''}`);
|
||||
if (!match(s, /^-?[0-9]{1,9}$/))
|
||||
return dflt;
|
||||
let n = +s;
|
||||
return (lo != null && n < lo) || (hi != null && n > hi) ? dflt : n;
|
||||
};
|
||||
|
||||
/* ---------- the settings section ---------- */
|
||||
|
||||
/*
|
||||
* type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | text | targets
|
||||
* dflt: the parsed default; restart: the portal (uhttpd) must restart when it changes;
|
||||
* min/max: ints and text length; values: enums; msg: the error for a bad value.
|
||||
*/
|
||||
export const SETTINGS = {
|
||||
portal_enabled: { type: 'bool', dflt: false, restart: true },
|
||||
portal_host: { type: 'host', dflt: '', restart: true, msg: 'Public address must be a hostname or IP address.' },
|
||||
portal_alt: { type: 'hosts', dflt: [], restart: true },
|
||||
portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true,
|
||||
msg: 'Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).' },
|
||||
portal_title: { type: 'text', dflt: 'Dawnline', max: 64, msg: 'Portal title: up to 64 characters on one line.' },
|
||||
portal_redirect: { type: 'url', dflt: '', msg: 'Redirect must be a full http:// or https:// address.' },
|
||||
portal_cert: { type: 'file', dflt: '', restart: true },
|
||||
portal_key: { type: 'file', dflt: '', restart: true },
|
||||
default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32, msg: 'Default device limit must be 1-32.' },
|
||||
hostnames: { type: 'bool', dflt: true },
|
||||
domain: { type: 'domain', dflt: 'lan', msg: 'Domain may use lowercase letters, digits, dashes and dots.' },
|
||||
geo_enabled: { type: 'bool', dflt: true },
|
||||
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ], msg: 'Unknown location service.' },
|
||||
log_connections: { type: 'bool', dflt: true },
|
||||
watchdog: { type: 'bool', dflt: true },
|
||||
log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999, msg: 'Keep activity for 0 (no age limit) to 9999 days.' },
|
||||
log_max: { type: 'int', dflt: 2000, min: 100, max: 20000, msg: 'Log size must be 100-20000 events.' },
|
||||
log_persist: { type: 'enum', dflt: 'hourly', values: [ '10min', 'hourly', 'off' ], msg: 'Save the log every 10min, hourly or off.' },
|
||||
usage_keep_days: { type: 'int', dflt: 62, min: 7, max: 1830, msg: 'Daily traffic history must be 7-1830 days.' },
|
||||
usage_keep_months: { type: 'int', dflt: 24, min: 1, max: 120, msg: 'Monthly traffic history must be 1-120 months.' },
|
||||
// Empty means "no fallback" (stored as 'none'); unset means the default.
|
||||
home_dns_fallback: { type: 'ipv4', dflt: '1.1.1.1', msg: 'Fallback DNS must be an IPv4 address (or empty for none).' },
|
||||
update_check: { type: 'bool', dflt: true },
|
||||
update_interval: { type: 'enum', dflt: '1d', values: keys(INTERVALS), msg: 'Check every 6h, 12h, 1d or 7d.' },
|
||||
update_auto: { type: 'bool', dflt: true },
|
||||
update_mode: { type: 'enum', dflt: 'scheduled', values: [ 'immediate', 'scheduled' ], msg: 'Install updates immediately or scheduled.' },
|
||||
update_time: { type: 'time', dflt: '04:00', msg: 'Enter a time as HH:MM, 00:00 to 23:59.' },
|
||||
update_targets: { type: 'targets', dflt: [ 'app', 'packages' ] },
|
||||
update_keep: { type: 'bool', dflt: false },
|
||||
update_mirrors: { type: 'bool', dflt: true },
|
||||
};
|
||||
|
||||
/** Ports the portal never takes: SSH, DNS and the LuCI web server. */
|
||||
export const RESERVED_PORTS = [ 22, 53, 80, 443 ];
|
||||
|
||||
function bad(spec, key) {
|
||||
die(spec.msg ?? `Invalid value for ${key}.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a value the admin saves for setting `key`. Returns what to store: a
|
||||
* string, a list, or null to remove the option (back to the default). Dies
|
||||
* with a message for the admin when the value is not acceptable.
|
||||
*/
|
||||
export function validate(key, val) {
|
||||
let spec = SETTINGS[key];
|
||||
if (!spec)
|
||||
die(`Unknown setting ${key}.`);
|
||||
let t = spec.type;
|
||||
if (t == 'hosts') {
|
||||
let lst = [];
|
||||
for (let x in (type(val) == 'array' ? val : []))
|
||||
if (type(x) == 'string' && valid_host(trim(x)) && index(lst, trim(x)) < 0)
|
||||
push(lst, trim(x));
|
||||
return length(lst) ? lst : null;
|
||||
}
|
||||
if (t == 'targets') {
|
||||
let lst = [];
|
||||
for (let x in (type(val) == 'array' ? val : []))
|
||||
if (index(TARGETS, x) >= 0 && index(lst, x) < 0)
|
||||
push(lst, x);
|
||||
// An empty list is a choice too ("none"), unlike a missing option (the default).
|
||||
return length(lst) ? lst : [ 'none' ];
|
||||
}
|
||||
if (type(val) == 'bool')
|
||||
val = val ? '1' : '0';
|
||||
val = trim(`${val ?? ''}`);
|
||||
if (t == 'ipv4' && val == '')
|
||||
return 'none';
|
||||
if (val == '')
|
||||
return null;
|
||||
if (t == 'bool') {
|
||||
if (val != '0' && val != '1')
|
||||
die(`${key} is 0 or 1.`);
|
||||
}
|
||||
else if (t == 'int') {
|
||||
if (!match(val, /^[0-9]{1,9}$/) || +val < spec.min || +val > spec.max)
|
||||
bad(spec, key);
|
||||
val = `${+val}`;
|
||||
}
|
||||
else if (t == 'enum') {
|
||||
if (index(spec.values, val) < 0)
|
||||
bad(spec, key);
|
||||
}
|
||||
else if (t == 'host') {
|
||||
if (!valid_host(val))
|
||||
bad(spec, key);
|
||||
}
|
||||
else if (t == 'url') {
|
||||
if (length(val) > 300 || !match(val, /^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^[:space:]"'<>]*)?$/))
|
||||
bad(spec, key);
|
||||
}
|
||||
else if (t == 'file') {
|
||||
if (substr(val, 0, 1) != '/' || !stat(val))
|
||||
die(`${val} does not exist.`);
|
||||
}
|
||||
else if (t == 'domain') {
|
||||
if (!match(val, /^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/))
|
||||
bad(spec, key);
|
||||
}
|
||||
else if (t == 'ipv4') {
|
||||
if (!ipv4(val))
|
||||
bad(spec, key);
|
||||
}
|
||||
else if (t == 'time') {
|
||||
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
|
||||
bad(spec, key);
|
||||
}
|
||||
else if (t == 'text') {
|
||||
if (length(val) > spec.max || match(val, /[[:cntrl:]]/))
|
||||
bad(spec, key);
|
||||
}
|
||||
return val;
|
||||
};
|
||||
|
||||
/**
|
||||
* A stored setting parsed by its schema entry: the typed value, or the default
|
||||
* when it is missing or invalid. For dawnline.core's load().
|
||||
*/
|
||||
export function get(raw, key) {
|
||||
let spec = SETTINGS[key];
|
||||
let v = raw?.[key];
|
||||
if (!spec)
|
||||
return v;
|
||||
let t = spec.type;
|
||||
if (t == 'bool')
|
||||
return bool(v, spec.dflt);
|
||||
if (t == 'int')
|
||||
return to_int(v, spec.dflt, spec.min, spec.max);
|
||||
if (t == 'hosts' || t == 'targets')
|
||||
return v == null ? spec.dflt : filter(type(v) == 'array' ? v : [ v ], (x) => x != '');
|
||||
if (v == null || v == '')
|
||||
return spec.dflt;
|
||||
if (t == 'enum')
|
||||
return index(spec.values, v) >= 0 ? v : spec.dflt;
|
||||
if (t == 'ipv4')
|
||||
return v == 'none' ? '' : (ipv4(v) ? v : spec.dflt);
|
||||
return v;
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
// Dawnline — changes to /etc/config/dawnline, the one way: under the config
|
||||
// lock, against a model loaded inside that lock, committed with the file kept
|
||||
// private. rpcd, the portal, the CLI and the agent all go through here, so
|
||||
// no change is made on a stale model and none is lost to another writer.
|
||||
|
||||
import { lock, unlock } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
|
||||
/** Section names that are never ids of people, devices, servers, services or circles. */
|
||||
export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
|
||||
|
||||
/** Commit the dawnline config and keep it readable by root only. */
|
||||
export function commit(c) {
|
||||
c.commit(core.CONFIG);
|
||||
system('chmod 600 /etc/config/dawnline');
|
||||
};
|
||||
|
||||
/**
|
||||
* Run fn(c, m) with the config lock held, on a fresh cursor and model; commit
|
||||
* when fn returns (the return value is passed on). Anything fn throws aborts
|
||||
* without committing and is rethrown with the same message.
|
||||
*/
|
||||
export function transact(fn) {
|
||||
let l = lock('config');
|
||||
try {
|
||||
let c = core.open_cursor();
|
||||
let m = core.load(c);
|
||||
let r = fn(c, m);
|
||||
commit(c);
|
||||
unlock(l);
|
||||
return r;
|
||||
}
|
||||
catch (e) {
|
||||
unlock(l);
|
||||
die(e.message ?? `${e}`);
|
||||
}
|
||||
};
|
||||
|
||||
/** Is `id` used by anything in the model (any kind of section), or reserved? */
|
||||
export function id_taken(m, id) {
|
||||
return index(RESERVED_IDS, id) >= 0 || m.servers?.[id] != null || m.people?.[id] != null || m.devices?.[id] != null ||
|
||||
m.services?.[id] != null || m.circles?.[id] != null;
|
||||
};
|
||||
@@ -0,0 +1,135 @@
|
||||
// Dawnline updater: Dawnline itself — check the latest release, install a
|
||||
// release (latest, a tag, the same one again) or the kept previous version.
|
||||
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { VERSION, REPO } from 'dawnline.util';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as gh from 'dawnline.github';
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
|
||||
function status(installed, latest) {
|
||||
let c = upd.version_cmp(installed, latest);
|
||||
return c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
|
||||
}
|
||||
|
||||
export function check(ctx) {
|
||||
let r = gh.latest(REPO);
|
||||
if (!r)
|
||||
return { installed: VERSION, latest: null, update: false, repo: REPO, status: '', note: `Cannot reach github.com/${REPO}` };
|
||||
let latest = replace(r.tag, /^v/, '');
|
||||
let st = status(VERSION, latest);
|
||||
ctx.log(st == 'outdated' ? `Dawnline update is available: ${VERSION} → ${latest}`
|
||||
: st == 'dev' ? `Installed Dawnline ${VERSION} is newer than the release ${latest}`
|
||||
: `Dawnline is up to date (${VERSION})`);
|
||||
return { installed: VERSION, latest, tag: r.tag, repo: REPO, url: r.url, published: r.published, update: st == 'outdated', status: st };
|
||||
};
|
||||
|
||||
/**
|
||||
* The sha256 a release publishes for a file: GitHub's own (API), else the
|
||||
* release's sha256sums.txt fetched straight from github.com (never a mirror).
|
||||
*/
|
||||
function want_sha(ctx, tag, asset, dir) {
|
||||
let want = gh.asset_sha256(REPO, tag, asset);
|
||||
if (want)
|
||||
return want;
|
||||
let sums = `${dir}/sha256sums-${replace(tag, /[^A-Za-z0-9.-]/g, '_')}.txt`;
|
||||
if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/sha256sums.txt`, sums, { mirrors: false, log: ctx.log }))
|
||||
return null;
|
||||
for (let line in split(readfile(sums) ?? '', '\n')) {
|
||||
let m = match(trim(line), /^([0-9a-f]{64})[ \t]+\*?(\S+)$/);
|
||||
if (m && m[2] == asset)
|
||||
return m[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Download a release's package, verified against its sha256. */
|
||||
function fetch(ctx, tag, dir) {
|
||||
let ver = replace(tag, /^v/, '');
|
||||
let asset = `luci-app-dawnline-${ver}.${pkg.ext()}`;
|
||||
ctx.phase(`Downloading ${asset}`);
|
||||
let want = want_sha(ctx, tag, asset, dir);
|
||||
if (!want)
|
||||
die(`Release ${tag} publishes no checksum for ${asset}: not installing an unverified package`);
|
||||
let f = `${dir}/${asset}`;
|
||||
if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/${asset}`, f, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log }))
|
||||
die(`Download failed: ${asset}`);
|
||||
ctx.log(`sha256 matches the release (${substr(want, 0, 12)}…)`);
|
||||
return f;
|
||||
}
|
||||
|
||||
/** The release tag of a version: tags may or may not carry the v. */
|
||||
function tag_of(ver) {
|
||||
for (let t in [ `v${ver}`, ver ]) {
|
||||
try {
|
||||
if (gh.release(REPO, t))
|
||||
return t;
|
||||
}
|
||||
catch (e) {}
|
||||
}
|
||||
return `v${ver}`;
|
||||
}
|
||||
|
||||
function backup(ctx) {
|
||||
ctx.phase('Backing up configuration');
|
||||
system('/usr/bin/dawnline backup --reason pre-update >/dev/null 2>&1');
|
||||
}
|
||||
|
||||
/** arg: null (latest) | @<tag> | reinstall | rollback */
|
||||
export function install(ctx, arg) {
|
||||
let out = { from: VERSION, to: null };
|
||||
if (arg == 'rollback') {
|
||||
let k = upd.kept('app');
|
||||
if (!k)
|
||||
die('No previous Dawnline version is kept on the router');
|
||||
out.to = k.version;
|
||||
ctx.versions(VERSION, k.version);
|
||||
backup(ctx);
|
||||
ctx.phase(`Rolling back to ${k.version}`);
|
||||
if (!pkg.install_files(k.files, true, ctx.log))
|
||||
die('Installation failed');
|
||||
upd.forget('app');
|
||||
ctx.after('app');
|
||||
return out;
|
||||
}
|
||||
let tag, force = false;
|
||||
if (arg == 'reinstall') {
|
||||
tag = tag_of(VERSION);
|
||||
force = true;
|
||||
}
|
||||
else if (arg && substr(arg, 0, 1) == '@') {
|
||||
tag = substr(arg, 1);
|
||||
force = upd.version_cmp(replace(tag, /^v/, ''), VERSION) <= 0;
|
||||
}
|
||||
else {
|
||||
let c = check(ctx);
|
||||
if (!c.latest)
|
||||
die(c.note);
|
||||
if (!c.update) {
|
||||
out.to = VERSION;
|
||||
return out;
|
||||
}
|
||||
tag = c.tag;
|
||||
}
|
||||
out.to = replace(tag, /^v/, '');
|
||||
ctx.versions(VERSION, out.to);
|
||||
let f = fetch(ctx, tag, ctx.work);
|
||||
// The version being replaced, for Roll back (downloaded again: opkg keeps no package files).
|
||||
if (ctx.pol.keep && out.to != VERSION && upd.kept('app')?.version != VERSION) {
|
||||
ctx.phase(`Keeping Dawnline ${VERSION} for rollback`);
|
||||
try {
|
||||
system(`mkdir -p '${ctx.work}/keep'`);
|
||||
upd.keep('app', VERSION, [ fetch(ctx, tag_of(VERSION), `${ctx.work}/keep`) ]);
|
||||
}
|
||||
catch (e) {
|
||||
ctx.log(`Warning: could not keep ${VERSION}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
backup(ctx);
|
||||
ctx.phase('Installing package');
|
||||
if (!pkg.install_files([ f ], force, ctx.log))
|
||||
die('Installation failed');
|
||||
ctx.after('app');
|
||||
return out;
|
||||
};
|
||||
@@ -0,0 +1,231 @@
|
||||
// Dawnline updater: AmneziaWG — the builds published for this firmware by
|
||||
// each source, installing or switching a build (verified against GitHub's
|
||||
// sha256), the Russian LuCI translation, and rolling back to a kept build.
|
||||
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
|
||||
|
||||
import { stat } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { iface_intent } from 'dawnline.util';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as gh from 'dawnline.github';
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
|
||||
function sh(cmd) {
|
||||
return system(`${cmd} >/dev/null 2>&1`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download one package of a build to dir, verified when GitHub publishes its
|
||||
* sha256 (then mirrors may serve it); without a sha256 only github.com itself.
|
||||
* Returns the path or null.
|
||||
*/
|
||||
function fetch(ctx, fw, name, src, dir) {
|
||||
let file = builds.asset(fw, name);
|
||||
let dest = `${dir}/${src}_${file}`;
|
||||
let want = gh.asset_sha256(builds.SOURCES[src].repo, fw.tag, file);
|
||||
let url = `https://github.com/${builds.SOURCES[src].repo}/releases/download/${fw.tag}/${file}`;
|
||||
return gh.download(url, dest, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log }) ? dest : null;
|
||||
}
|
||||
|
||||
/** 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 series = match(tag, /^v([0-9]+\.[0-9]+)\./)?.[1];
|
||||
let best = null;
|
||||
try {
|
||||
for (let x in gh.releases(rp, 1)) {
|
||||
let t = x.tag;
|
||||
if (series && match(t, regexp(`^v${replace(series, '.', '\\.')}\\.`)) && pkg.cmp(substr(t, 1), substr(tag, 1)) > 0 &&
|
||||
(!best || pkg.cmp(substr(t, 1), substr(best, 1)) > 0))
|
||||
best = t;
|
||||
}
|
||||
}
|
||||
catch (e) {}
|
||||
return best;
|
||||
}
|
||||
|
||||
export function check(ctx) {
|
||||
let installed = builds.installed();
|
||||
let ru = pkg.version(builds.RU) != null;
|
||||
let cur = installed['amneziawg-tools'];
|
||||
let fw = builds.firmware();
|
||||
if (!fw)
|
||||
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
|
||||
note: 'Cannot detect the firmware target' };
|
||||
let dir = `${ctx.work}/check`;
|
||||
system(`mkdir -p '${dir}'`);
|
||||
let sources = {};
|
||||
for (let id in builds.ORDER) {
|
||||
let src = builds.SOURCES[id];
|
||||
ctx.log(`Looking for the ${src.label} build for OpenWrt ${substr(fw.tag, 1)}`);
|
||||
let f = fetch(ctx, fw, 'amneziawg-tools', id, dir);
|
||||
let v = f ? pkg.file_version(f) : null;
|
||||
let date = null;
|
||||
try {
|
||||
date = f ? gh.release(src.repo, fw.tag)?.published : null;
|
||||
}
|
||||
catch (e) {}
|
||||
let s = { label: src.label, repo: src.repo, tag: fw.tag, version: v, gen: builds.gen(v), date };
|
||||
// A newer firmware may already get 3.1 from this source.
|
||||
if (s.gen != '3.1') {
|
||||
let nt = newer_series_tag(src.repo, fw.tag);
|
||||
if (nt) {
|
||||
let nf = fetch(ctx, builds.for_tag(fw, nt), 'amneziawg-tools', id, dir);
|
||||
if (builds.gen(nf ? pkg.file_version(nf) : null) == '3.1')
|
||||
s.newer = { tag: nt, gen: '3.1' };
|
||||
}
|
||||
}
|
||||
sources[id] = s;
|
||||
}
|
||||
// The installed build: the source whose package matches. Unknown stays unknown
|
||||
// (an automatic update never switches a build it could not identify).
|
||||
let current = null;
|
||||
for (let id, x in sources)
|
||||
if (!current && cur && x.version == cur)
|
||||
current = id;
|
||||
let mine = current ? sources[current] : null;
|
||||
let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null;
|
||||
let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
|
||||
ctx.log(cur == null ? 'AmneziaWG is not installed'
|
||||
: !current ? `AmneziaWG ${cur}: no source publishes this build for this firmware any more`
|
||||
: st == 'outdated' ? `AmneziaWG update is available: ${cur} → ${mine.version}`
|
||||
: `AmneziaWG is up to date (${cur})`);
|
||||
return { installed: cur, gen: builds.gen(cur), packages: installed, current, ru, release: fw.tag, sources,
|
||||
latest: mine?.version ?? null, status: st,
|
||||
update: cur == null || st == 'outdated',
|
||||
// An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic.
|
||||
gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version),
|
||||
note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} yet` : null };
|
||||
};
|
||||
|
||||
/** Tunnels on a new kernel module: every AmneziaWG interface is brought down and up again. */
|
||||
function reload_module(ctx, before, after) {
|
||||
if (!before['kmod-amneziawg'] || before['kmod-amneziawg'] == after['kmod-amneziawg'])
|
||||
return;
|
||||
let ifaces = [];
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
c.foreach('network', 'interface', (s) => {
|
||||
if (s.proto == 'amneziawg' && s.disabled != '1')
|
||||
push(ifaces, s['.name']);
|
||||
});
|
||||
ctx.phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`);
|
||||
for (let i in ifaces) {
|
||||
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
|
||||
sh(`ifdown '${i}'`);
|
||||
}
|
||||
sh('rmmod amneziawg');
|
||||
ctx.run('modprobe amneziawg');
|
||||
for (let i in ifaces)
|
||||
sh(`ifup '${i}'`);
|
||||
}
|
||||
|
||||
/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */
|
||||
function settle(ctx, before, after) {
|
||||
if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) {
|
||||
ctx.phase('Loading the kernel module');
|
||||
if (ctx.run('modprobe amneziawg').code != 0 && !stat('/sys/module/amneziawg'))
|
||||
die("AmneziaWG is installed, but its kernel module doesn't load on this firmware");
|
||||
}
|
||||
else
|
||||
reload_module(ctx, before, after);
|
||||
// netifd reads its protocol handlers when it starts.
|
||||
if (index(ctx.run('ubus call network get_proto_handlers').out, '"amneziawg"') < 0) {
|
||||
ctx.phase('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)');
|
||||
ctx.run('/etc/init.d/network restart');
|
||||
}
|
||||
ctx.after('apply');
|
||||
}
|
||||
|
||||
/** The first source that publishes every package for this firmware. */
|
||||
function pick(fw) {
|
||||
for (let id in builds.ORDER) {
|
||||
let r = null;
|
||||
try {
|
||||
r = gh.release(builds.SOURCES[id].repo, fw.tag);
|
||||
}
|
||||
catch (e) {}
|
||||
if (r && length(filter(builds.PKGS, (p) => index(r.assets, builds.asset(fw, p)) >= 0)) == length(builds.PKGS))
|
||||
return id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** arg: [auto|slava|grey][:ru] | rollback */
|
||||
export function install(ctx, arg) {
|
||||
let before = builds.installed();
|
||||
let out = { from: before['amneziawg-tools'], to: null, before };
|
||||
let fw = builds.firmware();
|
||||
if (!fw)
|
||||
die('Cannot detect the firmware target');
|
||||
if (arg == 'rollback') {
|
||||
let k = upd.kept('amneziawg');
|
||||
if (!k)
|
||||
die('No previous AmneziaWG build is kept on the router');
|
||||
if (k.firmware && k.firmware != fw.postfix)
|
||||
die('The kept AmneziaWG build was made for another firmware: it would not load on this one');
|
||||
out.to = k.version;
|
||||
out.build = k.build;
|
||||
ctx.versions(out.from, out.to);
|
||||
ctx.phase(`Rolling back to ${k.version}`);
|
||||
if (!pkg.install_files(k.files, true, ctx.log))
|
||||
die('Package installation failed');
|
||||
upd.forget('amneziawg');
|
||||
out.after = builds.installed();
|
||||
settle(ctx, before, out.after);
|
||||
return out;
|
||||
}
|
||||
let parts = split(arg ?? '', ':');
|
||||
let id = parts[0] || 'auto';
|
||||
let want_ru = parts[1] == 'ru';
|
||||
if (id == 'auto') {
|
||||
id = pick(fw);
|
||||
if (!id)
|
||||
die(`No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} (${fw.postfix}) yet`);
|
||||
}
|
||||
let src = builds.SOURCES[id];
|
||||
if (!src)
|
||||
die(`Unknown AmneziaWG build ${id}`);
|
||||
out.build = id;
|
||||
let files = [];
|
||||
for (let p in [ ...builds.PKGS, ...(want_ru ? [ builds.RU ] : []) ]) {
|
||||
ctx.phase(`Downloading ${p} from ${src.repo}`);
|
||||
let f = fetch(ctx, fw, p, id, ctx.work);
|
||||
if (!f)
|
||||
die(`No ${p} build for OpenWrt ${substr(fw.tag, 1)} in ${src.repo}, or it could not be verified`);
|
||||
push(files, f);
|
||||
}
|
||||
out.to = pkg.file_version(files[1]);
|
||||
ctx.versions(out.from, out.to);
|
||||
// The build being replaced, for Roll back: from another source that still publishes it.
|
||||
if (ctx.pol.keep && out.from && out.to != out.from) {
|
||||
let dir = `${ctx.work}/keep`;
|
||||
system(`mkdir -p '${dir}'`);
|
||||
let kept = null;
|
||||
for (let sid in builds.ORDER) {
|
||||
if (sid == id || kept)
|
||||
continue;
|
||||
let f = fetch(ctx, fw, 'amneziawg-tools', sid, dir);
|
||||
if (f && pkg.file_version(f) == out.from)
|
||||
kept = sid;
|
||||
}
|
||||
if (kept) {
|
||||
ctx.phase(`Keeping AmneziaWG ${out.from} for rollback`);
|
||||
let keepf = filter(map(builds.PKGS, (p) => fetch(ctx, fw, p, kept, dir)), (x) => x);
|
||||
if (length(keepf) == length(builds.PKGS))
|
||||
upd.keep('amneziawg', out.from, keepf, kept, fw.postfix);
|
||||
}
|
||||
else
|
||||
ctx.log('Warning: the installed build is no longer published, nothing to keep for rollback');
|
||||
}
|
||||
ctx.phase('Refreshing package lists');
|
||||
pkg.refresh(ctx.log);
|
||||
ctx.phase(`Installing the ${src.label} build`);
|
||||
if (!pkg.install_files(files, true, ctx.log))
|
||||
die('Package installation failed');
|
||||
if (!want_ru && pkg.version(builds.RU))
|
||||
pkg.remove([ builds.RU ], ctx.log);
|
||||
out.after = builds.installed();
|
||||
settle(ctx, before, out.after);
|
||||
return out;
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
// Dawnline updater: the OpenWrt packages Dawnline adds — the home-like link
|
||||
// (ip-full, kmod-veth) and HTTPS plus certificates for the personal portal —
|
||||
// checked against and updated from the OpenWrt feeds.
|
||||
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
|
||||
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
|
||||
/** What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the stock system). */
|
||||
export const NAMES = [ '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 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 FAMILY)
|
||||
if (match(p, f[0]))
|
||||
return f[1];
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 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));
|
||||
}
|
||||
|
||||
/** refresh: update the package lists first (a check by hand or on schedule). */
|
||||
export function check(ctx, refresh) {
|
||||
if (refresh ?? true) {
|
||||
ctx.phase('Refreshing package lists');
|
||||
pkg.refresh();
|
||||
}
|
||||
let up = pkg.upgradable();
|
||||
let res = {}, all = {};
|
||||
for (let p in NAMES) {
|
||||
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;
|
||||
}
|
||||
let n = length(keys(all));
|
||||
ctx.log(n ? `${n} package update${n == 1 ? '' : 's'} in the feeds: ${join(', ', sort(keys(all)))}` : 'System packages are up to date');
|
||||
return { pkgs: res, updates: n, status: n ? 'outdated' : 'latest' };
|
||||
};
|
||||
|
||||
/** arg: name,name,… (only names Dawnline manages): missing ones are installed, present ones updated with their family. */
|
||||
export function install(ctx, arg) {
|
||||
let names = filter(split(arg ?? '', ','), (x) => x != '');
|
||||
for (let n in names)
|
||||
if (index(NAMES, n) < 0)
|
||||
die(`${n} is not a package Dawnline manages`);
|
||||
if (!length(names))
|
||||
die('Nothing to install');
|
||||
ctx.phase('Refreshing package lists');
|
||||
pkg.refresh(ctx.log);
|
||||
let missing = filter(names, (n) => pkg.version(n) == null);
|
||||
let have = with_family(filter(names, (n) => pkg.version(n) != null), pkg.upgradable());
|
||||
if (length(have)) {
|
||||
ctx.phase(`Updating ${join(', ', have)}`);
|
||||
if (!pkg.upgrade(have, ctx.log))
|
||||
die('Update failed');
|
||||
}
|
||||
if (length(missing)) {
|
||||
ctx.phase(`Installing ${join(', ', missing)}`);
|
||||
if (!pkg.add(missing, ctx.log))
|
||||
die('Installation failed');
|
||||
}
|
||||
// The portal's HTTPS runs in uhttpd; a piece that just arrived lets the portal or the home-like link start.
|
||||
let touched = [ ...missing, ...have ];
|
||||
if (length(filter(missing, (n) => match(n, /^(openssl-util|libustream|ip-full|kmod-veth)/)))) {
|
||||
ctx.after('apply');
|
||||
ctx.after('uhttpd');
|
||||
}
|
||||
else if (length(filter(touched, (n) => match(n, /^(libustream|libopenssl)/))))
|
||||
ctx.after('uhttpd');
|
||||
return { updated: have, installed: missing, check: check(ctx, false) };
|
||||
};
|
||||
@@ -0,0 +1,228 @@
|
||||
// Dawnline — what the Components tab, the updater and the agent share: the
|
||||
// update policy (Settings → Updates), when an automatic run is due, the one
|
||||
// update job at a time (a kernel lock), the history for Activity, and the
|
||||
// versions kept for rollback. GitHub and the package manager live in
|
||||
// dawnline.github and dawnline.pkg.
|
||||
|
||||
import { open, stat } from 'fs';
|
||||
import { q, read_json, write_json, ensure_dir, RUN_DIR, DATA_DIR } from 'dawnline.util';
|
||||
|
||||
export const JOB_FILE = `${RUN_DIR}/update-job.json`;
|
||||
export const CHECK_FILE = `${RUN_DIR}/update-check.json`;
|
||||
/** Held (flock) by the updater for the whole job: busy() and stale jobs come from it, not from pids. */
|
||||
export const LOCK_FILE = `${RUN_DIR}/update.lock`;
|
||||
/** Automatic runs: when the last check and the last scheduled install happened. */
|
||||
export const AUTO_FILE = `${DATA_DIR}/update-auto.json`;
|
||||
/** What happened: updates (by hand or automatic), failures, checks that found something. */
|
||||
export const HISTORY_FILE = `${DATA_DIR}/update-history.json`;
|
||||
/** The version each component had before its last update (Keep the previous version). */
|
||||
export const KEEP_DIR = `${DATA_DIR}/keep`;
|
||||
|
||||
export const INTERVALS = { '6h': 6 * 3600, '12h': 12 * 3600, '1d': 86400, '7d': 7 * 86400 };
|
||||
export const TARGETS = [ 'app', 'amneziawg', 'packages' ];
|
||||
|
||||
function on(v, dflt) {
|
||||
if (v == null || v == '')
|
||||
return dflt;
|
||||
return v == '1' || v == 'true' || v == 'on' || v == 'yes';
|
||||
}
|
||||
|
||||
/** The update policy from raw UCI settings (core.load puts it in m.settings.updates). */
|
||||
export function policy(s) {
|
||||
s ??= {};
|
||||
let t = type(s.update_targets) == 'array' ? s.update_targets : s.update_targets ? [ s.update_targets ] : null;
|
||||
let time_ok = match(s.update_time ?? '', /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/);
|
||||
return {
|
||||
check: on(s.update_check, true),
|
||||
interval: INTERVALS[s.update_interval] ? s.update_interval : '1d',
|
||||
auto: on(s.update_auto, true),
|
||||
mode: s.update_mode == 'immediate' ? 'immediate' : 'scheduled',
|
||||
time: time_ok ? s.update_time : '04:00',
|
||||
// AmneziaWG is left out by default: a new kernel module restarts every tunnel.
|
||||
targets: t ? filter(t, (x) => index(TARGETS, x) >= 0) : [ 'app', 'packages' ],
|
||||
keep: on(s.update_keep, false),
|
||||
mirrors: on(s.update_mirrors, true),
|
||||
};
|
||||
};
|
||||
|
||||
/* ---------- schedule ---------- */
|
||||
|
||||
/** The scheduled time on the day of `ts` (router local time), in seconds since the epoch. */
|
||||
function scheduled_on(pol, ts) {
|
||||
let t = localtime(ts);
|
||||
let hm = split(pol.time, ':');
|
||||
return ts - (t.hour * 3600 + t.min * 60 + t.sec) + int(hm[0]) * 3600 + int(hm[1]) * 60;
|
||||
}
|
||||
|
||||
function day_of(ts) {
|
||||
let t = localtime(ts);
|
||||
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
|
||||
}
|
||||
|
||||
/** The scheduled slot `now` is in (up to an hour after the set time, also across midnight), or null. */
|
||||
function slot(pol, now) {
|
||||
for (let at in [ scheduled_on(pol, now), scheduled_on(pol, now - 86400) ])
|
||||
if (now >= at && now - at < 3600)
|
||||
return at;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What an automatic run should do now: 'install' (the scheduled window, at
|
||||
* most an hour after the set time, once per slot), 'check' (the interval has
|
||||
* passed), or null.
|
||||
*/
|
||||
export function due(pol, st, now) {
|
||||
now ??= time();
|
||||
st ??= {};
|
||||
if (pol.auto && pol.mode == 'scheduled' && length(pol.targets)) {
|
||||
let at = slot(pol, now);
|
||||
if (at != null && st.install_day != day_of(at))
|
||||
return 'install';
|
||||
}
|
||||
if (pol.check && now - (st.check ?? 0) >= INTERVALS[pol.interval])
|
||||
return 'check';
|
||||
return null;
|
||||
};
|
||||
|
||||
export function auto_state() {
|
||||
return read_json(AUTO_FILE, {});
|
||||
};
|
||||
|
||||
export function auto_save(st) {
|
||||
ensure_dir(DATA_DIR);
|
||||
write_json(AUTO_FILE, st, 0o600);
|
||||
};
|
||||
|
||||
/** Record that the scheduled slot `now` is in has run (the slot's own day, not today's after midnight). */
|
||||
export function mark_day(pol, st, now) {
|
||||
now ??= time();
|
||||
st.install_day = day_of(slot(pol, now) ?? now);
|
||||
return st;
|
||||
};
|
||||
|
||||
/* ---------- one job at a time ---------- */
|
||||
|
||||
/**
|
||||
* Take the update lock without waiting: the open file (keep it for the whole
|
||||
* job; the kernel releases it when the process ends), or null when another
|
||||
* job holds it.
|
||||
*/
|
||||
export function try_lock() {
|
||||
ensure_dir(RUN_DIR);
|
||||
let f = open(LOCK_FILE, 'a');
|
||||
if (f && f.lock('xn'))
|
||||
return f;
|
||||
f?.close();
|
||||
return null;
|
||||
};
|
||||
|
||||
/** A job is running: someone holds the update lock. */
|
||||
export function busy() {
|
||||
let f = try_lock();
|
||||
if (!f)
|
||||
return true;
|
||||
f.close();
|
||||
return false;
|
||||
};
|
||||
|
||||
/** The last job; a "running" one whose worker is gone (the lock is free) reads as failed. */
|
||||
export function job() {
|
||||
let j = read_json(JOB_FILE, null);
|
||||
if (j?.state == 'running' && !busy()) {
|
||||
j.state = 'failed';
|
||||
j.error = 'The update stopped unexpectedly.';
|
||||
j.finished = j.finished ?? time();
|
||||
}
|
||||
return j;
|
||||
};
|
||||
|
||||
/* ---------- history (Components → Activity) ---------- */
|
||||
|
||||
export function history() {
|
||||
let h = read_json(HISTORY_FILE, []);
|
||||
return type(h) == 'array' ? h : [];
|
||||
};
|
||||
|
||||
/** Newest first, the last 30 kept on flash. */
|
||||
export function history_add(e) {
|
||||
let h = history();
|
||||
unshift(h, { ts: time(), ...e });
|
||||
ensure_dir(DATA_DIR);
|
||||
write_json(HISTORY_FILE, slice(h, 0, 30), 0o600);
|
||||
};
|
||||
|
||||
/* ---------- Dawnline versions ---------- */
|
||||
|
||||
/**
|
||||
* Compare Dawnline release versions (0.3.2, v0.4.0-rc1): -1, 0 or 1. Numbers
|
||||
* compare as numbers; a pre-release (-rc1, -beta) comes before its release.
|
||||
*/
|
||||
export function version_cmp(a, b) {
|
||||
let parse = (v) => {
|
||||
let m = match(replace(`${v}`, /^v/, ''), /^([0-9.]+)([-~]([0-9A-Za-z.]+))?/);
|
||||
return m ? { nums: map(split(m[1], '.'), (x) => int(x)), pre: m[3] } : { nums: [ 0 ], pre: `${v}` };
|
||||
};
|
||||
let x = parse(a), y = parse(b);
|
||||
for (let i = 0; i < length(x.nums) || i < length(y.nums); i++) {
|
||||
let p = x.nums[i] ?? 0, r = y.nums[i] ?? 0;
|
||||
if (p != r)
|
||||
return p < r ? -1 : 1;
|
||||
}
|
||||
if (x.pre == y.pre)
|
||||
return 0;
|
||||
if (x.pre == null)
|
||||
return 1;
|
||||
if (y.pre == null)
|
||||
return -1;
|
||||
// rc1 < rc2 < rc10: compare the number runs as numbers.
|
||||
let px = match(x.pre, /^([^0-9]*)([0-9]*)/), py = match(y.pre, /^([^0-9]*)([0-9]*)/);
|
||||
if (px[1] != py[1])
|
||||
return px[1] < py[1] ? -1 : 1;
|
||||
return int(px[2] || 0) < int(py[2] || 0) ? -1 : int(px[2] || 0) > int(py[2] || 0) ? 1 : 0;
|
||||
};
|
||||
|
||||
/* ---------- kept previous versions ---------- */
|
||||
|
||||
/** { version, build?, firmware?, files: [paths], saved } of the kept version, or null. */
|
||||
export function kept(component) {
|
||||
let k = read_json(`${KEEP_DIR}/${component}/meta.json`, null);
|
||||
if (!k?.version || !length(k.files ?? []))
|
||||
return null;
|
||||
for (let f in k.files)
|
||||
if (!stat(f))
|
||||
return null;
|
||||
return k;
|
||||
};
|
||||
|
||||
/** What the Components tab shows; firmware: the current one (a kept AmneziaWG build is for one firmware only). */
|
||||
export function kept_all(firmware) {
|
||||
let out = {};
|
||||
for (let c in [ 'app', 'amneziawg' ]) {
|
||||
let k = kept(c);
|
||||
if (k && c == 'amneziawg' && k.firmware && firmware && k.firmware != firmware)
|
||||
k = null;
|
||||
out[c] = k ? { version: k.version, build: k.build ?? null, saved: k.saved ?? null } : null;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Replace the kept version of a component with these files (copied in). */
|
||||
export function keep(component, version, files, build, firmware) {
|
||||
let dir = `${KEEP_DIR}/${component}`;
|
||||
system(`rm -rf ${q(dir)}; mkdir -p ${q(dir)}; chmod 700 ${q(KEEP_DIR)} ${q(dir)}`);
|
||||
let saved = [];
|
||||
for (let f in files) {
|
||||
let to = `${dir}/${replace(f, /^.*\//, '')}`;
|
||||
if (system(`cp ${q(f)} ${q(to)}`) == 0)
|
||||
push(saved, to);
|
||||
}
|
||||
if (length(saved) == length(files))
|
||||
write_json(`${dir}/meta.json`, { version, build, firmware, files: saved, saved: time() }, 0o600);
|
||||
else
|
||||
system(`rm -rf ${q(dir)}`);
|
||||
};
|
||||
|
||||
export function forget(component) {
|
||||
system(`rm -rf ${q(KEEP_DIR + '/' + component)}`);
|
||||
};
|
||||
@@ -1,9 +1,10 @@
|
||||
// Dawnline — small helpers shared by the rpcd plugin, the CLI, the agent and
|
||||
// the portal CGI. Nothing in here touches configuration.
|
||||
// the portal CGI. Nothing in here loads or commits configuration (the uci
|
||||
// helpers work on a cursor the caller owns).
|
||||
|
||||
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
|
||||
|
||||
export const VERSION = '0.3.1';
|
||||
export const VERSION = '0.4.0';
|
||||
/** GitHub repository with Dawnline releases (updates and the installer). */
|
||||
export const REPO = 'tickcount/luci-app-dawnline';
|
||||
export const RUN_DIR = '/var/run/dawnline';
|
||||
@@ -91,15 +92,27 @@ export function read_json(path, fallback) {
|
||||
}
|
||||
};
|
||||
|
||||
/** Atomic write (temp file + rename). `mode` defaults to 0600. */
|
||||
/**
|
||||
* Atomic write (temp file + rename). `mode` defaults to 0600. A short write
|
||||
* (flash full) leaves the old file in place and returns false.
|
||||
*/
|
||||
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);
|
||||
data = `${data ?? ''}`;
|
||||
let n = length(data) ? f.write(data) : 0;
|
||||
let closed = f.close();
|
||||
if (n != length(data) || !closed) {
|
||||
unlink(tmp);
|
||||
return false;
|
||||
}
|
||||
if (!rename(tmp, path)) {
|
||||
unlink(tmp);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
export function write_json(path, data, mode) {
|
||||
@@ -126,6 +139,92 @@ export function unlock(f) {
|
||||
}
|
||||
};
|
||||
|
||||
// Locks this process holds through with_lock (flock does not nest: a second
|
||||
// open of the same lock file in one process would wait for itself).
|
||||
let held = {};
|
||||
|
||||
/**
|
||||
* Run fn() holding the named lock and return what it returns. Nested calls
|
||||
* for the same name in one process run fn() directly. Anything fn throws
|
||||
* releases the lock and is rethrown with the same message.
|
||||
*/
|
||||
export function with_lock(name, fn) {
|
||||
if (held[name])
|
||||
return fn();
|
||||
let l = lock(name);
|
||||
held[name] = true;
|
||||
try {
|
||||
let r = fn();
|
||||
delete held[name];
|
||||
unlock(l);
|
||||
return r;
|
||||
}
|
||||
catch (e) {
|
||||
delete held[name];
|
||||
unlock(l);
|
||||
die(e.message ?? `${e}`);
|
||||
}
|
||||
};
|
||||
|
||||
/* ---------- uci (on the caller's cursor) ---------- */
|
||||
|
||||
/** Set an option only when it differs (null, '' or [] delete it); true if something changed. */
|
||||
export function uci_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;
|
||||
};
|
||||
|
||||
/** Make `sec` a section of type `stype` (recreated when its type differs); true if it changed. */
|
||||
export function uci_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.
|
||||
*/
|
||||
export 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');
|
||||
};
|
||||
|
||||
/* ---------- service log ---------- */
|
||||
|
||||
/*
|
||||
@@ -271,6 +370,35 @@ export function int2ip(n) {
|
||||
return sprintf('%d.%d.%d.%d', (n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255);
|
||||
};
|
||||
|
||||
/**
|
||||
* "a.b.c.d[/len]" with any prefix 0-32 (a bare address is a /32) →
|
||||
* { net, prefix, size, ip }; null for anything else. Routes, rules and
|
||||
* allowed networks use this; parse_cidr is the stricter one for subnets.
|
||||
*/
|
||||
export function cidr_any(s) {
|
||||
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
|
||||
if (ip == null || prefix > 32)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
return { net: ip - ip % size, prefix, size, ip };
|
||||
};
|
||||
|
||||
/** The first of `nets` (CIDR strings, any prefix) that holds `ip` (a string or an int), or null. */
|
||||
export function in_nets(ip, nets) {
|
||||
let n = type(ip) == 'int' ? ip : ip2int(ip);
|
||||
if (n == null)
|
||||
return null;
|
||||
for (let s in nets) {
|
||||
let c = cidr_any(s);
|
||||
if (c && n >= c.net && n < c.net + c.size)
|
||||
return s;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// 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',
|
||||
@@ -286,13 +414,7 @@ export function cloudflare_ip(a) {
|
||||
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;
|
||||
return in_nets(n, CF_V4) != null;
|
||||
};
|
||||
|
||||
/** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */
|
||||
@@ -378,6 +500,16 @@ export function day_key(ts) {
|
||||
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
|
||||
};
|
||||
|
||||
/**
|
||||
* The day key `days` days before `ts` (default now). Counted from local noon,
|
||||
* so a 23- or 25-hour day around a DST change neither skips nor repeats a day.
|
||||
*/
|
||||
export function day_key_ago(days, ts) {
|
||||
let t = localtime(ts ?? time());
|
||||
let noon = timelocal({ year: t.year, mon: t.mon, mday: t.mday, hour: 12, min: 0, sec: 0 });
|
||||
return day_key(noon - (days ?? 0) * 86400);
|
||||
};
|
||||
|
||||
export function uniq(arr) {
|
||||
let seen = {}, out = [];
|
||||
for (let v in arr)
|
||||
@@ -399,3 +531,18 @@ export function remove(path) {
|
||||
export function now() {
|
||||
return time();
|
||||
};
|
||||
|
||||
/** netifd's view of an interface (ubus network.interface.<name> status), or null. */
|
||||
export function iface_status(ifname) {
|
||||
if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/))
|
||||
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;
|
||||
}
|
||||
};
|
||||
@@ -3,22 +3,24 @@
|
||||
|
||||
import * as core from 'dawnline.core';
|
||||
import * as live from 'dawnline.live';
|
||||
import { day_key, month_key } from 'dawnline.util';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import { day_key_ago, 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();
|
||||
let out = [];
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
let v = rec?.days?.[day_key(ts - i * 86400)];
|
||||
let v = rec?.days?.[day_key_ago(i)];
|
||||
push(out, v ? v[0] + v[1] : 0);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** The device holds an older configuration than the one it would get now. */
|
||||
function config_stale(m, d) {
|
||||
m._issued ??= core.issued();
|
||||
m._issued ??= awg.issued();
|
||||
let was = m._issued[d.id];
|
||||
return was != null && was != core.config_fingerprint(m, d);
|
||||
return was != null && was != awg.config_fingerprint(m, d);
|
||||
}
|
||||
|
||||
export function device_view(m, d, usage, dmp) {
|
||||
@@ -27,7 +29,7 @@ export function device_view(m, d, usage, dmp) {
|
||||
let ts = time();
|
||||
let hs = peer?.handshake || u?.handshake || 0;
|
||||
let p = m.people[d.person];
|
||||
return {
|
||||
let v = {
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
kind: d.kind,
|
||||
@@ -47,6 +49,7 @@ export function device_view(m, d, usage, dmp) {
|
||||
// Its configuration changed since it was last shown or downloaded.
|
||||
config_stale: config_stale(m, d),
|
||||
};
|
||||
return v;
|
||||
};
|
||||
|
||||
export function person_view(m, p, usage, dmp, states, opts) {
|
||||
@@ -85,9 +88,9 @@ export function person_view(m, p, usage, dmp, states, opts) {
|
||||
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);
|
||||
// The code and links themselves are person_links' (admins only): the
|
||||
// code opens the person's portal and their devices' configurations.
|
||||
v.has_link = core.portal_url(m, p) != null;
|
||||
v.note = p.note;
|
||||
v.services = p.services;
|
||||
v.home_nets = p.home_nets;
|
||||
|
||||
@@ -6,11 +6,12 @@
|
||||
|
||||
import { stat } from 'fs';
|
||||
import { sh_out, q, read_json, write_json, slog, slog_read, 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 loop from 'dawnline.loop';
|
||||
import * as ops from 'dawnline.ops';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as nft from 'dawnline.nft';
|
||||
import * as netifd from 'dawnline.netifd';
|
||||
|
||||
export const STATE = `${RUN_DIR}/watchdog.json`;
|
||||
/** The agent writes the time here on every tick. */
|
||||
@@ -18,13 +19,9 @@ export const BEAT = `${RUN_DIR}/agent.beat`;
|
||||
// Seconds before the next repair, by the number of repairs so far.
|
||||
const WAIT = [ 0, 120, 600, 1800, 3600 ];
|
||||
|
||||
/** Why a tunnel is down, from netifd and the last related syslog lines. */
|
||||
/** Why a tunnel is down (AmneziaWG; kept here for older callers). */
|
||||
export function iface_errors(ifname) {
|
||||
let s = live.iface_status(ifname);
|
||||
let errs = map(s?.errors ?? [], (e) => e.code + (length(e.data ?? []) ? ` (${join(' ', e.data)})` : ''));
|
||||
// Only what explains a failure, not the ordinary "is now up/down" lines.
|
||||
let lines = sh_out(`logread -l 400 2>/dev/null | grep -E ${q(`${ifname}|amneziawg`)} | grep -iE 'error|fail|invalid|unrecogni|cannot|unable|not found|refused|denied' | tail -n 6`);
|
||||
return join('\n', filter([ length(errs) ? `netifd: ${join(', ', errs)}` : null, lines ], (x) => x));
|
||||
return awg.iface_errors(ifname);
|
||||
};
|
||||
|
||||
function restart_services() {
|
||||
@@ -38,30 +35,11 @@ function restart_services() {
|
||||
*/
|
||||
function probes(m) {
|
||||
let out = [];
|
||||
// The kernel module first: without it no tunnel can run (they come back on the next pass).
|
||||
if (length(filter(values(m.servers), (x) => x.enabled && x.private_key)) && stat('/usr/bin/awg'))
|
||||
push(out, {
|
||||
id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', ok: stat('/sys/module/amneziawg') != null,
|
||||
problem: "kernel module isn't loaded", back: 'kernel module is loaded again',
|
||||
detail: () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4"),
|
||||
repair: { what: 'loading it', run: () => system('modprobe amneziawg >/dev/null 2>&1') },
|
||||
});
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.enabled || !srv.private_key)
|
||||
continue;
|
||||
let s = live.iface_status(srv.ifname);
|
||||
let up = !!s?.up;
|
||||
push(out, {
|
||||
id: `up_${id}`, src: 'awg', name: srv.name, who: srv.name, ok: up && ops.udp_listening(srv.port),
|
||||
problem: !s ? 'is missing from the router' : !up ? "isn't running" : `isn't accepting connections on port ${srv.port}`,
|
||||
back: `is running again · accepting connections on port ${srv.port}`,
|
||||
detail: () => iface_errors(srv.ifname),
|
||||
repair: s ? { what: 'restarting it', run: () => system(`ifup ${q(srv.ifname)}`) } : { what: 'setting it up again', run: () => apply.apply() },
|
||||
});
|
||||
}
|
||||
// The tunnels check themselves: AmneziaWG (packages, kernel module, netifd) and each server's interface.
|
||||
push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) }));
|
||||
if (length(m.servers))
|
||||
push(out, {
|
||||
id: 'nft', src: 'dawnline', name: 'Access rules', who: 'Access rules', ok: system('nft list table inet dawnline >/dev/null 2>&1') == 0,
|
||||
id: 'nft', src: 'dawnline', name: 'Access rules', who: 'Access rules', ok: nft.present(),
|
||||
problem: 'are missing', back: 'are loaded again',
|
||||
repair: { what: 'loading them again', run: () => apply.apply() },
|
||||
});
|
||||
@@ -79,15 +57,9 @@ function probes(m) {
|
||||
}
|
||||
|
||||
let s = m.settings;
|
||||
if (s.portal_enabled && core.portal_public_port(m) == 443 && s.portal_port != 443)
|
||||
if (s.portal_enabled && !length(health.needs().https) && !length(health.tcp_port_owners(s.portal_port)))
|
||||
push(out, {
|
||||
id: 'portal_lan', src: 'portal', name: 'Portal at home', who: 'Personal portal', ok: !apply.uhttpd_drift(m),
|
||||
problem: "links don't open at home (LuCI's web server lost the setting)", back: 'links open at home again',
|
||||
repair: { what: 'restoring it', run: () => apply.apply() },
|
||||
});
|
||||
if (s.portal_enabled && !length(ops.needs().https) && !length(ops.tcp_port_owners(s.portal_port)))
|
||||
push(out, {
|
||||
id: 'portal', src: 'portal', name: 'Portal', who: 'Personal portal', ok: ops.tcp_listening(s.portal_port),
|
||||
id: 'portal', src: 'portal', name: 'Portal', who: 'Personal portal', ok: health.tcp_listening(s.portal_port),
|
||||
problem: `isn't answering on port ${s.portal_port}`, back: 'answers again',
|
||||
detail: () => sh_out("logread -l 400 2>/dev/null | grep 'uhttpd' | grep -iE 'error|fail|cert|key|bind|address' | tail -n 4"),
|
||||
repair: { what: 'restarting it', run: restart_services },
|
||||
|
||||
Reference in new issue
Block a user