clavarium 0.2.18 → 0.2.19-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -35,6 +35,11 @@
35
35
  # it is read from /etc/clavarium/host.conf, which root owns.
36
36
  # --mnt DIR where the shared folders live ($MNT, see below); the same
37
37
  # rule: --say-only only, else MNT= in host.conf.
38
+ # --test DIR for the tests of the Wi-Fi verbs, which must run to be tried:
39
+ # run for real, with DIR as the data directory, Wi-Fi's record
40
+ # and NetworkManager's connection files, and waits of seconds instead of a minute. REFUSED AS
41
+ # ROOT: run by a plain account it can do nothing that account
42
+ # could not do already, and under sudo it is never honoured.
38
43
  #
39
44
  # WHY THE SHARED FOLDERS ARE NOT IN THE DATA DIRECTORY. The data directory
40
45
  # belongs to the server's account, so a compromised server could rename any
@@ -96,16 +101,31 @@ CODE="/opt/clavarium"
96
101
  UPDATER_NODE="$CODE/current/node/bin/node"
97
102
  UPDATER="$CODE/current/app/deploy/updater.mjs"
98
103
  UPDATE_STATE="/var/lib/clavarium/update"
104
+ # WI-FI (verbs "wifi ..."): root's record of the last switch, read back by
105
+ # "wifi status"; the unit a switch runs in; how long a new network has to
106
+ # give a working one before the switch goes back, how long one activation may
107
+ # take, and how often it is looked at meanwhile (seconds).
108
+ WIFI_STATE="/var/lib/clavarium/wifi"
109
+ WIFI_UNIT="clavarium-wifi-join"
110
+ WIFI_WAIT="60"
111
+ WIFI_UP_WAIT="45"
112
+ WIFI_STEP="3"
113
+ # Where NetworkManager keeps its connections as files (keyfiles): a new network is written
114
+ # there by this program, root's and 0600 -- the one place its password is ever written.
115
+ NM_KEYFILES="/etc/NetworkManager/system-connections"
99
116
 
100
117
  refuse() { echo "REFUSED: $*" >&2; exit 78; }
101
- usage() { echo "usage: clavarium-host [--say-only [--data DIR] [--mnt DIR]] <vm|shelf|folder|work|view|tools|mounts|operator|machines|disks|net|git|server|update> <verb> [arguments]" >&2; exit 64; }
118
+ usage() { echo "usage: clavarium-host [--say-only [--data DIR] [--mnt DIR]] <vm|shelf|folder|work|view|tools|mounts|operator|machines|disks|net|git|server|update|wifi> <verb> [arguments]" >&2; exit 64; }
102
119
 
103
- SAY="no"; DATA=""; MNT=""
120
+ SAY="no"; DATA=""; MNT=""; TEST=""
104
121
  while [ $# -gt 0 ]; do
105
122
  case "$1" in
106
123
  --say-only) SAY="yes"; shift ;;
107
124
  --data) [ "$SAY" = "yes" ] || refuse "--data is only for --say-only"; DATA="${2:-}"; shift 2 ;;
108
125
  --mnt) [ "$SAY" = "yes" ] || refuse "--mnt is only for --say-only"; MNT="${2:-}"; shift 2 ;;
126
+ --test) [ "$(id -u)" != "0" ] || refuse "--test is never for root"; [ "$SAY" = "no" ] || refuse "--test runs for real: not with --say-only"
127
+ TEST="${2:-}"; case "$TEST" in /*) : ;; *) refuse "--test takes an absolute path" ;; esac
128
+ DATA="$TEST"; MNT="$TEST"; WIFI_STATE="$TEST/wifi"; NM_KEYFILES="$TEST/system-connections"; WIFI_WAIT="3"; WIFI_UP_WAIT="3"; WIFI_STEP="0.2"; shift 2 ;;
109
129
  *) break ;;
110
130
  esac
111
131
  done
@@ -286,6 +306,166 @@ unit_code() {
286
306
  esac
287
307
  }
288
308
 
309
+ # WI-FI: the networks THIS SERVER sees, through NetworkManager (nmcli). The
310
+ # server is often reached from afar over that very Wi-Fi, so a switch that
311
+ # does not work must never leave it cut off: a switch runs as root in a unit
312
+ # of its own (it outlives the page, the request and the server's own network
313
+ # going away), and goes back to the connection it left when the new one gives
314
+ # no working network within $WIFI_WAIT seconds. The new network is saved with
315
+ # autoconnect off until it has worked: a reboot in the middle comes back on
316
+ # the old one. A password comes on standard input only (an argument shows in
317
+ # ps to everyone) and goes to nmcli only; it is never printed, never recorded.
318
+ #
319
+ # nmcli under LC_ALL=C writes a '?' for every character outside ASCII ("Café" came
320
+ # out "Caf?", and could then not be joined: found on a real NetworkManager). Its
321
+ # words stay English and its format the same under C.UTF-8; the names stay whole.
322
+ nmcli() { LC_ALL=C.UTF-8 command nmcli "$@"; }
323
+ # One line of `nmcli -t` cut into FIELDS: ':' separates, and '\' makes the
324
+ # next character plain (nmcli writes a ':' or a '\' inside a value as '\:'
325
+ # and '\\': an SSID may hold either).
326
+ terse_fields() {
327
+ local line="$1" field="" c i
328
+ FIELDS=()
329
+ for ((i = 0; i < ${#line}; i++)); do
330
+ c="${line:i:1}"
331
+ if [ "$c" = '\' ] && [ $((i + 1)) -lt ${#line} ]; then i=$((i + 1)); field+="${line:i:1}"
332
+ elif [ "$c" = ':' ]; then FIELDS+=("$field"); field=""
333
+ else field+="$c"; fi
334
+ done
335
+ FIELDS+=("$field")
336
+ }
337
+ # A network's name as this program takes it: 1 to 32 bytes (LC_ALL=C: ${#} counts
338
+ # bytes, so a name in any script is measured as the radio does), no control
339
+ # character (it is one line everywhere it goes).
340
+ is_ssid() { [ "${#1}" -ge 1 ] && [ "${#1}" -le 32 ] && [[ "$1" != *[[:cntrl:]]* ]]; }
341
+ is_uuid() { [[ "${1:-}" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ ]]; }
342
+ # What nmcli says of a network's protection, in one word: open, wpa (a password,
343
+ # WPA2 or older, or WPA3 alongside), wpa3 (WPA3 only), and what cannot be joined
344
+ # with a password alone here: wep, enterprise (a user and a certificate), other.
345
+ security_of() {
346
+ case "$1" in
347
+ ""|"--") echo open ;;
348
+ *802.1X*) echo enterprise ;;
349
+ *WEP*) echo wep ;;
350
+ *WPA1*|*WPA2*) echo wpa ;;
351
+ *WPA3*) echo wpa3 ;;
352
+ *WPA*) echo wpa ;;
353
+ *) echo other ;;
354
+ esac
355
+ }
356
+ # The Wi-Fi device NetworkManager has, and its state: "<device> <state>", or nothing.
357
+ wifi_device() {
358
+ local out line
359
+ out="$(nmcli -t -f DEVICE,TYPE,STATE device status 2>/dev/null || true)"
360
+ while IFS= read -r line; do
361
+ terse_fields "$line"
362
+ [ "${FIELDS[1]:-}" = "wifi" ] && [[ "${FIELDS[0]}" =~ ^[A-Za-z0-9._-]{1,15}$ ]] || continue
363
+ printf '%s %s\n' "${FIELDS[0]}" "${FIELDS[2]:-unknown}"; return 0
364
+ done <<< "$out"
365
+ return 0
366
+ }
367
+ # The networks in sight on <device>, one per name (its strongest): "<signal> <security> <now|other> <ssid>",
368
+ # the strongest first. <rescan>: yes (a fresh look, a few seconds) or no (what NetworkManager saw last).
369
+ wifi_seen() {
370
+ local out line ssid signal sec now
371
+ declare -A best=() how=() inuse=()
372
+ out="$(nmcli -t -f IN-USE,SSID,SIGNAL,SECURITY device wifi list ifname "$1" --rescan "$2" 2>/dev/null)" \
373
+ || out="$(nmcli -t -f IN-USE,SSID,SIGNAL,SECURITY device wifi list ifname "$1" --rescan no 2>/dev/null)" \
374
+ || return 1
375
+ while IFS= read -r line; do
376
+ [ -n "$line" ] || continue
377
+ terse_fields "$line"
378
+ [ "${#FIELDS[@]}" -eq 4 ] || continue
379
+ now="${FIELDS[0]}"; ssid="${FIELDS[1]}"; signal="${FIELDS[2]}"; sec="$(security_of "${FIELDS[3]}")"
380
+ # A hidden network has no name to show (nmcli writes it empty, or "--").
381
+ [ "$ssid" != "--" ] && is_ssid "$ssid" && [[ "$signal" =~ ^[0-9]{1,3}$ ]] && [ "$signal" -le 100 ] || continue
382
+ [ "$now" = "*" ] && inuse["$ssid"]=1
383
+ if [ -z "${best["$ssid"]:-}" ] || [ "$signal" -gt "${best["$ssid"]}" ]; then best["$ssid"]="$signal"; how["$ssid"]="$sec"; fi
384
+ done <<< "$out"
385
+ for ssid in "${!best[@]}"; do
386
+ if [ -n "${inuse["$ssid"]:-}" ]; then now="now"; else now="other"; fi
387
+ printf '%s %s %s %s\n' "${best["$ssid"]}" "${how["$ssid"]}" "$now" "$ssid"
388
+ done | sort -k1,1nr -k4
389
+ }
390
+ # The Wi-Fi networks NetworkManager keeps: "<uuid> <ssid>", one per profile.
391
+ wifi_saved() {
392
+ local out line u s
393
+ out="$(nmcli -t -f UUID,TYPE connection show 2>/dev/null || true)"
394
+ while IFS= read -r line; do
395
+ terse_fields "$line"
396
+ u="${FIELDS[0]:-}"
397
+ case "${FIELDS[1]:-}" in 802-11-wireless|wifi) : ;; *) continue ;; esac
398
+ is_uuid "$u" || continue
399
+ # One value, asked unescaped: it is the whole of what is printed. (Its input is not
400
+ # the loop's: nothing it reads may eat the lines still to come.)
401
+ s="$(nmcli -e no -g 802-11-wireless.ssid connection show uuid "$u" 2>/dev/null < /dev/null || true)"
402
+ is_ssid "$s" && printf '%s %s\n' "$u" "$s"
403
+ done <<< "$out"
404
+ return 0
405
+ }
406
+ # The uuid of the connection active on <device> (nothing when none), and every active one.
407
+ wifi_active_on() {
408
+ local out line
409
+ out="$(nmcli -t -f UUID,DEVICE connection show --active 2>/dev/null || true)"
410
+ while IFS= read -r line; do
411
+ terse_fields "$line"
412
+ [ "${FIELDS[1]:-}" = "$1" ] && is_uuid "${FIELDS[0]}" && { echo "${FIELDS[0]}"; return 0; }
413
+ done <<< "$out"
414
+ return 0
415
+ }
416
+ wifi_active_all() { nmcli -t -f UUID connection show --active 2>/dev/null | grep -E '^[0-9a-f-]{36}$' || true; }
417
+ # A working network through <device>: NetworkManager's own check says "full".
418
+ # When it does not check here (no check configured: "unknown"), the gateway of
419
+ # the Wi-Fi device answering will do.
420
+ wifi_online() {
421
+ local c gw
422
+ c="$(nmcli networking connectivity check 2>/dev/null || true)"
423
+ case "$c" in full) return 0 ;; limited|portal|none) return 1 ;; esac
424
+ gw="$(nmcli -g IP4.GATEWAY device show "$1" 2>/dev/null | head -1 || true)"
425
+ [[ "$gw" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || return 1
426
+ ping -c 1 -W 2 -I "$1" "$gw" >/dev/null 2>&1
427
+ }
428
+ # The last switch, as recorded: its first word (joining, joined, went-back...), or nothing.
429
+ wifi_last_word() { sed -n 's/^last \([a-z-]*\) [0-9]*$/\1/p' "$WIFI_STATE/last" 2>/dev/null | head -1 || true; }
430
+ # A switch is going on: recorded as such, and recently (a reboot in its middle
431
+ # leaves "joining" behind; it is not believed for ever).
432
+ wifi_busy() {
433
+ local at
434
+ [ "$(wifi_last_word)" = "joining" ] || return 1
435
+ at="$(sed -n 's/^last joining \([0-9]*\)$/\1/p' "$WIFI_STATE/last" | head -1)"
436
+ [ $(( $(date +%s) - ${at:-0} )) -lt $((WIFI_WAIT * 10)) ]
437
+ }
438
+ # A NEW NETWORK AS A NETWORKMANAGER KEYFILE, the format it keeps its own connections in:
439
+ # <uuid> <name> <device> <ssid> <key-mgmt, or nothing for an open network>; the password
440
+ # is $password. Its file is named from the uuid, never from the SSID (which may hold any
441
+ # byte); the SSID is written as its list of bytes ("104;111;109;101;"), unambiguous for
442
+ # any of them. Written whole beside it, root's, 0600, then renamed into place: NetworkManager
443
+ # never reads half a file (and skips a name that starts with a dot). The password goes from
444
+ # printf, part of bash, into that file: no program is started with it among its arguments.
445
+ wifi_file() { printf '%s/clavarium-wifi-%s.nmconnection' "$NM_KEYFILES" "$1"; }
446
+ wifi_keyfile() {
447
+ local file tmp bytes="" b
448
+ file="$(wifi_file "$1")"
449
+ for b in $(printf '%s' "$4" | od -An -v -tu1); do bytes+="$b;"; done
450
+ [ -d "$NM_KEYFILES" ] || install -d -m 0700 "$NM_KEYFILES"
451
+ tmp="$(mktemp -p "$NM_KEYFILES" .clavarium-wifi.XXXXXX)" || return 1
452
+ chmod 0600 -- "$tmp"
453
+ # In a keyfile value a '\' starts an escape: written doubled.
454
+ if ! { printf '[connection]\nid=%s\nuuid=%s\ntype=wifi\ninterface-name=%s\nautoconnect=false\n\n' "$2" "$1" "$3"
455
+ printf '[wifi]\nmode=infrastructure\nssid=%s\n\n' "$bytes"
456
+ [ -z "$5" ] || printf '[wifi-security]\nkey-mgmt=%s\npsk=%s\n\n' "$5" "${password//\\/\\\\}"
457
+ printf '[ipv4]\nmethod=auto\n\n[ipv6]\nmethod=auto\n'; } > "$tmp"; then rm -f -- "$tmp"; return 1; fi
458
+ [ -n "$TEST" ] || chown root:root -- "$tmp"
459
+ mv -f -- "$tmp" "$file"
460
+ }
461
+ # The outcome of a switch, recorded for "wifi status": <state> [<why>]. Uses $ssid and $back.
462
+ wifi_record() {
463
+ install -d -m 0700 "$WIFI_STATE"
464
+ { printf 'last %s %s\n' "$1" "$(date +%s)"; printf 'lastssid %s\n' "$ssid"; printf 'lastback %s\n' "$back"
465
+ [ -z "${2:-}" ] || printf 'lastwhy %s\n' "$2"; } > "$WIFI_STATE/last.new"
466
+ mv -f -- "$WIFI_STATE/last.new" "$WIFI_STATE/last"
467
+ }
468
+
289
469
  [ $# -ge 2 ] || usage
290
470
  AREA="$1"; VERB="$2"; shift 2
291
471
 
@@ -971,6 +1151,191 @@ case "$AREA $VERB" in
971
1151
  printf '%s %s\n' "$VERB" "$1" > "$UPDATE_STATE/request.new"
972
1152
  mv -f -- "$UPDATE_STATE/request.new" "$UPDATE_STATE/request"
973
1153
  exec systemctl start --no-block clavarium-update.service ;;
1154
+ "wifi status")
1155
+ # WI-FI, for Settings (This server, Network): what this server is on, and what it keeps. Read-only.
1156
+ # nmcli <yes|no>
1157
+ # wifiwhy <no-nmcli|not-running|no-device|unmanaged|unavailable> (nothing to do here: said, for the page)
1158
+ # device <name>
1159
+ # using <signal 0-100> <ssid> (the SSID is the rest of the line: it may hold spaces)
1160
+ # saved <ssid> (one per network NetworkManager keeps)
1161
+ # last <joining|joined|went-back|back-failed|interrupted> <seconds since 1970>
1162
+ # lastssid <ssid> lastback <ssid it went back to, or nothing> lastwhy <password|no-connection|no-internet|stopped>
1163
+ [ $# -eq 0 ] || usage
1164
+ if [ "$SAY" = "yes" ]; then echo "nmcli general; nmcli device status; nmcli device wifi list --rescan no; nmcli connection show (read-only)"; exit 0; fi
1165
+ if [ -f "$WIFI_STATE/last" ]; then
1166
+ busy="no"; wifi_busy && busy="yes"
1167
+ while IFS= read -r line; do
1168
+ # "joining" that has not been believed for a while: the switch never ended (a reboot in its middle).
1169
+ if [ "$busy" = "no" ] && [[ "$line" =~ ^last\ joining\ ([0-9]{1,12})$ ]]; then line="last interrupted ${BASH_REMATCH[1]}"; fi
1170
+ [[ "$line" =~ ^(last\ (joining|joined|went-back|back-failed|interrupted)\ [0-9]{1,12}|lastwhy\ [a-z-]{1,20}|last(ssid|back)\ .{0,32})$ ]] && printf '%s\n' "$line"
1171
+ done < "$WIFI_STATE/last"
1172
+ fi
1173
+ type -P nmcli >/dev/null 2>&1 || { printf '%s\n' "nmcli no" "wifiwhy no-nmcli"; exit 0; }
1174
+ echo "nmcli yes"
1175
+ [ "$(nmcli -t -f RUNNING general 2>/dev/null || true)" = "running" ] || { echo "wifiwhy not-running"; exit 0; }
1176
+ read -r dev state <<< "$(wifi_device)" || true
1177
+ [ -n "${dev:-}" ] || { echo "wifiwhy no-device"; exit 0; }
1178
+ echo "device $dev"
1179
+ # Not NetworkManager's to drive (netplan with systemd-networkd, or told so), or switched off.
1180
+ case "$state" in unmanaged) echo "wifiwhy unmanaged"; exit 0 ;; unavailable) echo "wifiwhy unavailable" ;; esac
1181
+ while IFS= read -r line; do
1182
+ # "<signal> <security> now <ssid>": the SSID whole, spaces at its ends included.
1183
+ [[ "$line" =~ ^([0-9]{1,3})\ [a-z0-9]+\ now\ (.+)$ ]] && printf 'using %s %s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
1184
+ done <<< "$(wifi_seen "$dev" no || true)"
1185
+ while IFS= read -r line; do [ -n "$line" ] && printf 'saved %s\n' "${line#* }"; done <<< "$(wifi_saved)"
1186
+ exit 0 ;;
1187
+ "wifi scan")
1188
+ # THE NETWORKS THIS SERVER SEES, looked for again now (a few seconds):
1189
+ # network <signal 0-100> <open|wpa|wpa3|wep|enterprise|other> <now|other> <ssid>
1190
+ # one per name (its strongest), the strongest first; a hidden network is left out.
1191
+ [ $# -eq 0 ] || usage
1192
+ if [ "$SAY" = "yes" ]; then echo "nmcli -t -f IN-USE,SSID,SIGNAL,SECURITY device wifi list --rescan yes (read-only)"; exit 0; fi
1193
+ type -P nmcli >/dev/null 2>&1 || refuse "NetworkManager (nmcli) is not on this server: its Wi-Fi is managed outside Clavarium"
1194
+ read -r dev state <<< "$(wifi_device)" || true
1195
+ [ -n "${dev:-}" ] || refuse "NetworkManager has no Wi-Fi device on this server"
1196
+ [ "$state" != "unmanaged" ] || refuse "the Wi-Fi device $dev is not managed by NetworkManager"
1197
+ seen="$(wifi_seen "$dev" yes)" || refuse "NetworkManager did not list the networks"
1198
+ while IFS= read -r line; do [ -n "$line" ] && printf 'network %s\n' "$line"; done <<< "$seen"
1199
+ exit 0 ;;
1200
+ "wifi join")
1201
+ # THIS SERVER TO ANOTHER WI-FI NETWORK, and back by itself if it does not work. On
1202
+ # standard input, never as arguments (ps shows those to everyone): the SSID on the
1203
+ # first line, the password on the second (empty for an open network). The network is
1204
+ # written as a keyfile and loaded (autoconnect off: a reboot comes back on the old
1205
+ # one), then the switch is
1206
+ # started in a unit of its own ("wifi switch") and this returns at once:
1207
+ # joining <ssid>
1208
+ # fallback <the ssid it goes back to, or nothing: there was no Wi-Fi in use>
1209
+ [ $# -eq 0 ] || usage
1210
+ ssid=""; password=""
1211
+ IFS= read -r ssid || true
1212
+ IFS= read -r password || true
1213
+ is_ssid "$ssid" || refuse "not a network name: 1 to 32 bytes, on one line"
1214
+ # The password itself is never in a message: only what is wrong with it.
1215
+ if [ -n "$password" ]; then
1216
+ [ "${#password}" -ge 8 ] && [ "${#password}" -le 63 ] || refuse "a Wi-Fi password has 8 to 63 characters (this one has ${#password})"
1217
+ [[ "$password" =~ ^[\ -~]+$ ]] || refuse "a Wi-Fi password is made of plain characters (letters, digits, signs, spaces): this one has another"
1218
+ # A keyfile value loses a space at its start, and one at its end is easily lost by hand.
1219
+ [[ "$password" != " "* && "$password" != *" " ]] || refuse "a password that starts or ends with a space cannot be given here"
1220
+ fi
1221
+ if [ "$SAY" = "yes" ]; then
1222
+ printf '%s\n' "write $NM_KEYFILES/clavarium-wifi-<uuid>.nmconnection (root, 0600: ssid $ssid, autoconnect=false${password:+, key-mgmt <wpa-psk|sae>, its password})" \
1223
+ "nmcli connection load $NM_KEYFILES/clavarium-wifi-<uuid>.nmconnection" \
1224
+ "systemd-run --unit=$WIFI_UNIT --collect clavarium-host wifi switch"
1225
+ exit 0
1226
+ fi
1227
+ type -P nmcli >/dev/null 2>&1 || refuse "NetworkManager (nmcli) is not on this server: its Wi-Fi is managed outside Clavarium"
1228
+ ! wifi_busy || refuse "a switch is going on already: wait for its end (a minute or two)"
1229
+ read -r dev state <<< "$(wifi_device)" || true
1230
+ [ -n "${dev:-}" ] || refuse "NetworkManager has no Wi-Fi device on this server"
1231
+ [ "$state" != "unmanaged" ] || refuse "the Wi-Fi device $dev is not managed by NetworkManager"
1232
+ # Its protection, as the radio says it now: a password for what wants one, and nothing more.
1233
+ sec=""
1234
+ while IFS= read -r line; do
1235
+ [[ "$line" =~ ^[0-9]{1,3}\ ([a-z0-9]+)\ (now|other)\ (.+)$ ]] && [ "${BASH_REMATCH[3]}" = "$ssid" ] && { sec="${BASH_REMATCH[1]}"; break; }
1236
+ done <<< "$(wifi_seen "$dev" no || true)"
1237
+ [ -n "$sec" ] || refuse "$ssid is not in sight of this server: look for the networks again"
1238
+ case "$sec" in
1239
+ open) [ -z "$password" ] || refuse "$ssid is an open network: it takes no password" ;;
1240
+ wpa|wpa3) [ -n "$password" ] || refuse "$ssid is protected: its password is needed" ;;
1241
+ wep) refuse "$ssid is protected the old way (WEP), which is not joined from here" ;;
1242
+ enterprise) refuse "$ssid asks for a user and a certificate (802.1X), which are not given from here" ;;
1243
+ *) refuse "$ssid is protected in a way not joined from here" ;;
1244
+ esac
1245
+ # What it goes back to: the connection on that device now, if any.
1246
+ prev="$(wifi_active_on "$dev")"; back=""
1247
+ [ -z "$prev" ] || back="$(nmcli -e no -g 802-11-wireless.ssid connection show uuid "$prev" 2>/dev/null || true)"
1248
+ is_ssid "$back" || back=""
1249
+ [ -z "$prev" ] || [ "$back" != "$ssid" ] || refuse "$ssid is the network in use already"
1250
+ new=""; read -r new < /proc/sys/kernel/random/uuid || true
1251
+ is_uuid "$new" || refuse "no new identifier could be made for the network"
1252
+ keys=""; case "$sec" in wpa) keys="wpa-psk" ;; wpa3) keys="sae" ;; esac
1253
+ wifi_keyfile "$new" "clavarium-wifi-$(date +%s)" "$dev" "$ssid" "$keys" || refuse "the new network could not be written for NetworkManager"
1254
+ password=""
1255
+ file="$(wifi_file "$new")"
1256
+ if ! nmcli connection load "$file" >/dev/null 2>&1 || [ "$(nmcli -g connection.uuid connection show uuid "$new" 2>/dev/null | head -1 || true)" != "$new" ]; then
1257
+ nmcli connection delete uuid "$new" >/dev/null 2>&1 || true; rm -f -- "$file"
1258
+ refuse "NetworkManager did not take the new network"
1259
+ fi
1260
+ install -d -m 0700 "$WIFI_STATE"
1261
+ printf 'new %s\nprev %s\ndevice %s\n' "$new" "${prev:-none}" "$dev" > "$WIFI_STATE/switch"
1262
+ wifi_record joining
1263
+ self=(/bin/bash "$(readlink -f -- "$0")"); [ -z "$TEST" ] || self+=(--test "$TEST")
1264
+ if ! systemd-run --quiet --unit="$WIFI_UNIT" --collect --description="Clavarium - Wi-Fi to another network, back to the one before if it does not work" \
1265
+ --property=TimeoutStopSec=180 "${self[@]}" wifi switch; then
1266
+ nmcli connection delete uuid "$new" >/dev/null 2>&1 || true; rm -f -- "$file"
1267
+ rm -f -- "$WIFI_STATE/switch"; wifi_record went-back stopped
1268
+ refuse "the switch could not be started (another one still running?)"
1269
+ fi
1270
+ printf 'joining %s\nfallback %s\n' "$ssid" "$back"
1271
+ exit 0 ;;
1272
+ "wifi switch")
1273
+ # THE SWITCH ITSELF, run by "wifi join" in its unit, as root: asks nothing, it does
1274
+ # the switch recorded by the last join (and nothing else: no join, nothing to do).
1275
+ # The new connection up; then up to $WIFI_WAIT seconds from its start for a working
1276
+ # network (see wifi_online); if there is none, the new network is deleted and the
1277
+ # one before brought up again. The outcome is recorded for "wifi status".
1278
+ [ $# -eq 0 ] || usage
1279
+ if [ "$SAY" = "yes" ]; then echo "nmcli connection up <the new network>; ${WIFI_WAIT} s at most for a working network; else nmcli connection delete <the new one>; nmcli connection up <the one before>"; exit 0; fi
1280
+ rec="$WIFI_STATE/switch"
1281
+ [ -f "$rec" ] && [ "$(wifi_last_word)" = "joining" ] || refuse "no switch was asked"
1282
+ new="$(sed -n 's/^new //p' "$rec" | head -1)"; prev="$(sed -n 's/^prev //p' "$rec" | head -1)"; dev="$(sed -n 's/^device //p' "$rec" | head -1)"
1283
+ ssid="$(sed -n 's/^lastssid //p' "$WIFI_STATE/last" | head -1)"; back="$(sed -n 's/^lastback //p' "$WIFI_STATE/last" | head -1)"
1284
+ is_uuid "$new" && { [ "$prev" = "none" ] || is_uuid "$prev"; } && [[ "$dev" =~ ^[A-Za-z0-9._-]{1,15}$ ]] || refuse "the switch's record is not what it should be"
1285
+ rm -f -- "$rec"
1286
+ # Back to the connection before: the new one deleted (that ends it) and its file sure
1287
+ # to be gone with its password, the old one up, tried three times (the radio may still
1288
+ # be busy leaving the other network).
1289
+ go_back() {
1290
+ local i
1291
+ nmcli connection delete uuid "$new" >/dev/null 2>&1 || true
1292
+ rm -f -- "$(wifi_file "$new")"
1293
+ if [ "$prev" = "none" ]; then wifi_record went-back "$1"; return 0; fi
1294
+ for i in 1 2 3; do
1295
+ if nmcli --wait "$WIFI_UP_WAIT" connection up uuid "$prev" >/dev/null 2>&1; then wifi_record went-back "$1"; return 0; fi
1296
+ sleep "$WIFI_STEP"
1297
+ done
1298
+ wifi_record back-failed "$1"
1299
+ }
1300
+ # Stopped in its middle (a shutdown, someone): never left on a network that was not proven.
1301
+ trap 'go_back stopped; exit 0' TERM INT HUP
1302
+ start="$SECONDS"
1303
+ if ! said="$(nmcli --wait "$WIFI_UP_WAIT" connection up uuid "$new" 2>&1 >/dev/null)"; then
1304
+ case "$said" in *[Ss]ecrets*|*assword*|*psk*|*802-11-wireless-security*) go_back password ;; *) go_back no-connection ;; esac
1305
+ exit 0
1306
+ fi
1307
+ # (A plain count of looks: $SECONDS is whole seconds, the tests' waits are shorter.)
1308
+ looks=$(awk -v w="$WIFI_WAIT" -v s="$WIFI_STEP" 'BEGIN { print int(w / s) }')
1309
+ for ((i = 0; i < looks && SECONDS - start < WIFI_WAIT; i++)); do
1310
+ if wifi_online "$dev"; then
1311
+ nmcli connection modify uuid "$new" connection.autoconnect yes >/dev/null 2>&1 || true
1312
+ trap - TERM INT HUP
1313
+ wifi_record joined
1314
+ exit 0
1315
+ fi
1316
+ sleep "$WIFI_STEP"
1317
+ done
1318
+ go_back no-internet
1319
+ exit 0 ;;
1320
+ "wifi forget")
1321
+ # <ssid>: every network NetworkManager keeps under that name, deleted. Never the one
1322
+ # in use (the server would lose its network), never during a switch.
1323
+ [ $# -eq 1 ] || usage
1324
+ is_ssid "$1" || refuse "not a network name: 1 to 32 bytes, on one line"
1325
+ if [ "$SAY" = "yes" ]; then echo "nmcli connection delete uuid <each saved network named $1>"; exit 0; fi
1326
+ type -P nmcli >/dev/null 2>&1 || refuse "NetworkManager (nmcli) is not on this server: its Wi-Fi is managed outside Clavarium"
1327
+ ! wifi_busy || refuse "a switch is going on: try again when it has ended"
1328
+ active="$(wifi_active_all)"; gone=()
1329
+ while IFS= read -r line; do
1330
+ u="${line%% *}"
1331
+ [ -n "$line" ] && [ "${line#* }" = "$1" ] || continue
1332
+ ! grep -qx -- "$u" <<< "$active" || refuse "$1 is the network in use: join another one first"
1333
+ gone+=("$u")
1334
+ done <<< "$(wifi_saved)"
1335
+ [ "${#gone[@]}" -gt 0 ] || refuse "no saved network is named $1"
1336
+ for u in "${gone[@]}"; do nmcli connection delete uuid "$u" >/dev/null 2>&1 || refuse "NetworkManager did not forget $1"; done
1337
+ printf 'forgotten %s\n' "$1"
1338
+ exit 0 ;;
974
1339
  "path held")
975
1340
  # <dir>: the check `held` makes, run for real on that path, as the
976
1341
  # caller (root not needed to refuse). --say-only only: it exists so
package/deploy/install.sh CHANGED
@@ -554,6 +554,11 @@ fi
554
554
  # Caddy would keep that one for hours: clavarium-certificate.timer replaces it
555
555
  # with Let's Encrypt's as soon as it can (sudo clavarium doctor --certificate).
556
556
  BIND=""; [ -z "$RELAY" ] || BIND=" bind 127.0.0.1"
557
+ # The page the front serves while the server is down (an update, a restart): kept outside the
558
+ # releases, so it is there during the switch; kept up to date by the updater (ensureMaintenance).
559
+ # A release from before it (--keep-release) has none: the updater writes it at its next turn.
560
+ install -d -o root -g root -m 0755 /var/lib/clavarium/maintenance
561
+ [ ! -f "$APP/deploy/maintenance.html" ] || install -o root -g root -m 0644 "$APP/deploy/maintenance.html" /var/lib/clavarium/maintenance/index.html
557
562
  # The probe's token: kept on a rerun (see deploy/doctor.mjs, probeBlock).
558
563
  # No Caddyfile yet (going online from local mode): no token, not a failure (pipefail).
559
564
  PROBE="$( { sed -n 's/.*respond "\([0-9a-f]\{32\}\)" 200.*/\1/p' /etc/caddy/Caddyfile 2>/dev/null || true; } | head -1)"
@@ -572,7 +577,30 @@ $BIND
572
577
  reverse_proxy 127.0.0.1:5556
573
578
  }
574
579
  handle {
575
- reverse_proxy 127.0.0.1:4180
580
+ # The server down (an update, a restart): the maintenance page (deploy/updater.mjs, MAINTENANCE_BLOCK).
581
+ reverse_proxy 127.0.0.1:4180 {
582
+ @down {
583
+ status 502 503 504
584
+ header Content-Type text/html*
585
+ }
586
+ handle_response @down {
587
+ header Cache-Control no-store
588
+ header Retry-After 3
589
+ header X-Clavarium-Down 1
590
+ @api path /api/* /c/api/*
591
+ handle @api {
592
+ header Content-Type "application/json; charset=utf-8"
593
+ respond "{\"error\":\"Clavarium is being updated or restarted: it comes back by itself in a moment.\",\"down\":true}" 503
594
+ }
595
+ handle {
596
+ root * /var/lib/clavarium/maintenance
597
+ rewrite * /index.html
598
+ file_server {
599
+ status 503
600
+ }
601
+ }
602
+ }
603
+ }
576
604
  }
577
605
  }
578
606
 
@@ -0,0 +1,109 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <!-- THE MAINTENANCE PAGE: one file, everything in it. Shown in two ways:
4
+ - by the edge (Caddy, see install.sh and deploy/updater.mjs, MAINTENANCE)
5
+ for any address while the server does not answer: an update, a restart.
6
+ It is kept outside the releases, so it is there during the switch;
7
+ - by the server itself (/maintenance.html), when a page learns that an
8
+ update is about to stop it (the header x-clavarium-update, app.js).
9
+ It asks the server every few seconds and goes back to where it was as
10
+ soon as the server answers again and no update is announced any more. -->
11
+ <meta charset="utf-8">
12
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
13
+ <meta name="robots" content="noindex">
14
+ <meta name="theme-color" content="#0f141a">
15
+ <title>Clavarium</title>
16
+ <style>
17
+ :root { --bg: #0f141a; --panel: #131a22; --line: #2b3745; --ink: #e7edf4; --ink2: #a3b1c2; --brass: #d2a94e; --on-brass: #1b1405; color-scheme: dark; }
18
+ @media (prefers-color-scheme: light) { :root { --bg: #fbfbfa; --panel: #ffffff; --line: #c5cdd8; --ink: #17202b; --ink2: #4f5d6d; --brass: #c79a3a; color-scheme: light; } }
19
+ * { box-sizing: border-box; }
20
+ html, body { margin: 0; min-height: 100%; background: var(--bg); color: var(--ink); }
21
+ body { min-height: 100dvh; display: grid; place-items: center; padding: 24px 16px; font: 1rem system-ui, -apple-system, "Segoe UI", sans-serif; }
22
+ main { max-width: 30rem; text-align: center; }
23
+ h1 { font-size: 1.25rem; font-weight: 600; margin: 18px 0 8px; overflow-wrap: anywhere; }
24
+ p { color: var(--ink2); margin: 6px 0; line-height: 1.45; }
25
+ .turning { width: 34px; height: 34px; margin: 0 auto; border-radius: 50%; border: 3px solid var(--line); border-top-color: var(--brass); animation: turn 1.1s linear infinite; }
26
+ @keyframes turn { to { transform: rotate(360deg); } }
27
+ @media (prefers-reduced-motion: reduce) { .turning { animation-duration: 4s; } }
28
+ #stuck { margin-top: 18px; padding: 14px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); text-align: left; }
29
+ #stuck p { margin: 0 0 10px; }
30
+ code { font: .8125rem ui-monospace, monospace; color: var(--ink); overflow-wrap: anywhere; }
31
+ button { font: 600 .875rem system-ui, sans-serif; color: var(--on-brass); background: var(--brass); border: 0; border-radius: 7px; padding: 8px 14px; cursor: pointer; }
32
+ [hidden] { display: none !important; }
33
+ </style>
34
+ <main>
35
+ <div class="turning" aria-hidden="true"></div>
36
+ <h1 id="title" aria-live="polite">Clavarium is being updated or restarted...</h1>
37
+ <p id="said">This page reloads by itself.</p>
38
+ <div id="stuck" hidden>
39
+ <p>This is taking longer than it should: something may have gone wrong.</p>
40
+ <p><button type="button" id="reload">Reload</button></p>
41
+ <p>On the server, what the updater did: <code>sudo journalctl -u clavarium-update -n 100</code>, and the server itself: <code>sudo journalctl -u clavarium -n 100</code>.</p>
42
+ </div>
43
+ </main>
44
+ <script>
45
+ /* Asked this often; past STUCK_MS the page says something is wrong (and goes on asking). */
46
+ const EVERY_MS = 2500;
47
+ const STUCK_MS = 10 * 60_000;
48
+ /* A restart asked from Settings: the server answers a moment more before it stops (two
49
+ seconds, serverlogs.mjs). That answer is not "back": it is, once it was seen down, or after this. */
50
+ const RESTART_GRACE_MS = 20_000;
51
+ const VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,6}(-[0-9A-Za-z.-]{1,40})?$/;
52
+
53
+ /* WHAT IT DOES NEXT: 'back', 'wait' or 'stuck'. `answer`: null when nothing answered (the
54
+ network, or the edge itself), else { status, down, update }: down when the edge said the
55
+ server is down (or the sign-in proxy's bare 502, before the edge knew this page), update
56
+ when the server still announces an update about to stop it. */
57
+ const next = ({ kind, startedAt, now, seenDown, answer }) => {
58
+ const up = !!answer && !answer.down && !answer.update && !(answer.status >= 502 && answer.status <= 504);
59
+ if (up && !(kind === 'restart' && !seenDown && now - startedAt < RESTART_GRACE_MS)) return 'back';
60
+ return now - startedAt > STUCK_MS ? 'stuck' : 'wait';
61
+ };
62
+
63
+ /* WHAT IT SAYS, from its address (?kind=update|back|restart&to=<version>): the edge serves
64
+ it at any address, with none of these: then it cannot know which. */
65
+ const title = (kind, to) => {
66
+ const v = VERSION.test(to ?? '') ? to : '';
67
+ if (kind === 'update') return v ? `Updating Clavarium to ${v}...` : 'Updating Clavarium...';
68
+ if (kind === 'back') return v ? `Going back to Clavarium ${v}...` : 'Going back to the previous Clavarium...';
69
+ if (kind === 'restart') return 'Restarting Clavarium...';
70
+ return 'Clavarium is being updated or restarted...';
71
+ };
72
+
73
+ /* WHERE IT GOES BACK TO: the page it replaced (?back=, on this site only), else the address
74
+ it was served at (the edge's), else the start (this page asked for by its own name). */
75
+ const backTo = (back, pathname, search) => {
76
+ if (/^\/(?![/\\])/.test(back ?? '')) return back;
77
+ if (pathname === '/maintenance.html') return '/';
78
+ if (pathname === '/c/maintenance.html') return '/c/';
79
+ return pathname + (search ?? '');
80
+ };
81
+
82
+ /* Only in a browser: the tests read the three functions above, and nothing starts. */
83
+ if (typeof document !== 'undefined') {
84
+ const q = new URLSearchParams(location.search);
85
+ const kind = q.get('kind') ?? '';
86
+ const startedAt = Date.now();
87
+ let seenDown = false;
88
+ /* Something small the server answers without effort; a paired device's own door needs no sign-in. */
89
+ const ask = location.pathname.startsWith('/c/') ? '/c/manifest.webmanifest' : '/manifest.webmanifest';
90
+ const go = () => location.replace(backTo(q.get('back'), location.pathname, location.search));
91
+ document.getElementById('title').textContent = title(kind, q.get('to'));
92
+ document.getElementById('reload').addEventListener('click', go);
93
+ const look = async () => {
94
+ let answer = null;
95
+ try {
96
+ const r = await fetch(ask, { cache: 'no-store', redirect: 'manual', credentials: 'same-origin' });
97
+ /* A redirection (to sign in again) is an answer: it has no status to read. */
98
+ answer = { status: r.type === 'opaqueredirect' ? 0 : r.status, down: !!r.headers.get('x-clavarium-down'), update: r.headers.get('x-clavarium-update') ?? '' };
99
+ } catch { /* no answer */ }
100
+ if (!answer || answer.down || (answer.status >= 502 && answer.status <= 504)) seenDown = true;
101
+ const then = next({ kind, startedAt, now: Date.now(), seenDown, answer });
102
+ if (then === 'back') { go(); return; }
103
+ document.getElementById('stuck').hidden = then !== 'stuck';
104
+ setTimeout(look, EVERY_MS);
105
+ };
106
+ setTimeout(look, EVERY_MS);
107
+ }
108
+ </script>
109
+ </html>