Repository navigation
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·2420 lines (2141 loc) · 82.6 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·2420 lines (2141 loc) · 82.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#
# Demarkus Install Script
#
# Usage:
# curl -fsSL https://raw.githubusercontent.com/latebit-io/demarkus/main/install.sh | bash
# curl -fsSL ... | bash -s -- --domain example.com --root /srv/site
# curl -fsSL ... | bash -s -- --tls-cert /path/cert.pem --tls-key /path/key.pem
# curl -fsSL ... | bash -s -- --client-only
#
# Reading room (--with-library, beside the server on one Linux host):
# curl -fsSL ... | sudo bash -s -- --domain example.com --with-library
# Serves a read-only reading room: HTTPS on :443 with the world's cert
# when TLS is configured (--domain or --tls-cert), else HTTP on :8090.
# Override with --library-port; pin the version with --library-version.
#
# For private repos, set GITHUB_TOKEN:
# curl -fsSL -H "Authorization: token $GITHUB_TOKEN" \
# https://raw.githubusercontent.com/latebit-io/demarkus/main/install.sh \
# | GITHUB_TOKEN=$GITHUB_TOKEN bash
#
# After install:
# demarkus-install update # update to latest version
# # --library-version pins the reading room
# demarkus-install uninstall # remove everything
#
set -euo pipefail
GITHUB_REPO="latebit-io/demarkus"
# Bound every GitHub call so a stalled request cannot hang an install forever.
CURL_TIMEOUT_ARGS=(--connect-timeout 10 --max-time 300 --retry 3 --retry-delay 2)
INSTALL_DIR="/usr/local/bin"
# If demarkus is already installed somewhere, use that directory so
# update/uninstall operate on the same location as the original install.
_detect_existing_install_dir() {
# type -P returns only filesystem paths, never aliases or shell functions.
# -x guard ensures the result is an actual executable before using dirname.
local self
self=$(type -P demarkus-install 2>/dev/null || true)
if [ -x "$self" ]; then
INSTALL_DIR=$(dirname "$self")
return
fi
# Fall back to where the client binary lives.
local cli
cli=$(type -P demarkus 2>/dev/null || true)
if [ -x "$cli" ]; then
INSTALL_DIR=$(dirname "$cli")
fi
}
_detect_existing_install_dir
CONFIG_DIR_LINUX="/etc/demarkus"
CONFIG_DIR_MACOS="$HOME/.demarkus"
DEFAULT_ROOT_LINUX="/var/lib/demarkus"
DEFAULT_ROOT_MACOS="$HOME/.demarkus/content"
SERVICE_NAME="demarkus"
SCRIPT_VERSION="1"
# Fixed to systemd's search path in production; the test harness redirects it
# via DEMARKUS_TEST_SYSTEMD_DIR only under DEMARKUS_INSTALL_TESTMODE=1, so a
# stray production override cannot misplace units.
SYSTEMD_DIR="/etc/systemd/system"
if [ "${DEMARKUS_INSTALL_TESTMODE:-}" = "1" ] && [ -n "${DEMARKUS_TEST_SYSTEMD_DIR:-}" ]; then
SYSTEMD_DIR="$DEMARKUS_TEST_SYSTEMD_DIR"
fi
# Touched only by the hairpin self-dial fallback (ensure_self_dial).
HOSTS_FILE="/etc/hosts"
# Global state
SUDO="" # set to "sudo" if needed for INSTALL_DIR writes
_TMPDIR="" # global tmpdir for EXIT trap
trap '[ -n "$_TMPDIR" ] && rm -rf "$_TMPDIR"' EXIT
# --- Logging ---
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'
log_info() { printf "${GREEN}[info]${NC} %s\n" "$*"; }
log_warn() { printf "${YELLOW}[warn]${NC} %s\n" "$*"; }
log_error() { printf "${RED}[error]${NC} %s\n" "$*" >&2; }
log_step() { printf "${BLUE}==> %s${NC}\n" "$*"; }
# validate_port aborts unless $2 is an integer in [1,65535]; $1 names the
# source for the error message (a flag or a config file).
validate_port() {
local source="$1"
local port="$2"
case "$port" in
''|*[!0-9]*)
log_error "${source} must be a number (1-65535), got '${port}'"
exit 1 ;;
esac
if [ "$port" -lt 1 ] || [ "$port" -gt 65535 ]; then
log_error "${source} must be between 1 and 65535, got '${port}'"
exit 1
fi
}
# --- Install permissions ---
_acquire_sudo() {
# Set SUDO="sudo" if we can get authorization. Works in curl|bash pipes because
# sudo opens /dev/tty directly. Returns 0 on success, 1 if unavailable/denied.
if ! command -v sudo >/dev/null 2>&1; then
return 1
fi
if sudo -n true 2>/dev/null || { ( : </dev/tty ) 2>/dev/null && sudo true </dev/tty 2>/dev/tty; }; then
SUDO="sudo"
return 0
fi
return 1
}
check_install_permissions() {
local require=false
[ "${1:-}" = "--require" ] && require=true
# Running as root: all operations are already privileged, nothing to do.
if [ "$(id -u)" -eq 0 ]; then
mkdir -p "$INSTALL_DIR"
return
fi
# On Linux, update/uninstall also touch CONFIG_DIR (/etc/demarkus) and systemd,
# so we need sudo even when INSTALL_DIR happens to be writable by the current user.
if [ "$require" = true ] && [ "${PLATFORM:-}" = "linux" ]; then
if ! _acquire_sudo; then
log_error "Cannot perform privileged operations and sudo is not available."
log_error "Run as root or with sudo."
exit 1
fi
mkdir -p "$INSTALL_DIR" 2>/dev/null || $SUDO mkdir -p "$INSTALL_DIR"
return
fi
if [ -d "$INSTALL_DIR" ] && [ -w "$INSTALL_DIR" ]; then
return
fi
# Use sudo if available. sudo can prompt via /dev/tty even in curl|bash pipes
# where stdin is not a TTY. Try non-interactive first (cached creds), then
# fall back to interactive (prompts via /dev/tty).
if _acquire_sudo; then
$SUDO mkdir -p "$INSTALL_DIR"
log_info "Will use sudo to install to ${INSTALL_DIR}"
return
fi
# For update/uninstall, switching directories would corrupt the existing install.
if [ "$require" = true ]; then
log_error "Cannot write to ${INSTALL_DIR} and sudo is not available."
log_error "Run as root or with sudo."
exit 1
fi
local user_bin="$HOME/.local/bin"
mkdir -p "$user_bin"
INSTALL_DIR="$user_bin"
log_info "Installing to ${user_bin} (add to PATH if not already there)"
}
# --- Platform detection ---
detect_platform() {
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
IS_WSL=false
IS_WSL2=false
case "$OS" in
linux)
PLATFORM="linux"
if grep -qi microsoft /proc/version 2>/dev/null; then
IS_WSL=true
# WSL2's kernel osrelease contains "WSL2"; WSL1 does not
if grep -qi 'wsl2' /proc/sys/kernel/osrelease 2>/dev/null; then
IS_WSL2=true
fi
fi
;;
darwin) PLATFORM="darwin" ;;
msys*|cygwin*|mingw*)
log_error "Windows detected. Download binaries directly from GitHub Releases:"
log_error " https://github.com/${GITHUB_REPO}/releases"
log_error "Or use WSL2 — see: https://latebit-io.github.io/demarkus/install/windows/"
exit 1
;;
*) log_error "Unsupported OS: $OS"; exit 1 ;;
esac
case "$ARCH" in
x86_64|amd64) GOARCH="amd64" ;;
aarch64|arm64) GOARCH="arm64" ;;
armv7l|armhf) GOARCH="arm" ;;
*) log_error "Unsupported architecture: $ARCH"; exit 1 ;;
esac
# Set platform-specific defaults
if [ "$PLATFORM" = "linux" ]; then
CONFIG_DIR="$CONFIG_DIR_LINUX"
DEFAULT_ROOT="$DEFAULT_ROOT_LINUX"
else
CONFIG_DIR="$CONFIG_DIR_MACOS"
DEFAULT_ROOT="$DEFAULT_ROOT_MACOS"
fi
}
# --- Semver helpers ---
# Parse version string into comparable integer: 1.2.3 -> 1002003
version_num() {
local parts
IFS='.' read -r -a parts <<<"$1"
echo $(( ${parts[0]:-0} * 1000000 + ${parts[1]:-0} * 1000 + ${parts[2]:-0} ))
}
version_lt() { [ "$(version_num "$1")" -lt "$(version_num "$2")" ]; }
version_gte() { [ "$(version_num "$1")" -ge "$(version_num "$2")" ]; }
# --- GitHub auth ---
# Auth args for curl when GITHUB_TOKEN is set (for private repos).
# Used as: curl -fsSL "${CURL_AUTH_ARGS[@]}" "$url"
CURL_AUTH_ARGS=()
if [ -n "${GITHUB_TOKEN:-}" ]; then
CURL_AUTH_ARGS=(-H "Authorization: token ${GITHUB_TOKEN}")
fi
# --- GitHub API ---
github_api() {
local url="$1"
set +u
curl -fsSL "${CURL_TIMEOUT_ARGS[@]}" "${CURL_AUTH_ARGS[@]}" "$url" 2>/dev/null
set -u
}
fetch_latest_version() {
local component="$1" # "server" or "client"
local url="https://api.github.com/repos/${GITHUB_REPO}/releases"
local releases
releases=$(github_api "$url") || {
log_error "Failed to fetch releases from GitHub"
exit 1
}
# Find the latest release tagged with the component prefix
echo "$releases" | grep -o "\"tag_name\": \"${component}/v[^\"]*\"" \
| head -1 \
| sed "s/\"tag_name\": \"${component}\/v\(.*\)\"/\1/"
}
# Download a release asset. For private repos (GITHUB_TOKEN set), uses the
# GitHub API to resolve asset IDs and download via the API endpoint.
# For public repos, uses the direct github.com download URL.
download_asset_file() {
local tag="$1"
local filename="$2"
local output_path="$3"
if [ -n "${GITHUB_TOKEN:-}" ]; then
# Private repo: resolve asset ID via API, then download with octet-stream accept
local encoded_tag
encoded_tag=$(printf '%s' "$tag" | sed 's|/|%2F|g')
local release_url="https://api.github.com/repos/${GITHUB_REPO}/releases/tags/${encoded_tag}"
local release_json
release_json=$(github_api "$release_url") || {
log_error "Failed to fetch release for tag ${tag}"
return 1
}
# Extract the asset API URL for the given filename.
# Look for the assets/NNNN URL that appears near our filename in the JSON.
local asset_url
asset_url=$(echo "$release_json" \
| grep -B10 "\"name\": \"${filename}\"" \
| grep '"url":.*releases/assets/' \
| head -1 \
| sed 's/.*"url": "\([^"]*\)".*/\1/')
if [ -z "$asset_url" ]; then
log_error "Asset ${filename} not found in release ${tag}"
return 1
fi
curl -fsSL "${CURL_TIMEOUT_ARGS[@]}" -H "Authorization: token ${GITHUB_TOKEN}" \
-H "Accept: application/octet-stream" \
-o "$output_path" "$asset_url" || return 1
else
# Public repo: direct download URL
local encoded_tag
encoded_tag=$(printf '%s' "$tag" | sed 's|/|%2F|g')
local url="https://github.com/${GITHUB_REPO}/releases/download/${encoded_tag}/${filename}"
curl -fsSL "${CURL_TIMEOUT_ARGS[@]}" -o "$output_path" "$url" || return 1
fi
}
# verify_sha256 exits unless file matches its entry in the checksums file.
# Every unverifiable case is fatal: no file, no entry, no sha tool.
verify_sha256() {
local file="$1" sums="$2"
local name expected actual
name=$(basename "$file")
if [ ! -f "$sums" ]; then
log_error "No checksums file for ${name}; refusing to install unverified"
exit 1
fi
expected=$(awk -v n="$name" '$2 == n || $2 == "*" n {print $1; exit}' "$sums")
if [ -z "$expected" ]; then
log_error "No checksum entry for ${name}; refusing to install unverified"
exit 1
fi
if command -v sha256sum >/dev/null 2>&1; then
actual=$(sha256sum "$file" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
actual=$(shasum -a 256 "$file" | awk '{print $1}')
else
log_error "sha256sum or shasum is required to verify ${name}"
exit 1
fi
if [ "$expected" != "$actual" ]; then
log_error "Checksum mismatch for ${name}"
log_error " Expected: $expected"
log_error " Actual: $actual"
exit 1
fi
log_info "Checksum verified"
}
download_and_verify() {
local component="$1" # "server" or "client"
local version="$2"
local tmpdir="$3"
local tag="${component}/v${version}"
local archive_name="demarkus-${component}_${version}_${PLATFORM}_${GOARCH}"
local archive_file="${archive_name}.tar.gz"
local checksums_file="demarkus-${component}_checksums.txt"
log_info "Downloading ${component} v${version} for ${PLATFORM}/${GOARCH}..."
download_asset_file "$tag" "$archive_file" "${tmpdir}/${archive_file}" || {
log_error "Failed to download ${archive_file}"
exit 1
}
download_asset_file "$tag" "$checksums_file" "${tmpdir}/${checksums_file}" || {
log_error "Failed to download ${checksums_file}"
exit 1
}
verify_sha256 "${tmpdir}/${archive_file}" "${tmpdir}/${checksums_file}"
tar xzf "${tmpdir}/${archive_file}" -C "${tmpdir}"
}
download_and_verify_asset() {
local asset_prefix="$1" # e.g. "demarkus-tui"
local version="$2"
local component="$3" # release component for tag, e.g. "client"
local tmpdir="$4"
local tag="${component}/v${version}"
local archive_name="${asset_prefix}_${version}_${PLATFORM}_${GOARCH}"
local archive_file="${archive_name}.tar.gz"
local checksums_file="demarkus-${component}_checksums.txt"
log_info "Downloading ${asset_prefix} v${version} for ${PLATFORM}/${GOARCH}..."
download_asset_file "$tag" "$archive_file" "${tmpdir}/${archive_file}" || {
log_error "Failed to download ${archive_file}"
exit 1
}
# A prior call for the same release may have fetched the checksums already.
if [ ! -f "${tmpdir}/${checksums_file}" ]; then
download_asset_file "$tag" "$checksums_file" "${tmpdir}/${checksums_file}" || {
log_error "Failed to download ${checksums_file}"
exit 1
}
fi
verify_sha256 "${tmpdir}/${archive_file}" "${tmpdir}/${checksums_file}"
tar xzf "${tmpdir}/${archive_file}" -C "${tmpdir}"
}
# --- Install functions ---
# install_binary_atomic replaces dest by rename, never opening it for write:
# a running executable rejects that with ETXTBSY ("Text file busy"). The stage
# is per-process and beside dest, so the rename is atomic on one filesystem.
install_binary_atomic() {
local src="$1" dest="$2"
local stage="${dest}.new.$$"
$SUDO install -m 755 "$src" "$stage" || return 1
$SUDO mv -f "$stage" "$dest" || { $SUDO rm -f "$stage"; return 1; }
}
install_binaries() {
local tmpdir="$1"
shift
local binaries=("$@")
for bin in "${binaries[@]}"; do
if [ -f "${tmpdir}/${bin}" ]; then
$SUDO cp "${tmpdir}/${bin}" "${INSTALL_DIR}/${bin}"
$SUDO chmod 755 "${INSTALL_DIR}/${bin}"
log_info "Installed ${INSTALL_DIR}/${bin}"
else
log_warn "Binary ${bin} not found in archive"
fi
done
}
create_system_user() {
if [ "$PLATFORM" != "linux" ]; then return; fi
if id "$SERVICE_NAME" >/dev/null 2>&1; then
log_info "User '${SERVICE_NAME}' already exists"
return
fi
log_info "Creating system user '${SERVICE_NAME}'..."
useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_NAME"
}
setup_config_dir() {
mkdir -p "$CONFIG_DIR"
if [ "$PLATFORM" = "linux" ]; then
chown root:"$SERVICE_NAME" "$CONFIG_DIR"
chmod 750 "$CONFIG_DIR"
fi
log_info "Config directory: ${CONFIG_DIR}"
}
setup_content_dir() {
local root="$1"
mkdir -p "$root"
if [ "$PLATFORM" = "linux" ]; then
chown "$SERVICE_NAME":"$SERVICE_NAME" "$root"
fi
log_info "Content directory: ${root}"
}
generate_token() {
local tokens_file="$1"
local token
log_step "Generating auth token" >&2
local token_stderr
token_stderr=$(mktemp)
token=$("${INSTALL_DIR}/demarkus-token" generate -label "install" -paths "/**" -ops publish -tokens "$tokens_file" 2>"$token_stderr") || {
log_error "Failed to generate auth token"
cat "$token_stderr" >&2
rm -f "$token_stderr"
exit 1
}
rm -f "$token_stderr"
if [ "$PLATFORM" = "linux" ]; then
chown root:"$SERVICE_NAME" "$tokens_file"
chmod 640 "$tokens_file"
fi
echo "$token"
}
# --- TLS setup ---
setup_tls() {
local domain="$1"
log_step "Setting up TLS with Let's Encrypt"
# Install certbot if not present
if ! command -v certbot >/dev/null 2>&1; then
log_info "Installing certbot..."
if command -v apt-get >/dev/null 2>&1; then
apt-get update -qq && apt-get install -y -qq certbot >/dev/null
elif command -v dnf >/dev/null 2>&1; then
dnf install -y -q certbot >/dev/null
elif command -v yum >/dev/null 2>&1; then
yum install -y -q certbot >/dev/null
else
log_error "Could not install certbot. Install it manually and re-run."
exit 1
fi
fi
log_info "Obtaining certificate for ${domain}..."
log_info "This requires port 80 to be temporarily available."
certbot certonly --standalone -d "$domain" --non-interactive --agree-tos \
--register-unsafely-without-email || {
log_error "certbot failed. Make sure port 80 is open and the domain points to this server."
exit 1
}
fix_cert_permissions "$domain"
# Renewal setup belongs to the caller: this function is skipped entirely when
# the cert already exists, so wiring it here left re-runs with no reload hook.
log_info "TLS configured for ${domain}"
}
fix_cert_permissions() {
local domain="$1"
if [ "$PLATFORM" != "linux" ]; then return; fi
if [ ! -d "/etc/letsencrypt/live/${domain}" ]; then return; fi
chmod 750 /etc/letsencrypt/live /etc/letsencrypt/archive
chgrp "$SERVICE_NAME" /etc/letsencrypt/live /etc/letsencrypt/archive
# The private key files in archive/ also need to be group-readable
if [ -d "/etc/letsencrypt/archive/${domain}" ]; then
chgrp -R "$SERVICE_NAME" "/etc/letsencrypt/archive/${domain}"
chmod 640 "/etc/letsencrypt/archive/${domain}"/privkey*.pem
fi
log_info "Certificate permissions updated for ${SERVICE_NAME} user"
}
CERT_DEPLOY_HOOK="/etc/letsencrypt/renewal-hooks/deploy/demarkus-reload.sh"
CERT_CRON_MARKER="# demarkus-managed-renewal"
# cert_cron_pattern matches only cron entries this installer wrote: the marker,
# or the exact unmarked line older versions produced (setup_cert_renewal
# migrates those to the marker). A bare "certbot renew.*demarkus" would also
# match a user's own job that reloads demarkus.
cert_cron_pattern() {
printf '%s|certbot renew --quiet --deploy-hook "pidof demarkus-server' "$CERT_CRON_MARKER"
}
# read_crontab prints the root crontab. 0 = read it (may be empty), 1 = no
# crontab installed, 2 = the read failed. crontab -l exits non-zero for both of
# the latter, and treating a failed read as "empty" makes the usual
# read-filter-write pipeline install an empty table, destroying the user's jobs.
# Callers must never write back on 2.
read_crontab() {
local out rc
out=$(crontab -l 2>&1)
rc=$?
if [ "$rc" -eq 0 ]; then
printf '%s\n' "$out"
return 0
fi
case "$out" in
*"no crontab for"*) return 1 ;;
*) return 2 ;;
esac
}
# strip_cron_entries prints TABLE without demarkus-owned entries. grep exits 1
# when it filters everything out, which is success here, and would otherwise
# trip set -e; only a status above 1 is a real failure.
strip_cron_entries() {
local table="$1" out="" rc=0
if [ -n "$table" ]; then
out=$(printf '%s\n' "$table" | grep -Ev "$(cert_cron_pattern)") || rc=$?
if [ "$rc" -gt 1 ]; then
return "$rc"
fi
fi
if [ -n "$out" ]; then
printf '%s\n' "$out"
fi
return 0
}
# compose_cron_table prints TABLE with demarkus-owned entries dropped and ENTRY
# appended. Filtering with grep -v '^$' instead would strip blank lines the user
# put in their own crontab.
compose_cron_table() {
local table="$1" entry="$2" kept
kept=$(strip_cron_entries "$table") || return 1
if [ -n "$kept" ]; then
printf '%s\n%s\n' "$kept" "$entry"
else
printf '%s\n' "$entry"
fi
}
# write_cert_deploy_hook installs the reload command as a certbot deploy hook.
# certbot.timer renews on its own schedule and runs only this directory, so
# without the file a timer-driven renewal leaves stale certs loaded.
# Staged through a temp file in the same directory: certbot executes whatever
# is at this path, so it must never be observable half-written.
write_cert_deploy_hook() {
local hook="$1"
local dir tmp
dir=$(dirname "$CERT_DEPLOY_HOOK")
if ! mkdir -p "$dir"; then
log_error "Could not create ${dir}; renewals will not reload the services"
exit 1
fi
if ! tmp=$(mktemp "${CERT_DEPLOY_HOOK}.XXXXXX"); then
log_error "Could not stage the certbot deploy hook in ${dir}"
exit 1
fi
if ! cat > "$tmp" << EOF
#!/bin/sh
# Managed by demarkus install.sh. Reloads the certificate holders after a
# successful renewal, whichever mechanism triggered it.
${hook}
EOF
then
rm -f "$tmp"
log_error "Could not write the certbot deploy hook"
exit 1
fi
if ! chmod 755 "$tmp" || ! mv -f "$tmp" "$CERT_DEPLOY_HOOK"; then
rm -f "$tmp"
log_error "Could not install the certbot deploy hook at ${CERT_DEPLOY_HOOK}"
exit 1
fi
}
# clear_cert_renewal drops demarkus-managed renewal wiring when this host is no
# longer Let's Encrypt backed, so a switch to custom certs or --no-tls does not
# leave a cron renewing and reloading against a cert nothing uses. Only our own
# cron line and hook path are touched; user-managed certbot config is left.
# Returns nonzero on a failed teardown but is deliberately not fatal: it runs
# after cert material is written, so aborting would leave the unit
# unregenerated — worse than a leftover entry renewing an unused cert.
clear_cert_renewal() {
if [ "$PLATFORM" != "linux" ]; then return 0; fi
local cleared=false failed=0
if [ -f "$CERT_DEPLOY_HOOK" ]; then
if rm -f "$CERT_DEPLOY_HOOK"; then
cleared=true
else
log_warn "Could not remove the stale deploy hook ${CERT_DEPLOY_HOOK}"
failed=1
fi
fi
# Capture guarded with ||: set -e aborts on a bare assignment from a command
# substitution that exits nonzero, and rc 1 (no crontab) is a normal state.
local table rc=0
table=$(read_crontab) || rc=$?
if [ "$rc" -eq 2 ]; then
# Leaving a stale entry is recoverable; rewriting from an unread table is not.
log_warn "Could not read the root crontab; leaving any stale renewal entry in place"
failed=1
elif [ "$rc" -eq 0 ] && printf '%s\n' "$table" | grep -Eq "$(cert_cron_pattern)"; then
if strip_cron_entries "$table" | crontab -; then
cleared=true
else
log_warn "Could not drop the stale certbot renewal cron entry"
failed=1
fi
fi
if [ "$cleared" = true ]; then
log_info "Removed demarkus certbot renewal wiring (no longer using Let's Encrypt)"
fi
return "$failed"
}
# report_stale_renewal names what to clean by hand after a failed teardown.
report_stale_renewal() {
log_warn "Stale demarkus renewal wiring may remain; check the root crontab for '${CERT_CRON_MARKER}' and remove ${CERT_DEPLOY_HOOK}"
}
setup_cert_renewal() {
local domain="$1"
if [ "$PLATFORM" != "linux" ]; then return; fi
local hook='pidof demarkus-server | xargs -r kill -HUP'
local cron_line="0 */12 * * * certbot renew --quiet --deploy-hook \"${hook}\" ${CERT_CRON_MARKER}"
# Never downgrade the library-aware hook back to the server-only one.
if [ ! -f "$CERT_DEPLOY_HOOK" ] || ! grep -q "demarkus-library" "$CERT_DEPLOY_HOOK"; then
write_cert_deploy_hook "$hook"
fi
# Guarded with ||: set -e aborts a bare assignment whose command substitution
# exits nonzero, and rc 1 (no root crontab yet) is the normal fresh-host case.
local table rc=0
table=$(read_crontab) || rc=$?
if [ "$rc" -eq 2 ]; then
log_error "Could not read the root crontab; refusing to rewrite it. Renewal will not reload the services"
exit 1
fi
if [ "$rc" -eq 1 ]; then table=""; fi
if printf '%s\n' "$table" | grep -q "$CERT_CRON_MARKER"; then
log_info "Certbot renewal cron already configured"
return
fi
# An unmarked entry from an older install is replaced, not duplicated, so
# hosts converge on the marker and stop relying on command matching.
local verb="Added"
if printf '%s\n' "$table" | grep -Eq "$(cert_cron_pattern)"; then
verb="Migrated"
fi
if ! compose_cron_table "$table" "$cron_line" | crontab -; then
log_error "Could not write the certbot renewal cron entry"
exit 1
fi
log_info "${verb} certbot renewal cron job (twice daily, zero-downtime reload)"
}
# setup_library_cert_renewal extends the renewal deploy-hook so certbot also
# restarts the library serving the same cert (the server reloads on SIGHUP;
# the library needs a restart). Replaces the server-only cron line.
setup_library_cert_renewal() {
if [ "$PLATFORM" != "linux" ]; then return; fi
local hook='pidof demarkus-server | xargs -r kill -HUP; systemctl try-restart demarkus-library'
# The deploy hook is rewritten even when the cron is already current: the
# server-only install may have written the server-only version of it.
write_cert_deploy_hook "$hook"
local table rc=0
table=$(read_crontab) || rc=$?
if [ "$rc" -eq 2 ]; then
log_error "Could not read the root crontab; refusing to rewrite it. Renewal will not restart the library"
exit 1
fi
if [ "$rc" -eq 1 ]; then table=""; fi
# Ours only: a user job mentioning the library must not suppress our entry.
if printf '%s\n' "$table" | grep -F "$CERT_CRON_MARKER" | grep -q "try-restart demarkus-library"; then
log_info "Certbot renewal cron already restarts the library"
return
fi
local cron_line="0 */12 * * * certbot renew --quiet --deploy-hook \"${hook}\" ${CERT_CRON_MARKER}"
if ! compose_cron_table "$table" "$cron_line" | crontab -; then
log_error "Could not update the certbot renewal cron for the library"
exit 1
fi
log_info "Certbot renewal cron now reloads the server and restarts the library"
}
setup_custom_tls() {
local cert_src="$1"
local key_src="$2"
log_step "Setting up TLS with provided certificates"
local tls_dir="${CONFIG_DIR}/tls"
mkdir -p "$tls_dir"
cp "$cert_src" "${tls_dir}/cert.pem"
cp "$key_src" "${tls_dir}/key.pem"
if [ "$PLATFORM" = "linux" ]; then
chown root:"$SERVICE_NAME" "$tls_dir" "${tls_dir}/cert.pem" "${tls_dir}/key.pem"
chmod 750 "$tls_dir"
chmod 640 "${tls_dir}/cert.pem" "${tls_dir}/key.pem"
else
chmod 700 "$tls_dir"
chmod 600 "${tls_dir}/cert.pem" "${tls_dir}/key.pem"
fi
log_info "Certificates installed to ${tls_dir}/"
}
# --- System tuning ---
setup_udp_buffers() {
if [ "$PLATFORM" != "linux" ]; then return; fi
local current
current=$(sysctl -n net.core.rmem_max 2>/dev/null || echo 0)
if [ "$current" -ge 7500000 ]; then
log_info "UDP buffer sizes already configured"
return
fi
log_info "Configuring UDP buffer sizes for QUIC..."
sysctl -w net.core.rmem_max=7500000 >/dev/null 2>&1 || true
sysctl -w net.core.wmem_max=7500000 >/dev/null 2>&1 || true
# Persist across reboots
local conf="/etc/sysctl.d/99-demarkus-quic.conf"
cat > "$conf" << 'EOF'
net.core.rmem_max=7500000
net.core.wmem_max=7500000
EOF
log_info "UDP buffer sizes set (persistent via ${conf})"
}
# --- Health check ---
verify_service_running() {
if [ "$PLATFORM" != "linux" ]; then return; fi
log_step "Verifying service is running"
sleep 2
if systemctl is-active --quiet demarkus 2>/dev/null; then
log_info "Service is running"
else
log_error "Service failed to start"
echo ""
log_info "Recent logs:"
journalctl -u demarkus -n 20 --no-pager 2>/dev/null || true
echo ""
log_info "Check full logs with: journalctl -u demarkus --no-pager"
log_info "Check service status with: systemctl status demarkus"
exit 1
fi
}
# self_dial_probe reads the world's health doc at the public domain with
# certificate verification on; one retry covers a world still settling
# after a restart.
self_dial_probe() {
local cli="$1"
local domain="$2"
if timeout 15 "$cli" "mark://${domain}/health" >/dev/null 2>&1; then
return 0
fi
sleep 2
timeout 15 "$cli" "mark://${domain}/health" >/dev/null 2>&1
}
# hosts_maps_domain reports whether a non-comment HOSTS_FILE line already
# maps the domain (exact token match, not substring).
hosts_maps_domain() {
local domain="$1"
awk -v d="$domain" '$1 !~ /^#/ { for (i = 2; i <= NF; i++) if ($i == d) found = 1 } END { exit found ? 0 : 1 }' "$HOSTS_FILE"
}
# ensure_self_dial proves this host can read its own world at the public
# domain; home NAT often cannot loop back, stranding same-host dialers.
# On failure, pin the domain to loopback in HOSTS_FILE and re-probe.
ensure_self_dial() {
local domain="$1"
if [ "$PLATFORM" != "linux" ]; then return; fi
local cli="${INSTALL_DIR}/demarkus"
if [ ! -x "$cli" ]; then
log_warn "Client binary not found at ${cli}; skipping the self-dial check for ${domain}"
return
fi
# Fail closed: an unbounded probe could hang on the very black-holed
# dial this check exists to detect.
if ! command -v timeout >/dev/null 2>&1; then
log_error "timeout (coreutils) is required for the self-dial check; install it and re-run"
exit 1
fi
log_step "Checking this host can read its own world (mark://${domain})"
if self_dial_probe "$cli" "$domain"; then
log_info "Self-dial OK"
return
fi
if hosts_maps_domain "$domain"; then
log_error "mark://${domain} is unreadable from this host even though ${HOSTS_FILE} already maps ${domain}."
log_error "Check the world service (journalctl -u demarkus --no-pager), UDP 6309, and that the TLS certificate matches ${domain}"
exit 1
fi
log_warn "This host cannot reach its own world at mark://${domain} (likely hairpin NAT)"
log_info "Pinning ${domain} to loopback in ${HOSTS_FILE} so same-host components dial locally"
# A hosts file without a trailing newline would merge the new entry into
# its last line; normalize first.
if [ -s "$HOSTS_FILE" ] && [ -n "$(tail -c 1 "$HOSTS_FILE")" ]; then
if ! printf '\n' >> "$HOSTS_FILE"; then
log_error "Could not update ${HOSTS_FILE}"
exit 1
fi
fi
if ! printf '127.0.0.1 %s # demarkus: self-dial (hairpin NAT workaround)\n' "$domain" >> "$HOSTS_FILE"; then
log_error "Could not update ${HOSTS_FILE}"
exit 1
fi
if ! self_dial_probe "$cli" "$domain"; then
log_error "mark://${domain} is still unreadable after pinning it to loopback."
log_error "Check the world service (journalctl -u demarkus --no-pager), UDP 6309, and that the TLS certificate matches ${domain}"
exit 1
fi
log_info "Self-dial OK via loopback; certificate verification stays on"
}
# --- Service management ---
# server_exe_path prints the executable behind a pid, however it was started.
# Linux reads /proc; macOS ps prints the full path as the command name.
server_exe_path() {
local pid="$1" exe=""
# -L, not -e: the link of a replaced or unlinked binary dangles.
if [ -L "/proc/${pid}/exe" ]; then
exe=$($SUDO readlink "/proc/${pid}/exe" 2>/dev/null || true)
exe="${exe% (deleted)}"
else
exe=$(ps -o comm= -p "$pid" 2>/dev/null || true)
fi
printf '%s\n' "$exe"
}
# resolved_path prints path with its directory symlinks resolved.
resolved_path() {
local dir
dir=$(cd "$(dirname "$1")" 2>/dev/null && pwd -P) || { printf '%s\n' "$1"; return 0; }
printf '%s/%s\n' "$dir" "$(basename "$1")"
}
# installed_server_pids lists servers running the INSTALL_DIR binary, by
# executable rather than argv[0]: a PATH start has a bare name, and a name
# match alone would hit the plugin managed server under ~/.demarkus/bin.
installed_server_pids() {
local want pid exe
want=$(resolved_path "${INSTALL_DIR}/demarkus-server")
for pid in $( { pgrep -x demarkus-server; pgrep -f '(^|/)demarkus-server( |$)'; } 2>/dev/null | sort -un); do
exe=$(server_exe_path "$pid")
if [ -z "$exe" ]; then
# Gone between pgrep and the lookup is fine; alive and unreadable is
# not: skipping it could replace the binary under a running server.
ps -p "$pid" >/dev/null 2>&1 || continue
log_error "Cannot inspect process ${pid}; cannot tell whether it runs ${want}"
return 1
fi
if [ "$(resolved_path "$exe")" = "$want" ]; then
echo "$pid"
fi
done
}
# stop_installed_server ends leftovers the service manager did not stop:
# TERM, then KILL. Returns 1 when one survives both or cannot be inspected.
stop_installed_server() {
local pids wait_count=0
pids=$(installed_server_pids) || return 1
[ -n "$pids" ] || return 0
# shellcheck disable=SC2086 # a pid list, split on purpose
$SUDO kill $pids 2>/dev/null || true
while [ "$wait_count" -lt "${SERVER_WAIT_SECONDS:-5}" ]; do
pids=$(installed_server_pids) || return 1
[ -n "$pids" ] || return 0
sleep 1
wait_count=$((wait_count + 1))
done
# shellcheck disable=SC2086 # a pid list, split on purpose
$SUDO kill -9 $pids 2>/dev/null || true
sleep 1
pids=$(installed_server_pids) || return 1
[ -z "$pids" ]
}
# verify_server_running needs two good probes a second apart, so a server
# that starts and dies at once does not pass.
verify_server_running() {
local tries=0 streak=0 pids
while [ "$tries" -lt "${SERVER_WAIT_SECONDS:-10}" ]; do
if [ "$PLATFORM" = "linux" ]; then
if $SUDO systemctl is-active --quiet demarkus; then streak=$((streak + 1)); else streak=0; fi
else
# A failed inspection is not proof the server runs.
if pids=$(installed_server_pids) && [ -n "$pids" ]; then streak=$((streak + 1)); else streak=0; fi
fi
[ "$streak" -ge 2 ] && return 0
sleep 1
tries=$((tries + 1))
done
return 1
}
setup_systemd() {
local content_root="$1"
local tokens_file="$2"
local cert_path="${3:-}"
local key_path="${4:-}"
log_step "Setting up systemd service"
# Ensure content_root is absolute for both DEMARKUS_ROOT and ReadWritePaths
content_root=$(readlink -f "$content_root" 2>/dev/null || echo "$content_root")
local env_lines="Environment=DEMARKUS_ROOT=${content_root}
Environment=DEMARKUS_TOKENS=${tokens_file}"
if [ -n "$cert_path" ] && [ -n "$key_path" ]; then
env_lines="${env_lines}
Environment=DEMARKUS_TLS_CERT=${cert_path}
Environment=DEMARKUS_TLS_KEY=${key_path}"
fi
# ProtectHome=yes makes /home inaccessible — skip it if content root is there
local protect_home="ProtectHome=yes"
case "$content_root" in