Build packages / Version (push) Waiting to run
- Find home devices (Bonjour) removed: iOS looks for services over the tunnel only under a search domain, and Android and Chromecast only over multicast, which WireGuard does not carry. Upgrading removes its server option and dnsmasq records - Home services still show the ports devices announce when umdns runs
1349 lines
48 KiB
Plaintext
1349 lines
48 KiB
Plaintext
// 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, rand_hex, lock, unlock, uniq, slog_clear, admin_log, 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';
|
||
import * as watchdog from 'dawnline.watchdog';
|
||
import * as access from 'dawnline.access';
|
||
|
||
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 ---------- */
|
||
|
||
/** 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 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, 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,
|
||
// 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[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),
|
||
circles: values(m.circles),
|
||
totals,
|
||
series: live.series(recs, clamp_days(a.days)),
|
||
events: with_hosts(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');
|
||
let made = core.load().servers[id];
|
||
admin_log('awg', 'created', 'server', made?.name ?? id, made ? `port ${made.port}` : null);
|
||
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,
|
||
device_mesh: srv.device_mesh, mesh: srv.mesh },
|
||
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');
|
||
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('dawnline', srv.id, 'mesh', mesh);
|
||
c.delete('dawnline', srv.id, 'device_mesh');
|
||
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);
|
||
// 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(core.load(c).servers[srv.id]) != sig(srv))
|
||
push(what, 'home network and internet path');
|
||
if (mesh != srv.mesh)
|
||
push(what, { off: 'devices kept apart', all: 'devices reach each other', circles: 'devices reach each other in circles' }[mesh]);
|
||
if (length(what))
|
||
admin_log('awg', 'changed', 'server', srv.name, join(', ', what));
|
||
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.device_mesh != null && v.mesh == null)
|
||
v.mesh = v.device_mesh === true || v.device_mesh == '1' ? 'all' : 'off';
|
||
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) {
|
||
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');
|
||
}
|
||
// For the log: what changed, in words. Turning on or off is its own line.
|
||
let labels = { name: 'name', endpoint: 'public address', port: '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(' ', type(v.dns) == 'array' ? v.dns : split(str(v.dns), /[ ,]+/)) : str(v[k]);
|
||
if (trim(was) != trim(now))
|
||
push(what, label);
|
||
}
|
||
let on = v.enabled == null ? null : (v.enabled === true || v.enabled == '1');
|
||
let mesh = v.mesh;
|
||
let name = v.name != null ? str(v.name) : srv.name;
|
||
let r = commit(c, true);
|
||
if (on != null && on != srv.enabled)
|
||
admin_log('awg', on ? 'turned on' : 'turned off', 'server', name);
|
||
if (length(what))
|
||
admin_log('awg', 'changed', 'server', name, join(', ', what));
|
||
if (mesh != null && mesh != srv.mesh)
|
||
admin_log('awg', 'changed', 'server', name,
|
||
{ off: 'devices kept apart', all: 'devices reach each other', circles: 'devices reach each other in circles' }[mesh]);
|
||
return r;
|
||
}
|
||
|
||
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');
|
||
let r = commit(c, true);
|
||
admin_log('awg', 'changed', 'server', srv.name, `disguise: ${a.preset || 'standard'}`);
|
||
return r;
|
||
}
|
||
|
||
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');
|
||
let gone = 0;
|
||
for (let pid, p in m.people)
|
||
if (p.server == a.id) {
|
||
core.delete_person(c, m, pid);
|
||
gone++;
|
||
}
|
||
c.delete('dawnline', a.id);
|
||
let r = commit(c, true);
|
||
admin_log('awg', 'removed', 'server', m.servers[a.id].name, gone ? `with ${gone} ${gone == 1 ? 'person' : 'people'}` : null);
|
||
return r;
|
||
}
|
||
|
||
/* ---------- 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, by: 'admin' });
|
||
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, 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');
|
||
live.add_event({ type: 'link_changed', person: a.id, by: 'admin' });
|
||
// 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, pname: name, by: 'admin' });
|
||
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', by: 'admin' });
|
||
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, by: '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');
|
||
}
|
||
let r = commit(c);
|
||
if (a.disabled != null && !!a.disabled != !!d.disabled)
|
||
live.add_event({ type: 'device_changed', person: d.person, device: a.id, detail: a.disabled ? 'turned off' : 'turned on', by: 'admin' });
|
||
else if (a.name != null && a.name != d.name)
|
||
live.add_event({ type: 'device_changed', person: d.person, device: a.id, detail: `renamed from ${d.name}`, by: 'admin' });
|
||
return r;
|
||
}
|
||
|
||
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, dname: d?.name, dkind: d?.kind, by: '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);
|
||
live.add_event({ type: 'device_keys', person: m.devices[a.id]?.person, device: a.id, detail: m.devices[a.id]?.name, by: 'admin' });
|
||
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;
|
||
if (a.circle != null)
|
||
fields.circle = a.circle;
|
||
if (type(a.home_nets) == 'array')
|
||
fields.home_nets = a.home_nets;
|
||
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, by: 'admin' }, 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', 'watchdog',
|
||
'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();
|
||
// The changes worth a line: the portal and the watchdog (other settings are housekeeping).
|
||
let now = core.load().settings, was = m.settings;
|
||
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_443 != was.portal_443)
|
||
push(what, now.portal_443 ? 'links without a port' : 'links with the port');
|
||
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({});
|
||
}
|
||
|
||
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 };
|
||
}
|
||
|
||
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
|
||
function circle_set(a) {
|
||
let c = core.open_cursor();
|
||
let m = core.load(c);
|
||
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.');
|
||
let name = trim(`${a.name ?? ''}`);
|
||
if (name == '' || length(name) > 32)
|
||
die('Enter a circle name (up to 32 characters).');
|
||
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 ?? `c_${rand_hex(4)}`;
|
||
c.set('dawnline', id, 'circle');
|
||
c.set('dawnline', id, 'server', server);
|
||
c.set('dawnline', id, 'name', name);
|
||
c.set('dawnline', id, 'color', `${(int(a.color) || 0) % core.CIRCLE_COLORS}`);
|
||
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('dawnline', pid, 'circle', id);
|
||
else if (p.circle == id)
|
||
c.delete('dawnline', pid, 'circle');
|
||
}
|
||
commit(c);
|
||
admin_log('awg', ci ? 'changed' : 'added', 'circle', name, m.servers[server].name);
|
||
return { id, circles: values(core.load().circles) };
|
||
}
|
||
|
||
function circle_delete(a) {
|
||
let c = core.open_cursor();
|
||
let m = core.load(c);
|
||
let ci = m.circles[a.id];
|
||
if (!ci)
|
||
die('Unknown circle.');
|
||
c.delete('dawnline', a.id);
|
||
for (let pid, p in m.people)
|
||
if (p.circle == a.id)
|
||
c.delete('dawnline', pid, 'circle');
|
||
commit(c);
|
||
admin_log('awg', 'removed', 'circle', ci.name, m.servers[ci.server]?.name);
|
||
return { circles: values(core.load().circles) };
|
||
}
|
||
|
||
/**
|
||
* 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 = net.server_net(srv).nets;
|
||
let inside = (ip) => {
|
||
let n = ip2int(ip);
|
||
for (let cidr in nets) {
|
||
let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/);
|
||
let size = 1 << (32 - +x[2]), base = ip2int(x[1]);
|
||
if (n != null && n >= base && n < base + size)
|
||
return true;
|
||
}
|
||
return false;
|
||
};
|
||
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();
|
||
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 ops.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 } ] };
|
||
let out = values(hosts);
|
||
return { hosts: sort(out, (x, y) => ip2int(x.address) - ip2int(y.address)), mdns: ops.mdns_running() };
|
||
}
|
||
|
||
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) {
|
||
// 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 };
|
||
}
|
||
|
||
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, device_mesh: true }, 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(), ...watchdog.view(core.load()) })) },
|
||
health_fix: { args: { id: '' }, call: wrap((a) => ({ result: ops.fix(a.id), checks: ops.health(), ...watchdog.view(core.load()) })) },
|
||
service_log: { call: wrap((a) => watchdog.view(core.load())) },
|
||
service_log_clear: { args: { older_days: '' }, call: wrap((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 };
|
||
}) },
|
||
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) => {
|
||
let r = ops.backup_restore(a.name);
|
||
admin_log('dawnline', 'restored', 'backup', a.name);
|
||
return r;
|
||
}) },
|
||
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) => {
|
||
let r = ops.backup_upload(a.data);
|
||
admin_log('dawnline', 'restored', 'backup', 'from a file');
|
||
return r;
|
||
}) },
|
||
export: { call: wrap((a) => {
|
||
let r = ops.export_json();
|
||
admin_log('dawnline', 'exported', null, 'all settings', 'the file holds private keys');
|
||
return r;
|
||
}) },
|
||
import: { args: { data: {} }, call: wrap((a) => {
|
||
let r = ops.import_json(a.data);
|
||
admin_log('dawnline', 'imported', null, 'settings from a file');
|
||
return r;
|
||
}) },
|
||
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: [], circle: '', home_nets: [] },
|
||
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) },
|
||
circle_set: { args: { id: '', server: '', name: '', color: 0, members: [] }, call: wrap(circle_set) },
|
||
circle_delete: { args: { id: '' }, call: wrap(circle_delete) },
|
||
access_check: { args: { from: '', to: '' }, call: wrap((a) => access.check(core.load(), a.from, a.to)) },
|
||
home_hosts: { args: { id: '' }, call: wrap(home_hosts) },
|
||
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 };
|