From a26ad7a0d0a180c05b2993221fb02169c9f132bb Mon Sep 17 00:00:00 2001 From: Daniyar Ennanov <21172041+limeflash@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:02:04 +0300 Subject: [PATCH] e2e: the stand of the relay leg automaton scripts/e2e/relay-leg.sh builds one panel, an entry and two exits in private network namespaces (documentation and RFC 1918 ranges only), with IPv4 and IPv6 on the entry-exit links and a filter in between that drops either family per relay on demand. It runs Hysteria2 UDP relays and covers the proposal, accept, reject, stale, rollback and pinned-leg cases of the relay_leg automaton; --long adds a lane for mode auto. Co-Authored-By: Claude Sonnet 5.5 --- scripts/e2e/relay-leg.sh | 950 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 950 insertions(+) create mode 100644 scripts/e2e/relay-leg.sh diff --git a/scripts/e2e/relay-leg.sh b/scripts/e2e/relay-leg.sh new file mode 100644 index 00000000..c0de87c2 --- /dev/null +++ b/scripts/e2e/relay-leg.sh @@ -0,0 +1,950 @@ +#!/usr/bin/env bash +# The relay-leg automaton on real processes: a real panel, real node agents, real Hysteria2 clients, and a filter between the entry +# and the exits that drops the IPv4 or the IPv6 packets of one relay on demand. What it proves: a relay on leg "auto" whose IPv4 +# entry->exit leg is dead while the IPv6 leg passes gets a relay_leg proposal "ipv4 -> ipv6"; the panel only proposes in the default +# mode suggest; accepting it moves the relay to IPv6 (pending -> active), the new leg is checked and people's traffic flows; both +# families dead gives no proposal; a relay pinned to a family is left alone; a proposal that lost its ground goes stale; "not now" +# holds the panel back; and a move whose new leg turns out dead is undone by the applier. The code under test is internal/panel/store +# relay_leg.go, health relay_leg_proposals.go, app proposal_relay_leg.go and the ProposalService (docs/en/guide/relays.md, "Moving the +# leg by itself"). +# +# MSYS_NO_PATHCONV=1 wsl.exe -d Ubuntu -u root --exec bash scripts/e2e/relay-leg.sh [options] (from the repo root) +# +# Options: +# --long also lane L: the automation mode "auto" for one relay, which moves by itself only after the other family passed two probes +# 30 minutes apart (no time seam exists in the panel); adds about 40 minutes +# --hold after the stand and the relays are up, wait (up to 2 hours) until the file $WORK/release exists, for poking at the stand with +# nsenter; the inner pid and the work directory are printed +# --keep keep the work directory (logs, configs) +# +# A run without --long takes about 25 minutes. The return to IPv4 of a relay with leg_return needs 6 hours on IPv6 and three probes of +# IPv4 half an hour apart: it is not covered (the run only checks that the relay on IPv6 with leg_return gets IPv4 probed and that no +# leg_return proposal appears early). Ending the run (an exit, INT, TERM, HUP) stops every process of the run, marked by MG_RLEG_MARK in +# its environment, and removes the work directory. +# +# Isolation: like scripts/e2e/bridge.sh. The script builds first, then `unshare -n -m` gives it a private network and mount namespace; +# the panel, the nodes, the client, the filter and the "internet" are network namespaces inside it (a private /run/netns). Nothing +# outside is visible or touched. Addresses: RFC 1918 links and documentation ranges only (203.0.113.0/24 and 2001:db8::/32 the nodes, +# 198.51.100.0/24 the "internet"); no packet leaves. +# +# TOPOLOGY (a /30 and a /64 link per line, "flt" is the filter, a router that sees both ways between the entry and the exits): +# +# cli -- ent -- flt -- ext -- net ent: the entry "in the country" (203.0.113.30, 2001:db8:1::1) +# \-- ext2 -- net ext: the exit "abroad" (203.0.113.10, 2001:db8:2::2), ext2: the third node that sends the +# pan -- ent, ext, ext2 path probes (203.0.113.11, 2001:db8:3::2); pan: the panel (10.88.100.1); net: the "internet" +# +# THE LANES: every lane is one relay (one Hysteria2 server of ext on its own UDP port) and the filter's faults are per lane, by the +# port and the family, so the scenarios run side by side and the run waits for the panel once: +# G auto, never touched: the control, no proposal and no probe of the other family +# A auto, leg_return on: IPv4 dead, IPv6 alive: the proposal, nothing moves in suggest, then accepted: the move, the traffic +# B auto: both families dead: a problem, no proposal, the automation view says no_target +# C pinned ipv4 under the IPv4 failure; D pinned ipv6 (the failure does not touch it): the panel leaves both alone +# E auto: IPv6 dies after the proposal and before it is accepted: the applier undoes the move (leg_failed) +# F auto: IPv4 comes back after the proposal: the proposal goes stale +# H auto: the owner rejects the proposal ("not now"): the panel holds back +set -Eeuo pipefail +SELF=$(readlink -f "$0") +ROOT=${MG_RLEG_ROOT:-$(cd "$(dirname "$SELF")/../.." && pwd)} +ARGS=("$@") + +LONG="" KEEP="" HOLD="" +while [ $# -gt 0 ]; do + case $1 in + --long) LONG=1 ;; + --hold) HOLD=1 ;; + --keep) KEEP=1 ;; + -h|--help) sed -n '2,/^set -E/p' "$SELF" | sed 's/^# \{0,1\}//' | head -n -1; exit 0 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac + shift +done + +if [ "$(uname -s)" != Linux ] || [ "$(id -u)" != 0 ]; then + if ! command -v wsl.exe >/dev/null 2>&1; then + echo "scripts/e2e/relay-leg.sh needs root on Linux (or WSL on Windows: wsl.exe was not found)" >&2 + exit 2 + fi + distro=${WSL_DISTRO:-Ubuntu} + here=$(pwd -W 2>/dev/null || pwd) + repo=$(MSYS_NO_PATHCONV=1 wsl.exe -d "$distro" -u root wslpath -a "$here" | tr -d '\r') + MSYS_NO_PATHCONV=1 exec wsl.exe -d "$distro" -u root -- bash "$repo/scripts/e2e/relay-leg.sh" "${ARGS[@]}" +fi + +for tool in go curl jq python3 openssl nft ip mount mountpoint unshare setsid ss sed awk sha256sum tcpdump; do + command -v "$tool" >/dev/null || { echo "missing tool: $tool" >&2; exit 2; } +done + +# ---------------------------------------------------------------- outer: build, then re-run in a private namespace + +if [ "${MG_RLEG_INNER:-}" != 1 ]; then + # No run of this script may be left over: look for the marker every process of a run carries. + left="" + for d in /proc/[0-9]*; do + [ -r "$d/environ" ] || continue + if { tr '\0' '\n' <"$d/environ" | grep -q '^MG_RLEG_MARK='; } 2>/dev/null; then left="$left ${d#/proc/}"; fi + done + if [ -n "$left" ]; then + echo "a run of relay-leg.sh is still alive (pids:$left); stop it first, nothing was started" >&2 + exit 2 + fi + WORK=$(mktemp -d /tmp/mg-rleg.XXXXXX) + chmod 700 "$WORK" + mkdir -p "$WORK/bin" + MARK=mgrl$$.$RANDOM + CHILD="" + sweep() { # : every process of this run, by the marker in its environment + local d pid + for d in /proc/[0-9]*; do + pid=${d#/proc/} + [ "$pid" != "$$" ] || continue + [ -r "$d/environ" ] || continue + if { tr '\0' '\n' <"$d/environ" | grep -qx "MG_RLEG_MARK=$MARK"; } 2>/dev/null; then kill "-$1" "$pid" 2>/dev/null || true; fi + done + } + outer_end() { + local rc=$? i + trap - EXIT INT TERM HUP + if [ -n "$CHILD" ] && kill -0 "$CHILD" 2>/dev/null; then + kill -TERM "$CHILD" 2>/dev/null || true + for ((i = 0; i < 100; i++)); do kill -0 "$CHILD" 2>/dev/null || break; sleep 0.1; done + fi + sweep TERM + sleep 0.5 + sweep KILL + if [ -z "$KEEP" ]; then case "$WORK" in /tmp/mg-rleg.*) rm -rf -- "$WORK";; esac; else echo "work directory kept: $WORK"; fi + exit "$rc" + } + trap outer_end EXIT + trap 'exit 143' INT TERM HUP + export GOTOOLCHAIN=${GOTOOLCHAIN:-auto} CGO_ENABLED=0 GOFLAGS="${GOFLAGS:--buildvcs=false -p=2}" + cd "$ROOT" + echo '[relay-leg] building the panel, the agent and the helpers' + go build -o "$WORK/bin/mistgate" ./cmd/mistgate + go build -o "$WORK/bin/mistgate-node" ./cmd/mistgate-node + go build -o "$WORK/bin/tlsdest" ./scripts/e2e/tlsdest + go build -o "$WORK/bin/bridgetool" ./scripts/e2e/bridgetool + # The Hysteria2 client, built from source and cached (the recipe of scripts/e2e-wsl.sh: the app module's go.mod has replace + # directives, so a scratch module requires the app and pins core and extras to the same tag). + CACHE=${MG3_TEST_CACHE:-$HOME/.cache/mistgate-tests} + HYV=${HYV:-v2.13.0} HYM=github.com/apernet/hysteria + if [ ! -x "$CACHE/hysteria-$HYV" ]; then + mkdir -p "$CACHE" + tmp=$(mktemp -d "$CACHE/hy-build.XXXXXX") + ( + cd "$tmp" + go mod init hyclient >/dev/null 2>&1 + go mod edit -go="$(sed -n 's/^toolchain go//p' "$ROOT/go.mod")" -require="$HYM/app/v2@$HYV" -replace="$HYM/core/v2=$HYM/core/v2@$HYV" -replace="$HYM/extras/v2=$HYM/extras/v2@$HYV" + GOFLAGS="-mod=mod -buildvcs=false" go build -trimpath -o "$tmp/hysteria" "$HYM/app/v2" + ) >"$WORK/build-hysteria.log" 2>&1 && mv "$tmp/hysteria" "$CACHE/hysteria-$HYV" || { tail -n 5 "$WORK/build-hysteria.log"; rm -rf "$tmp"; echo "building the hysteria client failed" >&2; exit 2; } + rm -rf "$tmp" + fi + cp "$CACHE/hysteria-$HYV" "$WORK/bin/hysteria" + chmod 755 "$WORK" + env MG_RLEG_INNER=1 MG_RLEG_WORK="$WORK" MG_RLEG_KEEP="$KEEP" MG_RLEG_MARK="$MARK" unshare -n -m -- bash "$SELF" "${ARGS[@]}" & + CHILD=$! + rc=0 + while kill -0 "$CHILD" 2>/dev/null; do wait "$CHILD" && rc=0 || rc=$?; done + exit "$rc" +fi + +# ---------------------------------------------------------------- inner: everything below runs in the private namespace + +WORK=${MG_RLEG_WORK:?missing work directory} +KEEP=${MG_RLEG_KEEP:-} +BIN=$WORK/bin +T0=$(date +%s) +PFX=rlg$$ +PIDS=() RESULTS=() FAILED=0 COOKIE="" TOTP_SECRET="" OWNER_STEP=-1 OWNER_STEPUP_UNTIL=0 STEP=start SCN=stand +PANEL_IP=10.88.100.1 +ENT_IP=203.0.113.30 EXT_IP=203.0.113.10 EXT2_IP=203.0.113.11 FAR=198.51.100.100 PROBE=198.51.100.101 +ADMIN=http://127.0.0.1:8081 PUBLIC=https://$PANEL_IP:8443 +declare -A NODE_ID=() NODE_NS=() NODE_ADDR=() + +say() { printf '[%4ds] %s\n' $(($(date +%s) - T0)) "$*"; } +die() { say "FAIL $* (step: $STEP)"; RESULTS+=("FAIL|setup|stand|$*"); exit 1; } +alive() { local state; state=$(ps -o stat= -p "${1:-0}" 2>/dev/null) && [ -n "$state" ] && [ "${state:0:1}" != Z ]; } +stop_pid() { + local pid=$1 i + alive "$pid" || { wait "$pid" 2>/dev/null || true; return 0; } + kill -TERM "$pid" 2>/dev/null || true + for ((i = 0; i < 50; i++)); do alive "$pid" || break; sleep 0.1; done + alive "$pid" && kill -KILL "$pid" 2>/dev/null || true + wait "$pid" 2>/dev/null || true +} + +# rec : one row of the final table +rec() { + RESULTS+=("$1|$2|$3|$4") + say "$1 $2 / $3: $4" + [ "$1" != FAIL ] || FAILED=1 +} +ok() { rec PASS "$SCN" "$1" "$2"; } +bad() { rec FAIL "$SCN" "$1" "$2"; } + +table() { + local row n=0 + printf '\n%-5s %-14s %-8s %s\n' result scenario cell detail + printf '%-5s %-14s %-8s %s\n' ----- -------------- -------- ------ + for row in "${RESULTS[@]}"; do + IFS='|' read -r r s c d <<<"$row" + printf '%-5s %-14s %-8s %s\n' "$r" "$s" "$c" "$d" + n=$((n + 1)) + done + printf '\n%d rows: %d PASS, %d FAIL, %d SKIP/NOTE (not checked or only noted, the reason is in the row)\n' "$n" \ + "$(printf '%s\n' "${RESULTS[@]}" | grep -c '^PASS|' || true)" "$(printf '%s\n' "${RESULTS[@]}" | grep -c '^FAIL|' || true)" \ + "$(printf '%s\n' "${RESULTS[@]}" | grep -c '^\(SKIP\|NOTE\)|' || true)" +} + +cleanup() { + local rc=$? i + trap - EXIT INT TERM HUP ERR + set +e + for ((i = ${#PIDS[@]} - 1; i >= 0; i--)); do stop_pid "${PIDS[$i]}"; done + if [ "$rc" != 0 ] && [ -z "$KEEP" ]; then + for f in "$WORK"/panel.log "$WORK"/node-*.log; do + [ -s "$f" ] || continue + echo "--- tail $(basename "$f")" + tail -n 12 "$f" | cut -c1-300 + done + fi + if [ -n "$KEEP" ]; then say "work directory kept: $WORK"; else case "$WORK" in /tmp/mg-rleg.*) rm -rf -- "$WORK" ;; esac; fi + table + say "finished in $(($(date +%s) - T0)) s: $([ "$rc" = 0 ] && [ "$FAILED" = 0 ] && echo ALL-PASS || echo FAILED)" + [ "$rc" != 0 ] || [ "$FAILED" = 0 ] || rc=1 + exit "$rc" +} +trap cleanup EXIT +trap 'exit 130' INT TERM HUP +trap 'say "unexpected error at line $LINENO (step: $STEP)"' ERR + +# ---------------------------------------------------------------- namespaces, links, routes, the filter + +mount --make-rprivate /run 2>/dev/null || true +mkdir -p /run/netns +mountpoint -q /run/netns || mount -t tmpfs -o mode=755 tmpfs /run/netns +mount --make-rprivate /run/netns +mkdir -p /etc/netns && mount -t tmpfs tmpfs /etc/netns # the hosts files `ip netns exec` puts over /etc/hosts: private, gone with the run +ns() { printf '%s-%s' "$PFX" "$1"; } +nsx() { local n=$1; shift; ip netns exec "$(ns "$n")" "$@"; } +ipa() { local n=$1; shift; ip -n "$(ns "$n")" "$@"; } +for n in pan ent ext ext2 cli net flt; do + ip netns add "$(ns "$n")" + ip -n "$(ns "$n")" link set lo up + nsx "$n" sysctl -qw net.ipv6.conf.all.disable_ipv6=0 net.ipv6.conf.default.disable_ipv6=0 2>/dev/null || true +done +nsx flt sysctl -qw net.ipv4.ip_forward=1 net.ipv6.conf.all.forwarding=1 +nsx net sysctl -qw net.ipv4.ip_forward=1 + +SEQ=0 +link() { # <10.88.N> [<2001:db8:N>]: a gets .1 (::1) and b gets .2 (::2); the interfaces are rla in a and rlb in b + local a=$1 b=$2 net=$3 v6=${4:-} + SEQ=$((SEQ + 1)) + ip link add "rla$SEQ" type veth peer name "rlb$SEQ" + ip link set "rla$SEQ" netns "$(ns "$a")" + ip link set "rlb$SEQ" netns "$(ns "$b")" + ipa "$a" addr add "$net.1/30" dev "rla$SEQ" + ipa "$b" addr add "$net.2/30" dev "rlb$SEQ" + if [ -n "$v6" ]; then # nodad: the address is stable at once (the doctor skips a tentative one) + ipa "$a" addr add "$v6::1/64" dev "rla$SEQ" nodad + ipa "$b" addr add "$v6::2/64" dev "rlb$SEQ" nodad + fi + ipa "$a" link set "rla$SEQ" up + ipa "$b" link set "rlb$SEQ" up +} +link ent flt 10.88.1 2001:db8:1 # rla1 (ent) rlb1 (flt) +link flt ext 10.88.2 2001:db8:2 # rla2 (flt) rlb2 (ext) +link flt ext2 10.88.3 2001:db8:3 # rla3 (flt) rlb3 (ext2) +link pan ent 10.88.5 +link pan ext 10.88.6 +link pan ext2 10.88.7 +link cli ent 10.88.9 +link ext net 10.88.11 +link ext2 net 10.88.12 + +# The filter's interfaces: the entry's side is rlb1, the exits' sides rla2 and rla3. +ipa ent addr add "$ENT_IP/32" dev lo +ipa ext addr add "$EXT_IP/32" dev lo +ipa ext2 addr add "$EXT2_IP/32" dev lo +ipa pan addr add "$PANEL_IP/32" dev lo +ipa net addr add "$FAR/32" dev lo +ipa net addr add "$PROBE/32" dev lo + +route() { local n=$1; shift; ipa "$n" route add "$@"; } +# Every node sources its connections from its own public address, as a host with one public address does. +route ent default via 10.88.1.2 src "$ENT_IP" +route ent "$PANEL_IP/32" via 10.88.5.1 src "$ENT_IP" +for who in ext:$EXT_IP:10.88.2.1:10.88.6.1:10.88.11.2 ext2:$EXT2_IP:10.88.3.1:10.88.7.1:10.88.12.2; do + IFS=: read -r n me flt_gw pan_gw net_gw <<<"$who" + route "$n" "$ENT_IP/32" via "$flt_gw" src "$me" + route "$n" "$PANEL_IP/32" via "$pan_gw" src "$me" + route "$n" 198.51.100.0/24 via "$net_gw" src "$me" + # a DNAT relay masquerades to the address of the entry's link; the exit answers from its own public address (the server's UDP + # socket answers from the address the route picks, and the entry's NAT only turns back what comes from the exit's address) + route "$n" 10.88.1.0/30 via "$flt_gw" src "$me" +done +route pan "$ENT_IP/32" via 10.88.5.2 src "$PANEL_IP" +route pan "$EXT_IP/32" via 10.88.6.2 src "$PANEL_IP" +route pan "$EXT2_IP/32" via 10.88.7.2 src "$PANEL_IP" +route cli "$ENT_IP/32" via 10.88.9.2 src 10.88.9.1 +route flt "$ENT_IP/32" via 10.88.1.1 +route flt "$EXT_IP/32" via 10.88.2.2 +route flt "$EXT2_IP/32" via 10.88.3.2 +route net "$EXT_IP/32" via 10.88.11.1 +route net "$EXT2_IP/32" via 10.88.12.1 +# IPv6: every node has a global address on its link to the filter and a default route through it, which is what the doctor reads +# (the interface of ::/0, its stable addresses) and what the panel then calls the node's IPv6 address. +ipa ent -6 route add default via 2001:db8:1::2 dev rla1 +ipa ext -6 route add default via 2001:db8:2::1 dev rlb2 +ipa ext2 -6 route add default via 2001:db8:3::1 dev rlb3 + +# ---- the lanes and the faults of the filter: a relay's packets from the entry to the exit are the UDP datagrams to its server's port, +# so a fault is "drop the IPv4 (or the IPv6) UDP of this port that comes from the entry". Named counters count what the entry offered +# (seen) and what was dropped (drop), per port and family; they live as long as the table, only the rules are replaced. +LANES=(G A B C D E F H) +[ -z "$LONG" ] || LANES+=(L) +declare -A PORT_OF=([G]=4431 [A]=4432 [B]=4433 [C]=4434 [D]=4435 [E]=4436 [F]=4437 [H]=4438 [L]=4439) +declare -A LEG_OF=([G]=auto [A]=auto [B]=auto [C]=ipv4 [D]=ipv6 [E]=auto [F]=auto [H]=auto [L]=auto) +declare -A DEAD4=() DEAD6=() RID=() INB=() SOCKS_OF=() +flt_init() { + local lane decl="" c + for lane in "${LANES[@]}"; do + for c in seen4 seen6 drop4 drop6; do decl+=" counter ${c}_${PORT_OF[$lane]} {}"$'\n'; done + done + nsx flt nft -f - < +fault() { + local fam=$1 on=$2 lane + shift 2 + for lane in "$@"; do + if [ "$on" = on ]; then + if [ "$fam" = v4 ]; then DEAD4[$lane]=1; else DEAD6[$lane]=1; fi + else + if [ "$fam" = v4 ]; then unset 'DEAD4[$lane]'; else unset 'DEAD6[$lane]'; fi + fi + done + flt_apply + say "filter: IPv${fam#v} UDP $on for lane(s) $*" +} +cnt() { nsx flt nft list counter inet relayleg "$1" | awk '/packets/ {print $2}'; } # +flt_init +flt_apply + +# ---------------------------------------------------------------- processes + +spawn_in() { # + local n=$1 log=$2 + shift 2 + ip netns exec "$(ns "$n")" setsid "$@" >>"$log" 2>&1 : 0 when it held in time, 1 when not + local n=$1 what=$2 i + shift 2 + for ((i = 0; i < n; i++)); do + if "$@" >/dev/null 2>&1; then return 0; fi + sleep 1 + done + say "timeout after ${n} s waiting for: $what" + return 1 +} +listening() { [ -n "$(nsx "$1" ss -Hltn "sport = :$2")" ]; } # +need() { # : wait_for, and die when it did not hold + local n=$1 what=$2 + shift 2 + wait_for "$n" "$what" "$@" || die "timeout waiting for $what" +} +retry() { # : the panel's port checks take the check lock of a node for a few seconds + local n=$1 i out + shift + for ((i = 1; i <= n; i++)); do + if out=$("$@" 2>&1); then printf '%s' "$out"; return 0; fi + sleep 8 + done + printf '%s' "$out" + return 1 +} + +# ---------------------------------------------------------------- the far side and the sites the panel's probes ask + +start_far() { + spawn_in net "$WORK/far.log" "$BIN/bridgetool" serve -listen "$FAR:8080" + spawn_in net "$WORK/tlsdest.log" "$BIN/tlsdest" -listen "$FAR:8443" -names www.example.com,www.example.net,www.example.org -cert "$WORK/tlsdest.pem" + need 20 "the certificate of the tls helper" test -s "$WORK/tlsdest.pem" + need 10 "the far server" listening net 8080 + # What the panel's own client-eye round asks through a relay (generate_204, the trace, a 64 KiB download) lives on real names of the + # internet: here the exits resolve those names to $PROBE (a hosts file of their namespaces) and the panel trusts that site's certificate. + spawn_in net "$WORK/probesite.log" "$BIN/bridgetool" probesite -listen "$PROBE:443" -cert "$WORK/probesite.pem" + need 20 "the probe site" listening net 443 + cat "$WORK/tlsdest.pem" "$WORK/probesite.pem" >"$WORK/trust.pem" + local n + for n in ext ext2; do + mkdir -p "/etc/netns/$(ns "$n")" + printf '127.0.0.1 localhost\n%s www.gstatic.com www.cloudflare.com speed.cloudflare.com\n' "$PROBE" >"/etc/netns/$(ns "$n")/hosts" + done +} + +# ---------------------------------------------------------------- the panel + +api() { # [JSON]: the admin API (mistgate.admin.v1) + local out code body=${2:-} + [ -n "$body" ] || body='{}' + out=$(nsx pan curl -skS -m 120 -w $'\n%{http_code}' -X POST "$ADMIN/api/mistgate.admin.v1.$1" \ + -H 'Content-Type: application/json' ${COOKIE:+-H "Cookie: $COOKIE"} -d "$body") || return 1 + code=${out##*$'\n'} + out=${out%$'\n'*} + if [ "$code" != 200 ]; then + echo "api $1 -> HTTP $code: $(jq -r '[.code, .message] | map(select(. != null)) | join(" ")' <<<"$out" 2>/dev/null || echo "$out")" >&2 + return 1 + fi + printf '%s' "$out" +} +papi() { # [JSON]: the proposal API (mistgate.proposal.v1.ProposalService) + local out code body=${2:-} + [ -n "$body" ] || body='{}' + out=$(nsx pan curl -skS -m 60 -w $'\n%{http_code}' -X POST "$ADMIN/api/mistgate.proposal.v1.ProposalService/$1" \ + -H 'Content-Type: application/json' ${COOKIE:+-H "Cookie: $COOKIE"} -d "$body") || return 1 + code=${out##*$'\n'} + out=${out%$'\n'*} + if [ "$code" != 200 ]; then + echo "proposal api $1 -> HTTP $code: $(jq -r '[.code, .message] | map(select(. != null)) | join(" ")' <<<"$out" 2>/dev/null || echo "$out")" >&2 + return 1 + fi + printf '%s' "$out" +} + +totp_code() { + python3 - "$TOTP_SECRET" <<'PY' +import base64, hashlib, hmac, struct, sys, time +k = base64.b32decode(sys.argv[1].upper() + "=" * ((8 - len(sys.argv[1]) % 8) % 8)) +h = hmac.new(k, struct.pack(">Q", int(time.time()) // 30), hashlib.sha1).digest(); o = h[-1] & 15 +print("%06d" % ((struct.unpack(">I", h[o:o + 4])[0] & 0x7fffffff) % 1000000)) +PY +} +owner_stepup() { + local now step code result + now=$(date +%s) + [ "$now" -lt "$OWNER_STEPUP_UNTIL" ] && return 0 + step=$((now / 30)) + while [ "$step" -le "$OWNER_STEP" ]; do sleep 1; now=$(date +%s); step=$((now / 30)); done + code=$(totp_code) + result=$(api AuthService/FinishStepUp "$(jq -nc --arg c "$code" '{totpCode:$c}')") + OWNER_STEP=$step + OWNER_STEPUP_UNTIL=$(jq -r '.stepUpUntilUnix // 0' <<<"$result") +} + +panel_serve() { + spawn_in pan "$WORK/panel.log" env SSL_CERT_FILE="$WORK/trust.pem" "$BIN/mistgate" serve --data-dir "$WORK/data" --listen "$PANEL_IP:8443" \ + --admin-listen 127.0.0.1:8081 --tls-cert "$WORK/panel.crt" --tls-key "$WORK/panel.key" --agent-addr "$PANEL_IP:8443" + PANEL_PID=$LAST_PID +} +start_panel() { + openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 2 -subj /CN=relay-leg-panel \ + -addext "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:$PANEL_IP" -keyout "$WORK/panel.key" -out "$WORK/panel.crt" 2>/dev/null + local out token begin ceremony login=leg-admin password + out=$(nsx pan "$BIN/mistgate" setup --data-dir "$WORK/data" --public-url "$PUBLIC" --admin-listen 127.0.0.1:8081) + token=$(sed -n 's|^Setup link: .*/setup#\(.*\)$|\1|p' <<<"$out") + [ -n "$token" ] || die "panel setup returned no setup token" + panel_serve + need 45 "the panel listener" nsx pan curl -skS -m 3 -o /dev/null "$PUBLIC/" + password=$(openssl rand -hex 16) + begin=$(api AuthService/BeginSetup "$(jq -nc --arg t "$token" --arg l "$login" --arg p "$password" \ + '{setupToken:$t,displayName:"Relay leg lab",method:"SETUP_METHOD_PASSWORD",login:$l,password:$p}')") || die "BeginSetup failed" + ceremony=$(jq -r .ceremonyId <<<"$begin") + TOTP_SECRET=$(jq -r .totpSecret <<<"$begin") + nsx pan curl -skS -m 30 -D "$WORK/setup.hdr" -o /dev/null -X POST "$ADMIN/api/mistgate.admin.v1.AuthService/FinishSetup" \ + -H 'Content-Type: application/json' -d "$(jq -nc --arg t "$token" --arg c "$ceremony" --arg code "$(totp_code)" \ + '{setupToken:$t,ceremonyId:$c,totpCode:$code}')" + grep -q '^HTTP/[0-9.]* 200' "$WORK/setup.hdr" || die "first-admin setup failed" + COOKIE=$(sed -n 's/^[Ss]et-[Cc]ookie: \(\(__Host-\)\{0,1\}sid=[^;]*\).*/\1/p' "$WORK/setup.hdr" | tr -d '\r') + [ -n "$COOKIE" ] || die "no session cookie" + OWNER_STEP=$(($(date +%s) / 30)) + OWNER_STEPUP_UNTIL=$(api AuthService/Me | jq -r '.stepUpUntilUnix // 0') + say "the panel is up in $(ns pan)" + # The rounds of a relay run every 300 s by default: the shortest the panel allows is 60 s (health.check_interval_s, read at every + # pass), which is what a stand that waits for "two failed rounds" can afford. Written into the stand's own database. + python3 - "$WORK/data/mistgate.db" <<'PY' || die "could not set the check interval" +import sqlite3, sys +c = sqlite3.connect(sys.argv[1], timeout=30) +c.execute("INSERT INTO setting (k, v) VALUES ('health.check_interval_s', '60') ON CONFLICT(k) DO UPDATE SET v = excluded.v") +c.commit() +PY +} + +# ---------------------------------------------------------------- the nodes + +node_cmd() { # : the agent, in its namespace, with its own sysctl.d and journald drop-in on private tmpfs + local name=$1 + spawn_in "${NODE_NS[$name]}" "$WORK/node-$name.log" env SSL_CERT_FILE="$WORK/tlsdest.pem" bash -c \ + 'mkdir -p /etc/systemd/journald.conf.d; mount -t tmpfs tmpfs /etc/sysctl.d; mount -t tmpfs tmpfs /etc/systemd/journald.conf.d; exec "$@"' _ \ + "$BIN/mistgate-node" run --state-dir "$WORK/state/$name" +} +make_node() { #
+ local name=$1 address=$2 country=$3 n=$4 out line + NODE_NS[$name]=$n NODE_ADDR[$name]=$address + out=$(api NodeService/CreateEnrollment "$(jq -nc --arg n "$name" --arg a "$address" --arg c "$country" '{name:$n,address:$a,countryCode:$c}')") \ + || die "CreateEnrollment failed for $name" + NODE_ID[$name]=$(jq -r .node.id <<<"$out") + line=$(jq -r .installCommand <<<"$out" | grep -m1 ' enroll ') + flag() { sed -n "s/.* --$1 \([^ ]*\).*/\1/p" <<<"$line"; } + mkdir -p "$WORK/state/$name" + SSL_CERT_FILE="$WORK/tlsdest.pem" nsx "$n" "$BIN/mistgate-node" enroll --panel "$(flag panel)" --sni "$(flag sni)" \ + --ca-sha256 "$(flag ca-sha256)" --token "$(flag token)" --state-dir "$WORK/state/$name" >"$WORK/enroll-$name.log" 2>&1 \ + || die "enrollment of $name failed: $(tail -n 3 "$WORK/enroll-$name.log")" + node_cmd "$name" +} +node_online() { api NodeService/ListNodes '{}' | jq -e --arg n "$1" '.nodes[] | select(.name == $n and .status == "NODE_STATUS_ONLINE")' >/dev/null; } +# what the doctor of a node says of its IPv6 uplink: "yes ADDRS" when it names a stable address, else the state +doctor_v6() { # + api HealthService/GetDoctor "$(jq -nc --arg n "${NODE_ID[$1]}" '{nodeId:$n}')" \ + | jq -r '.nodes[0].items[]? | select(.id == "ipv6") | "\(.params.ipv6 // "?") connect=\(.params.connect // "?") addrs=\(.params.addrs // "")"' +} +node_has_v6() { local d; d=$(doctor_v6 "$1"); case $d in *"addrs=2001:db8:"*) return 0 ;; esac; return 1; } + +# ---------------------------------------------------------------- profiles, users, relays + +settings_of() { api ProfileService/ListProtocols '{}' | jq -c --arg id "$1" '.protocols[] | select(.id == $id) | .defaultSettingsJson | fromjson'; } +make_profile() { # -> id + api ProfileService/CreateProfile "$(jq -nc --arg p "$1" --arg n "$2" --arg s "$3" '{protocol:$p,name:$n,settingsJson:$s}')" | jq -r .profile.id +} +make_inbound() { # -> inbound id + api ProfileService/CreateInbound "$(jq -nc --arg p "$1" --arg n "${NODE_ID[$2]}" '{profileId:$p,nodeId:$n}')" | jq -r .inbound.id +} +inbound_active() { # + api NodeService/GetNode "$(jq -nc --arg n "${NODE_ID[$1]}" '{nodeId:$n}')" \ + | jq -e --arg id "$2" 'any(.inbounds[]; .id == $id and .state == "INBOUND_STATE_ACTIVE")' >/dev/null +} + +relay_json() { api RelayService/ListRelays "{}" 2>/dev/null | jq -c --arg id "$1" '.relays[] | select(.id == $id)' || true; } +relay_get() { relay_json "$1" | jq -r "$2" 2>/dev/null || true; } +rleg() { relay_get "$1" '.activeLeg // ""'; } # the family now: "4" or "6" +rstate() { relay_get "$1" '(.state // "") | sub("INBOUND_STATE_"; "")'; } # PENDING, ACTIVE, FAILED +relay_summary() { relay_json "$1" | jq -c '{leg, active: .activeLeg, state: ((.state // "") | sub("INBOUND_STATE_"; "")), enabled, + monitor: (.monitor | {ok, stage, code, failStreak}), check: (.check | {ok, leg: .leg.status, legCode: .leg.code, legFam: .leg.family, path: .path.status, pathCode: .path.code}), + other: (.otherLeg | {family, status, code})}'; } + +add_relay() { # -> sets RID[lane] + local lane=$1 out + out=$(api RelayService/CreateRelay "$(jq -nc --arg i "${INB[$lane]}" --arg v "${NODE_ID[ent]}" --arg l "${LEG_OF[$lane]}" --argjson r "$([ "$lane" = A ] && echo true || echo false)" \ + '{inboundId:$i,viaNodeId:$v,mode:"auto",leg:$l,legReturn:$r}')") || die "CreateRelay for lane $lane failed" + RID[$lane]=$(jq -r .relay.id <<<"$out") +} +check_relay() { api RelayService/CheckRelay "$(jq -nc --arg i "$1" '{id:$i}')"; } +# a check that passed (the answer of a busy node or a lost gate is a failed stage, not an error of the call) +check_relay_ok() { check_relay "$1" | jq -e '.relay.check.ok == true' >/dev/null; } +enable_relay() { api RelayService/UpdateRelay "$(jq -nc --arg i "$1" '{id:$i,enabled:true}')"; } + +# proposals of a relay, newest first, and the facts the owner sees +props() { papi ListProposals '{"kind":"relay_leg","limit":200}' 2>/dev/null | jq -c --arg id "$1" '[.proposals[]? | select(.subjectId == $id)]'; } +pstate() { props "$1" | jq -r '(.[0].state // "") | sub("PROPOSAL_STATE_"; "")'; } # AWAITING APPLYING APPLIED REJECTED STALE FAILED +pget() { props "$1" | jq -r ".[0] | $2" 2>/dev/null || true; } +pcount() { props "$1" | jq 'length'; } +automation_of() { papi GetAutomation '{"kind":"relay_leg"}' 2>/dev/null | jq -c --arg id "$1" '[.subjects[]? | select(.subjectId == $id)][0] // {}'; } +alert_open() { api HealthService/ListAlerts '{}' | jq -e --arg id "$1" '[.active[]? | select((.kind | test("RELAY_DOWN")) and .subject == $id)] | length > 0' >/dev/null; } + +# ---------------------------------------------------------------- the client: a Hysteria2 client per use, a SOCKS port, the relay's line + +hy2_yaml() { # : the client config from $URI on stdout + URI=$URI python3 - "$1" <<'PY' +import json, os, sys +from urllib.parse import urlsplit, parse_qs, unquote +u = urlsplit(os.environ["URI"]) +q = {k: v[0] for k, v in parse_qs(u.query).items()} +auth = unquote(u.username or "") + ((":" + unquote(u.password)) if u.password else "") +j = json.dumps +out = [f"server: {j(u.netloc.rsplit('@', 1)[-1])}", f"auth: {j(auth)}"] +tls = [] +if q.get("sni"): tls.append(f" sni: {j(q['sni'])}") +if q.get("insecure") in ("1", "true"): tls.append(" insecure: true") +if q.get("pinSHA256"): tls.append(f" pinSHA256: {j(q['pinSHA256'])}") +if tls: out += ["tls:"] + tls +if q.get("obfs"): + out += ["obfs:", f" type: {q['obfs']}", f" {q['obfs']}:", f" password: {j(q.get('obfs-password', ''))}"] +out += ["socks5:", f" listen: 127.0.0.1:{sys.argv[1]}"] +print("\n".join(out)) +PY +} +sub_lines() { nsx pan curl -skS -m 30 -A 'Happ/3.0' "$USER_URL" | base64 -d 2>/dev/null; } +# the relay's own line in the subscription: the entry's address and the relay's port (what the person's app has) +relay_line() { # + local rport + rport=$(relay_get "${RID[$1]}" '.port') + sub_lines | grep '^hysteria2://' | grep -E "@$ENT_IP:$rport([?/]|$)" | head -n 1 || true +} +NEXT_SOCKS=11000 +# start_client