Files
dawnline/package/luci-app-dawnline/root/usr/libexec/dawnline/updater
T
Aemeath 34293fb8e5
Build packages / Version (push) Canceled after 0s
Build packages / Build apk (push) Canceled after 0s
Build packages / Build ipk (push) Canceled after 0s
Build packages / Release (push) Canceled after 0s
Dawnline 0.4.0
- 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
2026-10-16 02:14:15 +03:00

316 lines
10 KiB
Plaintext
Executable File

#!/usr/bin/ucode
// Dawnline background update worker, started detached by luci.dawnline and
// by the agent (automatic runs).
//
// 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)
//
// 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 { 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 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 = {
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() {
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) > 400)
splice(job.log, 0, length(job.log) - 400);
save();
}
function phase(p) {
job.phase = p;
log(p);
}
/** 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') ?? '';
let r = { code: p.close(), out };
for (let line in split(trim(out), '\n'))
if (length(trim(line)))
log(` ${line}`);
return r;
}
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 ?? {};
}
/** 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);
}
/** 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;
}
function run_checks(which) {
let res = {};
for (let name in which) {
phase(`Checking ${WHO[name]}`);
try {
res[name] = CHECKS[name](ctx);
}
catch (e) {
log(`Error: ${e.message}`);
res[name] = { error: e.message, status: '' };
}
}
save_check(res);
return res;
}
/** 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;
}
/* ---------- 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 } });
}
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;
}
}
/** 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
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 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 ---------- */
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 (!LOCK)
exit(0);
fs.mkdir(ctx.work, 0o700);
save();
try {
if (job.action == 'check') {
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 [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}`);
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 });
}
system(`rm -rf '${ctx.work}'`);
job.finished = time();
delete job.current;
save();
restarts();