Files
dawnline/package/luci-app-dawnline/root/usr/share/rpcd/ucode/luci.dawnline
T
Aemeath d0955e44b8
Build packages / Version (push) Waiting to run
Dawnline 0.1.1
- Fix "Cannot set properties of undefined (setting '_class')" after adding
  a person on a server page: kept Overview/People tabs are taken out before
  dom.content() wipes their LuCI registry
- No portal links while the personal portal is off
- "Off" disguise writes a plain WireGuard config (no neutral Jc..H4 lines)
- Setup wizard: Settings-style groups, portal off by default, "Internet like
  a home device" switch; no "Link path" (server ids are picked by the router)
- Server ids and imported section names may not contain dashes
- Health: Cloudflare-proxied endpoint and portal address are not warnings
- Themes other than Outline: solid menus, drawer, palette, toasts and tooltips
  (Bootstrap colour tokens as fallbacks), custom select chevron
- Server section tabs scroll sideways instead of wrapping; centred empty
  People list; wider search; "1 device" in the palette
- lint-ucode: exported functions must end with "};"
2026-10-15 04:58:28 +03:00

1114 lines
37 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Dawnline — rpcd backend for the LuCI admin UI (ubus object luci.dawnline).
'use strict';
import { cursor } from 'uci';
import { readfile, stat } from 'fs';
import {
q, sh, sh_out, sh_bg, ensure_dir, read_json, write_json, parse_cidr, cidr_str, cidr_overlaps, int2ip,
ip2int, valid_host, rand_int, lock, unlock, uniq, 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 * as ops from 'dawnline.ops';
import * as geo from 'dawnline.geo';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
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}` };
}
};
}
/** Commit the dawnline config and push runtime state. */
function commit(c, full) {
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
return full ? apply.apply() : apply.sync();
}
const METHODS = [ 'off', 'standard', 'strong', 'max' ];
/** A disguise method the installed AmneziaWG can run. */
function check_method(name) {
if (index(METHODS, name) < 0)
die('Unknown disguise method.');
if (name == 'max' && !core.awg_caps().v3)
die('Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1).');
return name;
}
/** Days of history a caller may ask for: 1–400, default 30. */
function clamp_days(v) {
let n = +(v ?? 30);
return n >= 1 ? (n > 400 ? 400 : n) : 30;
}
function str(v) {
return v == null ? '' : trim(`${v}`);
}
/* ---------- map ---------- */
/** 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,
};
}
/* ---------- status ---------- */
function status(a) {
let m = core.load();
let usage = core.load_usage();
let dmp = live.dump();
let states = view.states(m, usage);
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) {
let st = live.iface_status(srv.ifname);
let online = 0, peers = 0;
for (let k, p in dmp.peers)
if (p.ifname == srv.ifname) {
peers++;
if (p.handshake > 0 && time() - p.handshake < live.ONLINE_WINDOW)
online++;
}
push(servers, {
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, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
address: core.server_address(srv), up: !!st?.up, uptime: st?.uptime ?? 0,
peers, online, obf: srv.obf,
// Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices).
rate: rates[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 == id), (pid) => usage.people?.[pid]), clamp_days(a.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_443: s.portal_443, 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),
totals,
series: live.series(recs, clamp_days(a.days)),
events: slice(events, length(events) > 60 ? length(events) - 60 : 0),
like_home: loop.status(),
awg: core.awg_caps(),
};
}
/* ---------- setup ---------- */
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(ops.tcp_port_owners(p)))
return p;
return 9443;
}
function free_ifname(m) {
let nc = cursor();
nc.load('network');
for (let i = 0; i < 10; i++) {
let n = `dawn${i}`;
if (nc.get('network', n) == null && !m.servers[n])
return n;
}
return 'dawnx';
}
/** A free server id: home, then server2, server3, … (never a person, device or service id). */
function free_server_id(m) {
let taken = (id) => m.servers[id] || m.people[id] || m.devices[id] || m.services[id] || index([ 'settings', 'api', 'assets', 'cgi-bin' ], id) >= 0;
if (!taken('home'))
return 'home';
for (let n = 2; ; n++)
if (!taken(`server${n}`))
return `server${n}`;
}
function setup_defaults(a) {
let m = core.load();
let taken = ops.used_subnets(null);
for (let id, s in m.servers)
push(taken, s.subnet);
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 the WAN address.
let dc = cursor();
dc.load('ddns');
dc.foreach('ddns', 'service', (s) => {
if (!host && s.lookup_host && s.enabled == '1')
host = s.lookup_host;
});
if (!host) {
let acme = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1");
if (acme)
host = acme;
}
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: core.awg_caps(),
taken,
};
}
function server_create(a) {
let l = lock('config');
try {
let c = core.open_cursor();
let m = core.load(c);
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 (m.servers[id] || m.people[id] || id == 'settings' || id == 'api' || id == 'assets' || id == 'cgi-bin')
die(`"${id}" is already taken.`);
let nc = cursor();
nc.load('network');
let ifname = str(a.ifname) || free_ifname(m);
if (nc.get('network', ifname) != null)
die(`Network interface ${ifname} already exists.`);
let srv = {
id, ifname, port: +a.port || free_port(m), subnet: str(a.subnet), endpoint: str(a.endpoint),
obf: core.obf_preset(check_method(a.preset || 'standard')),
};
let pc = parse_cidr(srv.subnet);
if (pc)
srv.subnet = cidr_str(pc);
let taken = ops.used_subnets(null);
for (let k, s in m.servers)
push(taken, s.subnet);
let errs = core.server_errors(m, srv, taken);
if (length(errs))
die(join(' ', errs));
let priv = core.genkey(), pub = core.pubkey(priv);
if (!pub)
die('Key generation failed (is amneziawg-tools installed?).');
c.set('dawnline', 'settings', 'settings');
c.set('dawnline', id, 'server');
c.set('dawnline', id, 'name', str(a.name) || 'Home');
c.set('dawnline', id, 'ifname', ifname);
c.set('dawnline', id, 'port', `${srv.port}`);
c.set('dawnline', id, 'subnet', srv.subnet);
if (srv.endpoint)
c.set('dawnline', id, 'endpoint', srv.endpoint);
c.set('dawnline', id, 'mtu', `${+a.mtu || 1380}`);
c.set('dawnline', id, 'keepalive', '25');
c.set('dawnline', id, 'private_key', priv);
c.set('dawnline', id, 'public_key', pub);
c.set('dawnline', id, 'preset', a.preset ?? 'standard');
for (let k, v in srv.obf)
c.set('dawnline', id, k, v);
c.set('dawnline', id, 'lan_zone', str(a.lan_zone) || 'lan');
c.set('dawnline', id, 'wan_zone', str(a.wan_zone) || 'wan');
let snap = net.snapshot(true);
c.set('dawnline', id, 'auto_wan', '1');
c.set('dawnline', id, 'auto_lan', '1');
if (snap.wan)
c.set('dawnline', id, 'detected_wan', snap.wan);
if (snap.lan)
c.set('dawnline', id, 'detected_lan', snap.lan);
c.set('dawnline', id, 'lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
c.set('dawnline', id, 'enabled', '1');
if (a.portal_enabled != null) {
c.set('dawnline', 'settings', 'portal_enabled', a.portal_enabled ? '1' : '0');
let pp = +a.portal_port;
if (a.portal_enabled && (pp < 1 || pp > 65535))
die('Portal port must be 1-65535.');
if (a.portal_enabled && length(ops.tcp_port_owners(pp)))
die(`TCP ${pp} is already used by ${join(', ', ops.tcp_port_owners(pp))}. Choose another portal port.`);
if (pp)
c.set('dawnline', 'settings', 'portal_port', `${pp}`);
}
if (srv.endpoint && !c.get('dawnline', 'settings', 'portal_host') && valid_host(srv.endpoint))
c.set('dawnline', 'settings', 'portal_host', srv.endpoint);
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
unlock(l);
l = null;
let r = apply.apply();
system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable');
sh_bg('/etc/init.d/dawnline restart');
return { id, applied: r };
}
catch (e) {
if (l)
unlock(l);
die(e.message);
}
}
/** Interfaces card on the Server page: what exists, what is detected, what the server uses. */
function interfaces_view(srv, snap) {
let sn = net.server_net(srv, snap);
let home = {};
for (let h in sn.home)
home[h.dev] = h;
let devices = [];
for (let dev, d in snap.devices)
push(devices, {
...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(devices, { 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 core.load().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 },
like_home: loop.status(),
needs: ops.needs().home,
effective: sn,
zones: snap.zones,
devices,
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(srv, net.snapshot(true));
}
function server_interfaces(a) {
let c = core.open_cursor();
let m = core.load(c);
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
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 = trim(`${a.wan_device ?? ''}`);
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 = trim(`${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);
if (a.lan_like != null)
c.set('dawnline', srv.id, 'lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
c.set('dawnline', srv.id, 'auto_wan', auto_wan ? '1' : '0');
c.set('dawnline', srv.id, 'auto_lan', auto_lan ? '1' : '0');
if (auto_wan || wan_dev == '')
c.delete('dawnline', srv.id, 'wan_device');
else
c.set('dawnline', srv.id, 'wan_device', wan_dev);
if (length(lans))
c.set('dawnline', srv.id, 'lan_device', lans);
else
c.delete('dawnline', srv.id, 'lan_device');
// Remember what was detected, as the fallback while an interface is down.
if (snap.wan)
c.set('dawnline', srv.id, 'detected_wan', snap.wan);
if (snap.lan)
c.set('dawnline', srv.id, 'detected_lan', snap.lan);
// Keep the legacy zone options in step (older code paths, health checks).
let m2 = core.load(c);
let sn = net.server_net(m2.servers[srv.id], snap);
if (sn.wan.zone)
c.set('dawnline', srv.id, 'wan_zone', sn.wan.zone);
if (length(sn.zones))
c.set('dawnline', srv.id, 'lan_zone', sn.zones[0]);
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
let before = join(',', net.server_net(srv, snap).nets);
apply.apply();
let m3 = core.load();
let view = interfaces_view(m3.servers[srv.id], net.snapshot(true));
view.nets_changed = before != join(',', view.effective.nets);
return view;
}
/** Server settings from the General and Network tabs; applied at once. */
function server_update(a) {
let c = core.open_cursor();
let m = core.load(c);
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
let v = a.values ?? {};
let set = (k, val) => (val == null || val == '') ? c.delete('dawnline', srv.id, k) : c.set('dawnline', 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) {
let n = +v.port;
if (!match(str(v.port), /^[0-9]+$/) || n < 1 || n > 65535)
die('UDP port must be 1-65535.');
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.mtu != null) {
if (str(v.mtu) != '' && (!match(str(v.mtu), /^[0-9]+$/) || +v.mtu < 1280 || +v.mtu > 1500))
die('MTU must be 1280-1500.');
set('mtu', str(v.mtu));
}
if (v.keepalive != null) {
if (str(v.keepalive) != '' && (!match(str(v.keepalive), /^[0-9]+$/) || +v.keepalive > 600))
die('Keep-alive must be 0-600 seconds.');
set('keepalive', str(v.keepalive));
}
if (v.dns != null) {
let list = filter(map(type(v.dns) == 'array' ? v.dns : split(str(v.dns), /[ ,]+/), str), (x) => x != '');
for (let d in list)
if (!match(d, /^[0-9]{1,3}(\.[0-9]{1,3}){3}$/) && !match(d, /^[0-9a-fA-F:]+$/))
die(`${d} is not an IP address.`);
if (length(list))
c.set('dawnline', srv.id, 'dns', list);
else
c.delete('dawnline', srv.id, 'dns');
}
return commit(c, true);
}
function server_obfuscation(a) {
let c = core.open_cursor();
let m = core.load(c);
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
let o = core.obf_preset(check_method(a.preset || 'standard'));
for (let k in core.OBF_KEYS)
c.delete('dawnline', a.id, k);
for (let k, v in o)
c.set('dawnline', a.id, k, v);
c.set('dawnline', a.id, 'preset', a.preset ?? 'standard');
return commit(c, true);
}
function server_delete(a) {
let c = core.open_cursor();
let m = core.load(c);
if (!m.servers[a.id])
die('Unknown server.');
ops.backup_create('pre-delete');
for (let pid, p in m.people)
if (p.server == a.id)
core.delete_person(c, m, pid);
c.delete('dawnline', a.id);
return commit(c, true);
}
/* ---------- people ---------- */
function person_create(a) {
let l = lock('config');
try {
let c = core.open_cursor();
let m = core.load(c);
let slug = core.create_person(c, m, {
name: str(a.name), slug: str(a.slug) || null, server: str(a.server) || null, access: a.access,
device_limit: a.device_limit, expires: str(a.expires), quota_gb: a.quota_gb, quota_period: a.quota_period,
});
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
unlock(l);
l = null;
let m2 = core.load();
live.add_event({ type: 'person_added', person: slug, detail: m2.people[slug].name });
return { id: slug, link: core.portal_url(m2, m2.people[slug]) };
}
catch (e) {
if (l)
unlock(l);
die(e.message);
}
}
function person_pause(a) {
let c = core.open_cursor();
let m = core.load(c);
let p = m.people[a.id];
if (!p)
die('Unknown person.');
if (a.paused)
c.set('dawnline', a.id, 'paused', '1');
else
c.delete('dawnline', a.id, 'paused');
live.add_event({ type: a.paused ? 'paused' : 'resumed', person: a.id, detail: 'by admin' });
return commit(c);
}
function person_regen(a) {
let c = core.open_cursor();
let m = core.load(c);
let p = m.people[a.id];
if (!p)
die('Unknown person.');
c.set('dawnline', a.id, 'code', core.new_code());
c.commit('dawnline');
// The old link stops working at once: every portal request carries the code.
let m2 = core.load();
return { link: core.portal_url(m2, m2.people[a.id]) };
}
function person_delete(a) {
let c = core.open_cursor();
let m = core.load(c);
let name = m.people[a.id]?.name;
core.delete_person(c, m, a.id);
live.add_event({ type: 'person_removed', person: a.id, detail: name });
return commit(c);
}
function pause_all(a) {
let c = core.open_cursor();
c.set('dawnline', 'settings', 'settings');
c.set('dawnline', 'settings', 'paused_all', a.paused ? '1' : '0');
live.add_event({ type: a.paused ? 'paused_all' : 'resumed_all' });
return commit(c);
}
/* ---------- devices ---------- */
function device_create(a) {
let l = lock('config');
try {
let c = core.open_cursor();
let m = core.load(c);
let id = core.create_device(c, m, a.person, a.name, a.kind, { by: 'admin', force: true });
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
unlock(l);
l = null;
apply.sync();
live.add_event({ type: 'device_added', person: a.person, device: id, detail: `${a.name} (admin)` });
let m2 = core.load();
core.mark_issued(m2, id);
return { id, config: core.client_config(m2, m2.devices[id]) };
}
catch (e) {
if (l)
unlock(l);
die(e.message);
}
}
function device_config(a) {
let m = core.load();
let d = m.devices[a.id];
if (!d)
die('Unknown device.');
core.mark_issued(m, d.id);
return core.client_config(m, d);
}
function device_update(a) {
let c = core.open_cursor();
let m = core.load(c);
let d = m.devices[a.id];
if (!d)
die('Unknown device.');
if (a.name != null && a.name != d.name)
core.rename_device(c, m, a.id, a.name);
if (a.disabled != null) {
if (a.disabled)
c.set('dawnline', a.id, 'disabled', '1');
else
c.delete('dawnline', a.id, 'disabled');
}
return commit(c);
}
function device_delete(a) {
let c = core.open_cursor();
let m = core.load(c);
let d = m.devices[a.id];
core.delete_device(c, m, a.id);
live.add_event({ type: 'device_removed', person: d?.person, device: a.id, detail: `${d?.name} (admin)` });
return commit(c);
}
function device_rotate(a) {
let c = core.open_cursor();
let m = core.load(c);
core.rotate_device(c, m, a.id);
commit(c);
let m2 = core.load();
core.mark_issued(m2, a.id);
return core.client_config(m2, m2.devices[a.id]);
}
/* ---------- misc ---------- */
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 devs = {};
for (let d in p.devices)
devs[d] = live.series([ usage.devices?.[d] ], clamp_days(a.days));
return { person: live.series([ usage.people?.[a.id] ], clamp_days(a.days)), devices: devs };
}
function updates_status(a) {
let m = core.load();
let rel = {};
for (let line in split(readfile('/etc/openwrt_release') ?? '', '\n')) {
let m = match(line, /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/);
if (m)
rel[lc(m[1])] = m[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: ops.needs(),
check: read_json(`${RUN_DIR}/update-check.json`, null),
job: read_json(`${RUN_DIR}/update-job.json`, null),
};
}
function updates_run(a) {
let what = a.what ?? 'check';
// check | app | all | amneziawg[:slava|grey[:ru]] | pkgs:<name,…> (the updater checks names against its list)
if (length(what) > 400 || !match(what, /^(check|app|all|amneziawg(:(slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/))
die('Unknown update target.');
let job = read_json(`${RUN_DIR}/update-job.json`, null);
if (job?.state == 'running' && time() - (job.started ?? 0) < 600)
die('An update is already running.');
ensure_dir(RUN_DIR);
system(`start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${what == 'check' ? 'check' : 'install ' + what}`);
return { started: true };
}
/* ---------- immediate edits ---------- */
function person_update(a) {
let l = lock('config');
try {
let c = core.open_cursor();
let m = core.load(c);
let fields = {};
for (let k in [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period',
'bonus_gb', 'hours', 'note', 'dns_mode' ])
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;
let before = m.people[a.id];
core.update_person(c, m, a.id, fields);
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
unlock(l);
l = null;
let changes = join(', ', filter(keys(fields), (k) => k != 'note'));
if (changes)
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes }, 120);
// Access changes affect the nft sets and client AllowedIPs.
apply.sync();
let m2 = core.load();
let u = core.load_usage();
return { person: view.person_view(m2, m2.people[a.id], u, live.dump(), view.states(m2, u), { admin: true }), was: before?.access };
}
catch (e) {
if (l)
unlock(l);
die(e.message);
}
}
const SETTING_KEYS = [ 'portal_enabled', 'portal_host', 'portal_alt', 'portal_port', 'portal_443', 'portal_title', 'portal_redirect', 'portal_cert', 'portal_key',
'default_device_limit', 'hostnames', 'domain', 'geo_enabled', 'geo_provider', 'log_connections',
'log_keep_days', 'log_max', 'log_persist', 'usage_keep_days', 'usage_keep_months', 'home_dns_fallback' ];
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 pol = live.policy(m.settings.retention);
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: pol,
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('dawnline', 'settings') ?? {};
let m = core.load(c);
let out = {};
for (let k in SETTING_KEYS)
out[k] = raw[k] ?? '';
out.log_category = live.policy(m.settings.retention).categories;
let cert = m.settings.portal_enabled ? ops.portal_cert(m.settings) : null;
return {
settings: out,
needs: ops.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 ? [] : ops.tcp_port_owners(m.settings.portal_port),
wan443_taken: core.wan443_taken(),
portal_public_port: core.portal_public_port(m),
portal_candidates: ops.portal_candidates(m),
// The portal's own checks from Health, shown next to its settings.
portal_checks: filter(ops.health(m), (x) => index([ 'portal', 'portal_dns', 'portal_reply', 'portal_443', 'portal_lan', 'portal_http', 'cert' ], x.id) >= 0),
geo_cached: length(keys(geo.load().ips)),
logs: logs_info(m),
};
}
function settings_update(a) {
let c = core.open_cursor();
let m = core.load(c);
let v = a.values ?? {};
let restart = false;
c.set('dawnline', 'settings', 'settings');
for (let k, val in v) {
if (index(SETTING_KEYS, k) < 0 && k != 'log_category')
die(`Unknown setting ${k}.`);
if (k == 'log_category') {
let lst = filter(type(val) == 'array' ? val : [], (x) => index(live.CATEGORIES, x) >= 0);
c.set('dawnline', 'settings', 'log_category', length(lst) ? lst : [ '' ]);
// Superseded by the category list.
c.delete('dawnline', 'settings', 'log_connections');
continue;
}
if (k == 'portal_alt') {
let lst = uniq(filter(type(val) == 'array' ? val : [], (x) => type(x) == 'string' && valid_host(x)));
if (join(' ', lst) != join(' ', m.settings.portal_alt))
restart = true;
if (length(lst))
c.set('dawnline', 'settings', 'portal_alt', lst);
else
c.delete('dawnline', 'settings', 'portal_alt');
continue;
}
val = trim(`${val ?? ''}`);
if (k == 'portal_port' && val != '') {
let n = +val;
if (n < 1 || n > 65535 || index([ 22, 53, 80, 443 ], n) >= 0)
die('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).');
if (n != m.settings.portal_port && length(ops.tcp_port_owners(n)))
die(`TCP ${n} is already used by ${join(', ', ops.tcp_port_owners(n))}.`);
}
if (k == 'portal_redirect' && val != '' && (length(val) > 300 || !match(val, /^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^[:space:]"'<>]*)?$/)))
die('Redirect must be a full http:// or https:// address.');
if (k == 'portal_host' && val != '' && !valid_host(val))
die('Public address must be a hostname or IP address.');
if (k == 'default_device_limit' && val != '' && (+val < 1 || +val > 32))
die('Default device limit must be 1-32.');
if (k == 'domain' && val != '' && !match(val, /^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/))
die('Domain may use lowercase letters, digits, dashes and dots.');
if ((k == 'portal_cert' || k == 'portal_key') && val != '' && !stat(val))
die(`${val} does not exist.`);
if (k == 'home_dns_fallback') {
if (val != '' && !match(val, /^[0-9]{1,3}(\.[0-9]{1,3}){3}$/))
die('Fallback DNS must be an IPv4 address (or empty for none).');
// Empty means "no fallback"; an unset option means the default.
if (val == '')
val = 'none';
}
if (k == 'log_keep_days' && val != '' && !match(val, /^(0|[1-9][0-9]{0,3})$/))
die('Keep activity for 0 (no age limit) to 9999 days.');
if (k == 'log_max' && val != '' && (!match(val, /^[0-9]+$/) || +val < 100 || +val > 20000))
die('Log size must be 100-20000 events.');
if (k == 'log_persist' && val != '' && index([ '10min', 'hourly', 'off' ], val) < 0)
die('Save the log every 10min, hourly or off.');
if (k == 'usage_keep_days' && val != '' && (!match(val, /^[0-9]+$/) || +val < 7 || +val > 1830))
die('Daily traffic history must be 7-1830 days.');
if (k == 'usage_keep_months' && val != '' && (!match(val, /^[0-9]+$/) || +val < 1 || +val > 120))
die('Monthly traffic history must be 1-120 months.');
if (index([ 'portal_enabled', 'portal_port', 'portal_443', 'portal_cert', 'portal_key', 'portal_host' ], k) >= 0 && val != (c.get('dawnline', 'settings', k) ?? ''))
restart = true;
if (val == '')
c.delete('dawnline', 'settings', k);
else
c.set('dawnline', 'settings', k, val);
}
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
if (restart)
system('/etc/init.d/dawnline reload >/dev/null 2>&1');
else
apply.sync();
return settings_get({});
}
function service_set(a) {
let c = core.open_cursor();
let id = a.id || `svc_${rand_int(100000, 999999)}`;
if (!match(id, /^[A-Za-z0-9_]{1,32}$/))
die('Invalid service id.');
// Never turn a person, server or the settings into a service.
let existing = c.get('dawnline', id);
if (existing != null && existing != 'service')
die('That id is taken.');
if (!a.name || length(a.name) > 48)
die('Enter a service name.');
if (ip2int(a.address ?? '') == null)
die('Address must be an IPv4 address.');
let ports = filter(map(type(a.ports) == 'array' ? a.ports : split(`${a.ports ?? ''}`, /[ ,]+/), (x) => trim(`${x}`)), (x) => x != '');
for (let pt in ports)
if (!match(pt, /^[0-9]+$/) || +pt < 1 || +pt > 65535)
die(`Invalid port ${pt}.`);
c.set('dawnline', id, 'service');
c.set('dawnline', id, 'name', trim(a.name));
c.set('dawnline', id, 'address', a.address);
if (length(ports))
c.set('dawnline', id, 'port', ports);
else
c.delete('dawnline', id, 'port');
commit(c);
return { id };
}
function service_delete(a) {
let c = core.open_cursor();
if (c.get('dawnline', a.id) != 'service')
die('Unknown service.');
c.delete('dawnline', a.id);
c.foreach('dawnline', 'person', (p) => {
if (type(p.service) == 'array' && index(p.service, a.id) >= 0) {
let rest = filter(p.service, (x) => x != a.id);
if (length(rest))
c.set('dawnline', p['.name'], 'service', rest);
else
c.delete('dawnline', p['.name'], 'service');
}
});
commit(c);
return { ok: true };
}
function events_list(a) {
let ev = live.load_events();
let n = +a.limit || 300;
return { events: 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;
}
return { ok: true, removed: live.clear_events(f) };
}
/**
* 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);
}
return { ok: true };
}
function uninstall(a) {
if (a.confirm != 'remove')
die('Type "remove" to confirm.');
ops.backup_create('pre-remove');
apply.teardown();
system('/etc/init.d/dawnline stop >/dev/null 2>&1; /etc/init.d/dawnline disable >/dev/null 2>&1');
let c = core.open_cursor();
let rm = [];
c.foreach('dawnline', null, (s) => {
if (s['.type'] != 'settings')
push(rm, s['.name']);
});
for (let n in rm)
c.delete('dawnline', n);
c.set('dawnline', 'settings', 'portal_enabled', '0');
c.commit('dawnline');
return { ok: true };
}
const methods = {
status: { args: { days: 30 }, call: wrap(status) },
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 }, call: wrap(server_interfaces) },
server_delete: { args: { id: '' }, call: wrap(server_delete) },
person_create: {
args: { name: '', slug: '', server: '', access: '', device_limit: 0, expires: '', quota_gb: 0, quota_period: '' },
call: wrap(person_create),
},
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
person_regen: { args: { id: '' }, call: wrap(person_regen) },
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(device_delete) },
device_rotate: { args: { id: '' }, call: wrap(device_rotate) },
apply: { call: wrap((a) => apply.apply()) },
health: { call: wrap((a) => ({ checks: ops.health() })) },
health_fix: { args: { id: '' }, call: wrap((a) => ({ result: ops.fix(a.id), checks: ops.health() })) },
backup_list: { call: wrap((a) => ({ backups: ops.backup_list() })) },
backup_create: { call: wrap((a) => ({ name: ops.backup_create(null) })) },
backup_restore: { args: { name: '' }, call: wrap((a) => ops.backup_restore(a.name)) },
backup_delete: { args: { name: '' }, call: wrap((a) => ({ ok: ops.backup_delete(a.name) })) },
backup_read: { args: { name: '' }, call: wrap((a) => ({ data: ops.backup_read(a.name) })) },
backup_upload: { args: { data: '' }, call: wrap((a) => ops.backup_upload(a.data)) },
export: { call: wrap((a) => ops.export_json()) },
import: { args: { data: {} }, call: wrap((a) => ops.import_json(a.data)) },
updates_status: { call: wrap(updates_status) },
updates_run: { args: { what: '' }, call: wrap(updates_run) },
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: [] },
call: wrap(person_update),
},
settings_get: { call: wrap(settings_get) },
settings_update: { args: { values: {} }, call: wrap(settings_update) },
service_set: { args: { id: '', name: '', address: '', ports: [] }, call: wrap(service_set) },
service_delete: { args: { id: '' }, call: wrap(service_delete) },
geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) },
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) },
uninstall: { args: { confirm: '' }, call: wrap(uninstall) },
};
return { 'luci.dawnline': methods };