Initial commit
This commit is contained in:
commit
71712b07db
263 files changed
+83991
No files matched your search
@@ -0,0 +1,139 @@
|
||||
@REM SPDX-FileCopyrightText: 2026 amurcanov
|
||||
@REM SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
set "VERIFY_ONLY=0"
|
||||
if "%~1"=="" goto args_ok
|
||||
if /I "%~1"=="--verify-native-only" (
|
||||
set "VERIFY_ONLY=1"
|
||||
goto args_ok
|
||||
)
|
||||
echo Usage: build_apk.bat [--verify-native-only]
|
||||
exit /b 2
|
||||
|
||||
:args_ok
|
||||
for %%I in ("%~dp0..") do set "PROJECT_ROOT=%%~fI\"
|
||||
set "PROVENANCE_SCRIPT=%PROJECT_ROOT%scripts\native_client_provenance.ps1"
|
||||
set "SERVER_PROVENANCE_SCRIPT=%PROJECT_ROOT%scripts\server_asset_provenance.ps1"
|
||||
cd /d "%PROJECT_ROOT%"
|
||||
|
||||
echo === CSQTT APK Build Script ===
|
||||
echo === Output: 4 APKs (universal, arm64-v8a, armeabi-v7a, x86_64) ===
|
||||
echo.
|
||||
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%SERVER_PROVENANCE_SCRIPT%" -Mode Verify
|
||||
if %errorlevel% neq 0 (
|
||||
echo.
|
||||
echo Run rust-server\build_linux.bat first to rebuild the verified server asset.
|
||||
if "%VERIFY_ONLY%"=="0" if not defined CI pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%PROVENANCE_SCRIPT%" -Mode Verify
|
||||
if %errorlevel% neq 0 (
|
||||
echo.
|
||||
echo Run rust-client\build_so.bat first to rebuild verified Rust native libraries.
|
||||
if "%VERIFY_ONLY%"=="0" if not defined CI pause
|
||||
exit /b 1
|
||||
)
|
||||
if "%VERIFY_ONLY%"=="1" (
|
||||
echo Native verification completed successfully.
|
||||
exit /b 0
|
||||
)
|
||||
|
||||
:: 2. Find Android SDK so Gradle can locate it even if local.properties is stale
|
||||
call "%PROJECT_ROOT%scripts\find_android_sdk.bat"
|
||||
if %errorlevel% neq 0 (
|
||||
if not defined CI pause
|
||||
exit /b 1
|
||||
)
|
||||
set "ANDROID_HOME=%SDK_PATH%"
|
||||
|
||||
:: 3. Skipping clean for faster incremental builds
|
||||
echo Incremental build...
|
||||
|
||||
:: 4. Build release APKs
|
||||
echo Building release APKs...
|
||||
call "%PROJECT_ROOT%gradlew.bat" :app:assembleRelease --no-daemon
|
||||
|
||||
if %errorlevel% neq 0 (
|
||||
echo.
|
||||
echo BUILD FAILED! Please check the errors above.
|
||||
if not defined CI pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
set "VERIFY_DEPLOY_ASSET=%PROJECT_ROOT%scripts\verify_apk_deploy_asset.ps1"
|
||||
set "APK_DIR=%PROJECT_ROOT%app\build\outputs\apk\release"
|
||||
set "DEPLOY_SOURCE=%PROJECT_ROOT%app\src\main\assets\deploy.sh"
|
||||
for %%F in (
|
||||
"%APK_DIR%\app-universal-release.apk"
|
||||
"%APK_DIR%\app-arm64-v8a-release.apk"
|
||||
"%APK_DIR%\app-armeabi-v7a-release.apk"
|
||||
"%APK_DIR%\app-x86_64-release.apk"
|
||||
) do (
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%VERIFY_DEPLOY_ASSET%" -ApkPath "%%~fF" -SourcePath "%DEPLOY_SOURCE%"
|
||||
if errorlevel 1 goto verify_failed
|
||||
)
|
||||
|
||||
:: 4. Create release directory
|
||||
if not exist "%PROJECT_ROOT%app\release" mkdir "%PROJECT_ROOT%app\release"
|
||||
|
||||
:: 5. Copy and rename all APK variants
|
||||
echo.
|
||||
echo Copying APKs to release folder...
|
||||
|
||||
if exist "%APK_DIR%\app-x86-release.apk" del /Q "%APK_DIR%\app-x86-release.apk"
|
||||
if exist "%PROJECT_ROOT%app\release\CSQTT-x86.apk" del /Q "%PROJECT_ROOT%app\release\CSQTT-x86.apk"
|
||||
|
||||
:: Universal APK (all architectures)
|
||||
if exist "%APK_DIR%\app-universal-release.apk" (
|
||||
copy /Y "%APK_DIR%\app-universal-release.apk" "%PROJECT_ROOT%app\release\CSQTT-universal.apk" >nul
|
||||
for %%F in ("%PROJECT_ROOT%app\release\CSQTT-universal.apk") do echo [OK] CSQTT-universal.apk [%%~zF bytes]
|
||||
) else (
|
||||
echo [!!] Universal APK not found
|
||||
)
|
||||
|
||||
:: arm64-v8a
|
||||
if exist "%APK_DIR%\app-arm64-v8a-release.apk" (
|
||||
copy /Y "%APK_DIR%\app-arm64-v8a-release.apk" "%PROJECT_ROOT%app\release\CSQTT-arm64-v8a.apk" >nul
|
||||
for %%F in ("%PROJECT_ROOT%app\release\CSQTT-arm64-v8a.apk") do echo [OK] CSQTT-arm64-v8a.apk [%%~zF bytes]
|
||||
) else (
|
||||
echo [!!] arm64-v8a APK not found
|
||||
)
|
||||
|
||||
:: armeabi-v7a
|
||||
if exist "%APK_DIR%\app-armeabi-v7a-release.apk" (
|
||||
copy /Y "%APK_DIR%\app-armeabi-v7a-release.apk" "%PROJECT_ROOT%app\release\CSQTT-armeabi-v7a.apk" >nul
|
||||
for %%F in ("%PROJECT_ROOT%app\release\CSQTT-armeabi-v7a.apk") do echo [OK] CSQTT-armeabi-v7a.apk [%%~zF bytes]
|
||||
) else (
|
||||
echo [!!] armeabi-v7a APK not found
|
||||
)
|
||||
|
||||
:: x86_64
|
||||
if exist "%APK_DIR%\app-x86_64-release.apk" (
|
||||
copy /Y "%APK_DIR%\app-x86_64-release.apk" "%PROJECT_ROOT%app\release\CSQTT-x86_64.apk" >nul
|
||||
for %%F in ("%PROJECT_ROOT%app\release\CSQTT-x86_64.apk") do echo [OK] CSQTT-x86_64.apk [%%~zF bytes]
|
||||
) else (
|
||||
echo [!!] x86_64 APK not found
|
||||
)
|
||||
|
||||
echo.
|
||||
echo === DONE ===
|
||||
echo Output directory: app\release\
|
||||
echo.
|
||||
echo CSQTT-universal.apk - all architectures in one APK
|
||||
echo CSQTT-arm64-v8a.apk - 64-bit ARM only
|
||||
echo CSQTT-armeabi-v7a.apk - 32-bit ARM only
|
||||
echo CSQTT-x86_64.apk - 64-bit x86 only
|
||||
echo.
|
||||
if not defined CI pause
|
||||
exit /b 0
|
||||
|
||||
:verify_failed
|
||||
echo.
|
||||
echo APK deploy asset verification failed. Release files were not replaced.
|
||||
if not defined CI pause
|
||||
exit /b 1
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/usr/bin/env bash
|
||||
# SPDX-FileCopyrightText: 2026 amurcanov
|
||||
# SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "${BASH_SOURCE[0]}")/.."
|
||||
|
||||
echo "=== CSQTT APK Build Script ==="
|
||||
echo "=== Output: 3 APKs (universal, arm64-v8a, armeabi-v7a) ==="
|
||||
echo ""
|
||||
|
||||
MISSING=0
|
||||
if [[ ! -f "app/src/main/jniLibs/arm64-v8a/libclient.so" ]]; then
|
||||
echo "ERROR: arm64-v8a .so not found!"
|
||||
MISSING=1
|
||||
fi
|
||||
if [[ ! -f "app/src/main/jniLibs/armeabi-v7a/libclient.so" ]]; then
|
||||
echo "ERROR: armeabi-v7a .so not found!"
|
||||
MISSING=1
|
||||
fi
|
||||
if [[ "$MISSING" == "1" ]]; then
|
||||
echo ""
|
||||
echo "Run build_client.sh first to build all native libraries!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Incremental build..."
|
||||
echo "Building release APKs..."
|
||||
|
||||
SDK_DIR=""
|
||||
if [[ -n "${ANDROID_HOME:-}" && -d "$ANDROID_HOME" ]]; then
|
||||
SDK_DIR="$ANDROID_HOME"
|
||||
elif [[ -n "${ANDROID_SDK_ROOT:-}" && -d "$ANDROID_SDK_ROOT" ]]; then
|
||||
SDK_DIR="$ANDROID_SDK_ROOT"
|
||||
elif [[ -f "local.properties" ]]; then
|
||||
SDK_DIR="$(grep -E '^sdk\.dir=' local.properties | head -n1 | cut -d= -f2- || true)"
|
||||
SDK_DIR="${SDK_DIR//\\:/:}"
|
||||
if [[ -n "$SDK_DIR" && ! -d "$SDK_DIR" ]]; then
|
||||
SDK_DIR=""
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "$SDK_DIR" ]]; then
|
||||
for cand in \
|
||||
"$HOME/AppData/Local/Android/Sdk" \
|
||||
"$HOME/Library/Android/sdk" \
|
||||
"/opt/android-sdk" \
|
||||
"/usr/lib/android-sdk"; do
|
||||
if [[ -d "$cand" ]]; then
|
||||
SDK_DIR="$cand"
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
if [[ -n "$SDK_DIR" ]]; then
|
||||
export ANDROID_HOME="$SDK_DIR"
|
||||
echo "Using SDK: $SDK_DIR"
|
||||
fi
|
||||
|
||||
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "cygwin" || "$OSTYPE" == "win32" ]]; then
|
||||
./gradlew.bat assembleRelease --no-daemon
|
||||
else
|
||||
./gradlew assembleRelease --no-daemon
|
||||
fi
|
||||
|
||||
mkdir -p app/release
|
||||
|
||||
echo ""
|
||||
echo "Copying APKs to release folder..."
|
||||
|
||||
APK_DIR="app/build/outputs/apk/release"
|
||||
|
||||
if [[ -f "$APK_DIR/app-universal-release.apk" ]]; then
|
||||
cp "$APK_DIR/app-universal-release.apk" "app/release/CSQTT-universal.apk"
|
||||
echo " [OK] CSQTT-universal.apk"
|
||||
else
|
||||
echo " [!!] Universal APK not found"
|
||||
fi
|
||||
|
||||
if [[ -f "$APK_DIR/app-arm64-v8a-release.apk" ]]; then
|
||||
cp "$APK_DIR/app-arm64-v8a-release.apk" "app/release/CSQTT-arm64-v8a.apk"
|
||||
echo " [OK] CSQTT-arm64-v8a.apk"
|
||||
else
|
||||
echo " [!!] arm64-v8a APK not found"
|
||||
fi
|
||||
|
||||
if [[ -f "$APK_DIR/app-armeabi-v7a-release.apk" ]]; then
|
||||
cp "$APK_DIR/app-armeabi-v7a-release.apk" "app/release/CSQTT-armeabi-v7a.apk"
|
||||
echo " [OK] CSQTT-armeabi-v7a.apk"
|
||||
else
|
||||
echo " [!!] armeabi-v7a APK not found"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "=== DONE ==="
|
||||
echo "Output directory: app/release/"
|
||||
echo ""
|
||||
echo " CSQTT-universal.apk - all architectures in one APK"
|
||||
echo " CSQTT-arm64-v8a.apk - 64-bit ARM only"
|
||||
echo " CSQTT-armeabi-v7a.apk - 32-bit ARM only"
|
||||
echo ""
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env bash
|
||||
set -u
|
||||
|
||||
mode="${1:-report}"
|
||||
duration="${2:-25}"
|
||||
|
||||
if [[ "$mode" != "report" && "$mode" != "capture" ]]; then
|
||||
printf 'Usage: %s [report|capture] [seconds]\n' "$0" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if ! [[ "$duration" =~ ^[1-9][0-9]*$ ]] || (( duration > 300 )); then
|
||||
printf 'Capture duration must be an integer between 1 and 300 seconds\n' >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
section() {
|
||||
printf '\n========== %s ==========' "$1"
|
||||
printf '\n'
|
||||
}
|
||||
|
||||
run() {
|
||||
printf '\n$'
|
||||
printf ' %q' "$@"
|
||||
printf '\n'
|
||||
"$@" 2>&1
|
||||
local status=$?
|
||||
printf '[exit=%s]\n' "$status"
|
||||
}
|
||||
|
||||
run_shell() {
|
||||
printf '\n$ %s\n' "$1"
|
||||
bash -o pipefail -c "$1" 2>&1
|
||||
local status=$?
|
||||
printf '[exit=%s]\n' "$status"
|
||||
}
|
||||
|
||||
have() {
|
||||
command -v "$1" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
if (( EUID != 0 )); then
|
||||
printf 'Run this report as root: sudo bash %s %s\n' "$0" "$mode" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
section "CSQTT network report"
|
||||
printf 'UTC: %s\n' "$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
|
||||
printf 'Host: %s\n' "$(hostname -f 2>/dev/null || hostname)"
|
||||
printf 'Mode: %s\n' "$mode"
|
||||
|
||||
if [[ "$mode" == "capture" ]]; then
|
||||
section "UDP capture"
|
||||
if have tcpdump; then
|
||||
printf 'Start the CSQTT client now. Capture ends after %s seconds.\n' "$duration"
|
||||
run timeout "${duration}s" tcpdump -ni any -nn -tttt -vv 'udp port 46000'
|
||||
else
|
||||
printf 'tcpdump is not installed. Install it with: apt-get update && apt-get install -y tcpdump\n'
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
section "Operating system"
|
||||
run uname -a
|
||||
[[ -r /etc/os-release ]] && run cat /etc/os-release
|
||||
run uptime
|
||||
|
||||
section "CSQTT service"
|
||||
run systemctl status csqtt --no-pager --full
|
||||
run systemctl show csqtt -p ActiveState -p SubState -p Result -p MainPID -p NRestarts -p ExecMainCode -p ExecMainStatus -p RestartUSec
|
||||
run systemctl cat csqtt
|
||||
run_shell "journalctl -u csqtt -b -n 200 --no-pager | sed -E 's/(\\[INIT\\] generated (main|web) password: ).*/\\1[REDACTED]/'"
|
||||
run ps -eo pid,ppid,user,stat,etimes,cmd --forest
|
||||
|
||||
section "Listening sockets"
|
||||
run ss -lunp
|
||||
run ss -ltnp
|
||||
|
||||
section "Interfaces and routes"
|
||||
run ip -br link
|
||||
run ip -br address
|
||||
run ip -d link show csqtt1
|
||||
run ip address show dev csqtt1
|
||||
run ip tuntap show
|
||||
run ip route show table all
|
||||
run ip rule show
|
||||
run ip route get 1.1.1.1
|
||||
run ls -l /dev/net/tun
|
||||
|
||||
section "Kernel networking"
|
||||
run sysctl net.ipv4.ip_forward net.ipv4.conf.all.rp_filter net.ipv4.conf.default.rp_filter net.core.rmem_max net.core.wmem_max net.netfilter.nf_conntrack_max
|
||||
wan_iface="$(ip -o -4 route show default 2>/dev/null | awk '{for (i = 1; i <= NF; i++) if ($i == "dev") { print $(i + 1); exit }}')"
|
||||
if [[ -n "$wan_iface" ]]; then
|
||||
run sysctl "net.ipv4.conf.${wan_iface}.rp_filter"
|
||||
fi
|
||||
run sysctl net.ipv4.conf.csqtt1.rp_filter
|
||||
have nstat && run nstat
|
||||
|
||||
section "Firewall"
|
||||
have iptables-save && run iptables-save -c
|
||||
have iptables && run iptables -w 2 -nvL
|
||||
have iptables && run iptables -w 2 -t nat -nvL
|
||||
have iptables && run iptables -w 2 -t mangle -nvL
|
||||
have nft && run nft list ruleset
|
||||
have ufw && run ufw status verbose
|
||||
have firewall-cmd && run firewall-cmd --state
|
||||
have firewall-cmd && run firewall-cmd --list-all
|
||||
|
||||
section "Runtime files"
|
||||
run ls -ld /etc/csqtt /run/csqtt /usr/local/lib/csqtt
|
||||
run find /etc/csqtt -maxdepth 1 -mindepth 1 -printf '%M %u:%g %s %f\n'
|
||||
have docker && run docker ps -a --no-trunc
|
||||
|
||||
section "Report complete"
|
||||
@@ -0,0 +1,45 @@
|
||||
import argparse
|
||||
import json
|
||||
import signal
|
||||
import socket
|
||||
import time
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--host", required=True)
|
||||
parser.add_argument("--port", required=True, type=int)
|
||||
parser.add_argument("--stats", required=True)
|
||||
arguments = parser.parse_args()
|
||||
state = {"received_bytes": 0, "received_packets": 0, "sent_bytes": 0, "sent_packets": 0}
|
||||
running = True
|
||||
|
||||
def persist(*_):
|
||||
nonlocal running
|
||||
with open(arguments.stats, "w", encoding="utf-8") as output:
|
||||
json.dump(state, output, sort_keys=True)
|
||||
output.write("\n")
|
||||
running = False
|
||||
|
||||
signal.signal(signal.SIGINT, persist)
|
||||
signal.signal(signal.SIGTERM, persist)
|
||||
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
server.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 16 * 1024 * 1024)
|
||||
server.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 16 * 1024 * 1024)
|
||||
server.bind((arguments.host, arguments.port))
|
||||
server.settimeout(0.5)
|
||||
while running:
|
||||
try:
|
||||
packet, address = server.recvfrom(65_535)
|
||||
except TimeoutError:
|
||||
continue
|
||||
state["received_bytes"] += len(packet)
|
||||
state["received_packets"] += 1
|
||||
if server.sendto(packet, address) == len(packet):
|
||||
state["sent_bytes"] += len(packet)
|
||||
state["sent_packets"] += 1
|
||||
server.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env bash
|
||||
set -u -o pipefail
|
||||
|
||||
PEER_PORT="${CSQTT_PEER_PORT:-46000}"
|
||||
WEB_PORT="${CSQTT_WEB_PORT:-46002}"
|
||||
CSQTT_IFACE="${CSQTT_IFACE:-csqtt1}"
|
||||
CSQTT_DIR="${CSQTT_CONFIG_DIR:-/etc/csqtt}"
|
||||
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
printf 'Run as root: sudo bash %s\n' "$0" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
section() {
|
||||
printf '\n========== %s ==========' "$1"
|
||||
printf '\n'
|
||||
}
|
||||
|
||||
redact() {
|
||||
sed -E \
|
||||
-e 's/((password|token|secret|authorization|cookie|api[_-]?key)[[:space:]]*[:=][[:space:]]*)[^[:space:];,]+/\1<redacted>/Ig' \
|
||||
-e 's/(--password[[:space:]]+)[^[:space:]]+/\1<redacted>/g' \
|
||||
-e 's#(csqtt://)[^@[:space:]]+@#\1<redacted>@#g'
|
||||
}
|
||||
|
||||
safe() {
|
||||
"$@" 2>&1 || true
|
||||
}
|
||||
|
||||
service_pids() {
|
||||
systemctl show --value -p MainPID csqtt.service 2>/dev/null | awk '$1 ~ /^[0-9]+$/ && $1 > 1 { print $1 }'
|
||||
pgrep -x csqtt 2>/dev/null || true
|
||||
}
|
||||
|
||||
section 'timestamp and host'
|
||||
safe date --iso-8601=seconds
|
||||
safe hostnamectl
|
||||
safe uname -a
|
||||
safe uptime
|
||||
|
||||
section 'systemd state'
|
||||
safe systemctl is-active csqtt.service
|
||||
safe systemctl is-enabled csqtt.service
|
||||
safe systemctl show csqtt.service \
|
||||
-p LoadState -p ActiveState -p SubState -p Result -p MainPID -p ControlPID \
|
||||
-p NRestarts -p ExecMainCode -p ExecMainStatus -p RestartUSec -p Restart \
|
||||
-p FragmentPath -p DropInPaths -p ControlGroup -p ExecStart -p ExecStartPre \
|
||||
-p EnvironmentFiles
|
||||
safe systemctl status csqtt.service --no-pager --full
|
||||
|
||||
section 'unit definition'
|
||||
safe systemctl cat csqtt.service
|
||||
|
||||
section 'other CSQTT systemd units'
|
||||
safe systemctl list-units --all --type=service --no-legend --plain | awk 'tolower($0) ~ /csqtt/'
|
||||
safe systemctl list-unit-files --no-legend | awk 'tolower($0) ~ /csqtt/'
|
||||
safe find /etc/systemd/system /lib/systemd/system -type f -name '*.service' -print0 2>/dev/null | xargs -0r grep -lE '/usr/local/bin/csqtt|csqtt' 2>/dev/null
|
||||
|
||||
section 'CSQTT processes and owners'
|
||||
for pid in $(service_pids | sort -un); do
|
||||
[ -r "/proc/$pid/status" ] || continue
|
||||
printf '%s\n' "PID=$pid"
|
||||
safe ps -p "$pid" -o pid,ppid,user,lstart,etime,stat,comm,args
|
||||
printf 'exe='
|
||||
readlink "/proc/$pid/exe" 2>/dev/null || true
|
||||
printf 'cgroup:\n'
|
||||
safe cat "/proc/$pid/cgroup"
|
||||
printf 'parent:\n'
|
||||
parent="$(awk '/^PPid:/ {print $2}' "/proc/$pid/status" 2>/dev/null || true)"
|
||||
if [ -n "$parent" ] && [ "$parent" -gt 1 ] 2>/dev/null; then
|
||||
safe ps -p "$parent" -o pid,ppid,user,lstart,etime,stat,comm,args
|
||||
fi
|
||||
done | redact
|
||||
|
||||
section 'CSQTT executable and runtime files'
|
||||
safe ls -l /usr/local/bin/csqtt /usr/local/lib/csqtt 2>/dev/null
|
||||
safe sha256sum /usr/local/bin/csqtt 2>/dev/null
|
||||
safe file /usr/local/bin/csqtt 2>/dev/null
|
||||
safe find "$CSQTT_DIR" -maxdepth 2 -type f -printf '%M %u:%g %s bytes %TY-%Tm-%TdT%TH:%TM:%TS %p\n' 2>/dev/null | sort
|
||||
safe ls -ld /run/csqtt "$CSQTT_DIR" 2>/dev/null
|
||||
|
||||
section 'database integrity without reading records'
|
||||
if command -v sqlite3 >/dev/null 2>&1 && [ -f "$CSQTT_DIR/csqtt.db" ]; then
|
||||
safe sqlite3 "$CSQTT_DIR/csqtt.db" 'PRAGMA quick_check; SELECT name FROM sqlite_master WHERE type IN ("table", "index") ORDER BY type, name;'
|
||||
else
|
||||
printf 'sqlite3 or %s/csqtt.db is unavailable\n' "$CSQTT_DIR"
|
||||
fi
|
||||
|
||||
section 'listening sockets'
|
||||
safe ss -H -lunp "sport = :$PEER_PORT"
|
||||
safe ss -H -ltnp "sport = :$WEB_PORT"
|
||||
safe ss -H -uanp | grep -E "(:$PEER_PORT|csqtt)" || true
|
||||
|
||||
section 'TUN and routing'
|
||||
safe ls -l /dev/net/tun
|
||||
safe ip -d link show "$CSQTT_IFACE"
|
||||
safe ip -br address show "$CSQTT_IFACE"
|
||||
safe ip -s link show "$CSQTT_IFACE"
|
||||
safe ip route show table main
|
||||
safe ip rule show
|
||||
safe sysctl net.ipv4.ip_forward net.ipv4.conf.all.rp_filter net.ipv4.conf.default.rp_filter
|
||||
|
||||
section 'CSQTT firewall rules'
|
||||
if command -v iptables-save >/dev/null 2>&1; then
|
||||
safe iptables-save | grep -E 'CSQTT|10\.66\.67\.|46000|46002' || true
|
||||
fi
|
||||
if command -v nft >/dev/null 2>&1; then
|
||||
safe nft list ruleset | grep -Ei 'csqtt|10\.66\.67\.|46000|46002' || true
|
||||
fi
|
||||
|
||||
section 'Docker and scheduled restart sources'
|
||||
if command -v docker >/dev/null 2>&1; then
|
||||
safe docker ps -a --format '{{.ID}} {{.Names}} {{.Image}} {{.Status}}' | grep -i csqtt || true
|
||||
fi
|
||||
safe find /etc/cron.d /etc/cron.daily /etc/cron.hourly /etc/cron.weekly /etc/cron.monthly /var/spool/cron -type f -print0 2>/dev/null | xargs -0r grep -lEi 'csqtt|/usr/local/bin/csqtt' 2>/dev/null
|
||||
|
||||
section 'CSQTT journal, current boot'
|
||||
safe journalctl -u csqtt.service -b -n 300 --no-pager -o short-iso | redact
|
||||
|
||||
section 'all current-boot CSQTT related journal lines'
|
||||
safe journalctl -b --no-pager -o short-iso | grep -Ei 'csqtt|tun-recover|network-up' | tail -n 300 | redact
|
||||
|
||||
section 'result'
|
||||
printf 'Report complete. No service, firewall, database, or configuration was modified.\n'
|
||||
@@ -0,0 +1,67 @@
|
||||
@REM SPDX-FileCopyrightText: 2026 amurcanov
|
||||
@REM SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
:: Find Android SDK and export SDK_PATH to the caller.
|
||||
:: Usage (inside a script with enabledelayedexpansion):
|
||||
:: set "PROJECT_ROOT=..."
|
||||
:: call scripts\find_android_sdk.bat
|
||||
::
|
||||
:: Search order:
|
||||
:: ANDROID_HOME -> ANDROID_SDK_ROOT -> local.properties sdk.dir ->
|
||||
:: %%LOCALAPPDATA%%\Android\Sdk -> %%ProgramFiles%%\Android\android-sdk ->
|
||||
:: %%ProgramFiles(x86)%%\Android\android-sdk
|
||||
|
||||
set "SDK_PATH="
|
||||
|
||||
if defined ANDROID_HOME (
|
||||
if exist "%ANDROID_HOME%" (
|
||||
set "SDK_PATH=%ANDROID_HOME%"
|
||||
)
|
||||
)
|
||||
|
||||
if not defined SDK_PATH (
|
||||
if defined ANDROID_SDK_ROOT (
|
||||
if exist "%ANDROID_SDK_ROOT%" (
|
||||
set "SDK_PATH=%ANDROID_SDK_ROOT%"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if not defined SDK_PATH (
|
||||
if exist "%PROJECT_ROOT%local.properties" (
|
||||
for /f "tokens=1,* delims==" %%A in ('type "%PROJECT_ROOT%local.properties" ^| findstr /R /C:"^sdk\.dir="') do (
|
||||
set "SDK_PATH=%%B"
|
||||
)
|
||||
if defined SDK_PATH (
|
||||
set "SDK_PATH=!SDK_PATH:\\=\!"
|
||||
set "SDK_PATH=!SDK_PATH:\:=:!"
|
||||
if not exist "!SDK_PATH!" (
|
||||
set "SDK_PATH="
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if not defined SDK_PATH (
|
||||
if exist "%LOCALAPPDATA%\Android\Sdk" (
|
||||
set "SDK_PATH=%LOCALAPPDATA%\Android\Sdk"
|
||||
) else if exist "%ProgramFiles%\Android\android-sdk" (
|
||||
set "SDK_PATH=%ProgramFiles%\Android\android-sdk"
|
||||
) else if exist "%ProgramFiles(x86)%\Android\android-sdk" (
|
||||
set "SDK_PATH=%ProgramFiles(x86)%\Android\android-sdk"
|
||||
)
|
||||
)
|
||||
|
||||
if not defined SDK_PATH (
|
||||
echo Error: Android SDK not found.
|
||||
echo Set ANDROID_HOME or ANDROID_SDK_ROOT, define sdk.dir in local.properties,
|
||||
echo or install Android Studio to the default location.
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo Using SDK: %SDK_PATH%
|
||||
endlocal & set "SDK_PATH=%SDK_PATH%"
|
||||
exit /b 0
|
||||
@@ -0,0 +1,141 @@
|
||||
@REM SPDX-FileCopyrightText: 2026 amurcanov
|
||||
@REM SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
:: Find Android SDK/NDK and export SDK_PATH + NDK_PATH + TOOLCHAIN to the caller.
|
||||
:: Usage (inside a script with enabledelayedexpansion):
|
||||
:: set "PROJECT_ROOT=..."
|
||||
:: call scripts\find_android_sdk_ndk.bat
|
||||
::
|
||||
:: Search order:
|
||||
:: SDK: ANDROID_HOME -> ANDROID_SDK_ROOT -> local.properties sdk.dir ->
|
||||
:: %%LOCALAPPDATA%%\Android\Sdk -> %%ProgramFiles%%\Android\android-sdk ->
|
||||
:: %%ProgramFiles(x86)%%\Android\android-sdk
|
||||
:: NDK: ANDROID_NDK_HOME -> ANDROID_NDK_ROOT -> %%SDK_PATH%%\ndk ->
|
||||
:: %%LOCALAPPDATA%%\Android\Sdk\ndk -> %%ProgramFiles%%\Android\ndk
|
||||
|
||||
set "SDK_PATH="
|
||||
|
||||
:: 1. ANDROID_HOME
|
||||
if defined ANDROID_HOME (
|
||||
if exist "%ANDROID_HOME%" (
|
||||
set "SDK_PATH=%ANDROID_HOME%"
|
||||
)
|
||||
)
|
||||
|
||||
:: 2. ANDROID_SDK_ROOT
|
||||
if not defined SDK_PATH (
|
||||
if defined ANDROID_SDK_ROOT (
|
||||
if exist "%ANDROID_SDK_ROOT%" (
|
||||
set "SDK_PATH=%ANDROID_SDK_ROOT%"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
:: 3. local.properties (sdk.dir)
|
||||
if not defined SDK_PATH (
|
||||
if exist "%PROJECT_ROOT%local.properties" (
|
||||
for /f "tokens=1,* delims==" %%A in ('type "%PROJECT_ROOT%local.properties" ^| findstr /R /C:"^sdk\.dir="') do (
|
||||
set "SDK_PATH=%%B"
|
||||
)
|
||||
if defined SDK_PATH (
|
||||
set "SDK_PATH=!SDK_PATH:\\=\!"
|
||||
set "SDK_PATH=!SDK_PATH:\:=:!"
|
||||
if not exist "!SDK_PATH!" (
|
||||
set "SDK_PATH="
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
:: 4. Common Android Studio SDK locations
|
||||
if not defined SDK_PATH (
|
||||
if exist "%LOCALAPPDATA%\Android\Sdk" (
|
||||
set "SDK_PATH=%LOCALAPPDATA%\Android\Sdk"
|
||||
) else if exist "%ProgramFiles%\Android\android-sdk" (
|
||||
set "SDK_PATH=%ProgramFiles%\Android\android-sdk"
|
||||
) else if exist "%ProgramFiles(x86)%\Android\android-sdk" (
|
||||
set "SDK_PATH=%ProgramFiles(x86)%\Android\android-sdk"
|
||||
)
|
||||
)
|
||||
|
||||
if not defined SDK_PATH (
|
||||
echo Error: Android SDK not found.
|
||||
echo Set ANDROID_HOME or ANDROID_SDK_ROOT, define sdk.dir in local.properties,
|
||||
echo or install Android Studio to the default location.
|
||||
exit /b 1
|
||||
)
|
||||
echo Using SDK: %SDK_PATH%
|
||||
|
||||
:: Find NDK
|
||||
set "NDK_ROOT="
|
||||
|
||||
if defined ANDROID_NDK_HOME (
|
||||
if exist "%ANDROID_NDK_HOME%" (
|
||||
set "NDK_ROOT=%ANDROID_NDK_HOME%"
|
||||
)
|
||||
)
|
||||
|
||||
if not defined NDK_ROOT (
|
||||
if defined ANDROID_NDK_ROOT (
|
||||
if exist "%ANDROID_NDK_ROOT%" (
|
||||
set "NDK_ROOT=%ANDROID_NDK_ROOT%"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if not defined NDK_ROOT (
|
||||
if defined NDK_HOME (
|
||||
if exist "%NDK_HOME%" (
|
||||
set "NDK_ROOT=%NDK_HOME%"
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if not defined NDK_ROOT (
|
||||
if exist "%SDK_PATH%\ndk" (
|
||||
set "NDK_ROOT=%SDK_PATH%\ndk"
|
||||
)
|
||||
)
|
||||
|
||||
if not defined NDK_ROOT (
|
||||
if exist "%LOCALAPPDATA%\Android\Sdk\ndk" (
|
||||
set "NDK_ROOT=%LOCALAPPDATA%\Android\Sdk\ndk"
|
||||
) else if exist "%ProgramFiles%\Android\ndk" (
|
||||
set "NDK_ROOT=%ProgramFiles%\Android\ndk"
|
||||
)
|
||||
)
|
||||
|
||||
if not defined NDK_ROOT (
|
||||
echo Error: NDK folder not found.
|
||||
echo Set ANDROID_NDK_HOME or ANDROID_NDK_ROOT, install NDK via Android Studio,
|
||||
echo or place it next to the detected SDK under %%SDK_PATH%%\ndk.
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
:: Detect whether NDK_ROOT is a parent of versioned folders or a single NDK install.
|
||||
:: dir /o-n selects the newest installed version first (for example 30 before 29).
|
||||
set "NDK_VER="
|
||||
for /f "delims=" %%D in ('dir /b /ad /o-n "%NDK_ROOT%" 2^>nul') do (
|
||||
if not defined NDK_VER if exist "%NDK_ROOT%\%%D\toolchains\llvm\prebuilt\windows-x86_64\bin" (
|
||||
set "NDK_VER=%%D"
|
||||
)
|
||||
)
|
||||
|
||||
if defined NDK_VER (
|
||||
echo Using NDK: !NDK_VER!
|
||||
endlocal & set "SDK_PATH=%SDK_PATH%" & set "NDK_PATH=%NDK_ROOT%\%NDK_VER%" & set "NDK_VERSION=%NDK_VER%" & set "TOOLCHAIN=%NDK_ROOT%\%NDK_VER%\toolchains\llvm\prebuilt\windows-x86_64\bin"
|
||||
exit /b 0
|
||||
)
|
||||
|
||||
:: NDK_ROOT points directly to one NDK installation.
|
||||
if exist "%NDK_ROOT%\toolchains\llvm\prebuilt\windows-x86_64\bin" (
|
||||
echo Using NDK: %NDK_ROOT%
|
||||
endlocal & set "SDK_PATH=%SDK_PATH%" & set "NDK_PATH=%NDK_ROOT%" & set "NDK_VERSION=" & set "TOOLCHAIN=%NDK_ROOT%\toolchains\llvm\prebuilt\windows-x86_64\bin"
|
||||
exit /b 0
|
||||
)
|
||||
|
||||
echo Error: NDK toolchain not found in %NDK_ROOT%.
|
||||
exit /b 1
|
||||
@@ -0,0 +1,372 @@
|
||||
# SPDX-FileCopyrightText: 2026 amurcanov
|
||||
# SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidateSet("Write", "Verify")]
|
||||
[string]$Mode,
|
||||
[string]$Root
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($Root)) {
|
||||
$projectRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot ".."))
|
||||
}
|
||||
else {
|
||||
$projectRoot = [IO.Path]::GetFullPath($Root)
|
||||
}
|
||||
$manifestPath = Join-Path $projectRoot "app\src\main\libclient.provenance.json"
|
||||
$cargoTomlPath = Join-Path $projectRoot "rust-client\Cargo.toml"
|
||||
$cargoLockPath = Join-Path $projectRoot "rust-client\Cargo.lock"
|
||||
$marker = "CSQTT_RUST_NATIVE_PRODUCTION_V1"
|
||||
$schema = "csqtt.native-client-provenance.v3"
|
||||
$producer = "rust-client/build_so.bat"
|
||||
$transport = "rust-turn-sans-io-rfc8656-channeldata"
|
||||
$transportMarker = "CSQTT_RUST_TURN_SANS_IO_V1"
|
||||
$nativeCoreAbi = 1
|
||||
|
||||
$specs = @(
|
||||
[pscustomobject]@{
|
||||
Abi = "arm64-v8a"
|
||||
Target = "aarch64-linux-android"
|
||||
RelativePath = "app/src/main/jniLibs/arm64-v8a/libclient.so"
|
||||
ProductionPath = Join-Path $projectRoot "app\src\main\jniLibs\arm64-v8a\libclient.so"
|
||||
CargoPath = Join-Path $projectRoot "build\rust-client-android-arm64\aarch64-linux-android\release\client"
|
||||
ElfClass = 2
|
||||
ElfMachine = 183
|
||||
},
|
||||
[pscustomobject]@{
|
||||
Abi = "armeabi-v7a"
|
||||
Target = "armv7-linux-androideabi"
|
||||
RelativePath = "app/src/main/jniLibs/armeabi-v7a/libclient.so"
|
||||
ProductionPath = Join-Path $projectRoot "app\src\main\jniLibs\armeabi-v7a\libclient.so"
|
||||
CargoPath = Join-Path $projectRoot "build\rust-client-android-armv7\armv7-linux-androideabi\release\client"
|
||||
ElfClass = 1
|
||||
ElfMachine = 40
|
||||
},
|
||||
[pscustomobject]@{
|
||||
Abi = "x86_64"
|
||||
Target = "x86_64-linux-android"
|
||||
RelativePath = "app/src/main/jniLibs/x86_64/libclient.so"
|
||||
ProductionPath = Join-Path $projectRoot "app\src\main\jniLibs\x86_64\libclient.so"
|
||||
CargoPath = Join-Path $projectRoot "build\rust-client-android-x86_64\x86_64-linux-android\release\client"
|
||||
ElfClass = 2
|
||||
ElfMachine = 62
|
||||
}
|
||||
)
|
||||
|
||||
function Assert-RegularFile {
|
||||
param([string]$Path, [string]$Label)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
|
||||
throw "$Label not found: $Path"
|
||||
}
|
||||
if ((Get-Item -LiteralPath $Path).Length -le 0) {
|
||||
throw "$Label is empty: $Path"
|
||||
}
|
||||
}
|
||||
|
||||
function Get-Sha256 {
|
||||
param([string]$Path)
|
||||
|
||||
$stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
|
||||
$hasher = [Security.Cryptography.SHA256]::Create()
|
||||
try {
|
||||
$hash = $hasher.ComputeHash($stream)
|
||||
return ([BitConverter]::ToString($hash)).Replace("-", "")
|
||||
}
|
||||
finally {
|
||||
$hasher.Dispose()
|
||||
$stream.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
function Get-BuildInputHash {
|
||||
$entries = @(
|
||||
(Join-Path $projectRoot "rust-client\build_so.bat"),
|
||||
(Join-Path $projectRoot "rust-client\build_android_abis.ps1"),
|
||||
(Join-Path $projectRoot "rust-client\Cargo.toml"),
|
||||
(Join-Path $projectRoot "rust-client\Cargo.lock"),
|
||||
(Join-Path $projectRoot "rust-client"),
|
||||
(Join-Path $projectRoot "rust-client\dispatcher"),
|
||||
(Join-Path $projectRoot "rust-client\vendor\primp"),
|
||||
(Join-Path $projectRoot "scripts\find_android_sdk_ndk.bat"),
|
||||
(Join-Path $projectRoot "scripts\native_client_provenance.ps1"),
|
||||
(Join-Path $projectRoot "shared\wire_protocol.rs"),
|
||||
(Join-Path $projectRoot "shared\striped_scheduler.rs")
|
||||
)
|
||||
$files = @()
|
||||
foreach ($entry in $entries) {
|
||||
if (Test-Path -LiteralPath $entry -PathType Leaf) {
|
||||
$files += [IO.Path]::GetFullPath($entry)
|
||||
}
|
||||
elseif (Test-Path -LiteralPath $entry -PathType Container) {
|
||||
if ($entry -eq (Join-Path $projectRoot "rust-client")) {
|
||||
# Crate root: hash only top-level sources, skip target/ and vendor/
|
||||
$files += Get-ChildItem -LiteralPath $entry -File -Filter *.rs |
|
||||
ForEach-Object { $_.FullName }
|
||||
}
|
||||
else {
|
||||
$files += Get-ChildItem -LiteralPath $entry -Recurse -File |
|
||||
ForEach-Object { $_.FullName }
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw "Native build input not found: $entry"
|
||||
}
|
||||
}
|
||||
$rootPrefix = $projectRoot.TrimEnd([char[]]@('\', '/')) + [IO.Path]::DirectorySeparatorChar
|
||||
$builder = New-Object Text.StringBuilder
|
||||
foreach ($file in @($files | Sort-Object -Unique)) {
|
||||
$fullPath = [IO.Path]::GetFullPath($file)
|
||||
if (-not $fullPath.StartsWith($rootPrefix, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw "Native build input escaped project root: $fullPath"
|
||||
}
|
||||
$relativePath = $fullPath.Substring($rootPrefix.Length).Replace("\", "/")
|
||||
[void]$builder.Append($relativePath)
|
||||
[void]$builder.Append(":")
|
||||
[void]$builder.Append((Get-Sha256 -Path $fullPath))
|
||||
[void]$builder.Append("`n")
|
||||
}
|
||||
$bytes = [Text.Encoding]::UTF8.GetBytes($builder.ToString())
|
||||
$hasher = [Security.Cryptography.SHA256]::Create()
|
||||
try {
|
||||
return ([BitConverter]::ToString($hasher.ComputeHash($bytes))).Replace("-", "")
|
||||
}
|
||||
finally {
|
||||
$hasher.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-Elf {
|
||||
param(
|
||||
[string]$Path,
|
||||
[int]$ExpectedClass,
|
||||
[int]$ExpectedMachine,
|
||||
[string]$Abi
|
||||
)
|
||||
|
||||
$stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
|
||||
try {
|
||||
$header = New-Object byte[] 20
|
||||
$offset = 0
|
||||
while ($offset -lt $header.Length) {
|
||||
$read = $stream.Read($header, $offset, $header.Length - $offset)
|
||||
if ($read -eq 0) {
|
||||
throw "Invalid ELF header for $Abi`: $Path"
|
||||
}
|
||||
$offset += $read
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$stream.Dispose()
|
||||
}
|
||||
|
||||
if ($header[0] -ne 0x7f -or $header[1] -ne 0x45 -or $header[2] -ne 0x4c -or $header[3] -ne 0x46) {
|
||||
throw "Production artifact is not ELF for $Abi`: $Path"
|
||||
}
|
||||
if ($header[4] -ne $ExpectedClass -or $header[5] -ne 1) {
|
||||
throw "ELF class or endianness mismatch for $Abi`: $Path"
|
||||
}
|
||||
|
||||
$elfType = [int]$header[16] -bor ([int]$header[17] -shl 8)
|
||||
$machine = [int]$header[18] -bor ([int]$header[19] -shl 8)
|
||||
if ($elfType -ne 3) {
|
||||
throw "Production artifact is not an Android PIE/ET_DYN for $Abi`: $Path"
|
||||
}
|
||||
if ($machine -ne $ExpectedMachine) {
|
||||
throw "ELF machine mismatch for $Abi`: expected $ExpectedMachine, got $machine"
|
||||
}
|
||||
}
|
||||
|
||||
function Test-BytePattern {
|
||||
param([string]$Path, [byte[]]$Pattern)
|
||||
|
||||
$stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
|
||||
try {
|
||||
$buffer = New-Object byte[] 65536
|
||||
$matched = 0
|
||||
while (($read = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) {
|
||||
for ($index = 0; $index -lt $read; $index++) {
|
||||
if ($buffer[$index] -eq $Pattern[$matched]) {
|
||||
$matched++
|
||||
if ($matched -eq $Pattern.Length) {
|
||||
return $true
|
||||
}
|
||||
}
|
||||
elseif ($buffer[$index] -eq $Pattern[0]) {
|
||||
$matched = 1
|
||||
}
|
||||
else {
|
||||
$matched = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
return $false
|
||||
}
|
||||
finally {
|
||||
$stream.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
function Get-CargoPackage {
|
||||
Assert-RegularFile -Path $cargoTomlPath -Label "Cargo.toml"
|
||||
|
||||
$insidePackage = $false
|
||||
$name = $null
|
||||
$version = $null
|
||||
foreach ($line in Get-Content -LiteralPath $cargoTomlPath) {
|
||||
$trimmed = $line.Trim()
|
||||
if ($trimmed -eq "[package]") {
|
||||
$insidePackage = $true
|
||||
continue
|
||||
}
|
||||
if ($insidePackage -and $trimmed.StartsWith("[")) {
|
||||
break
|
||||
}
|
||||
if ($insidePackage -and $trimmed -match '^(name|version)\s*=\s*"([^"]+)"') {
|
||||
if ($matches[1] -eq "name") {
|
||||
$name = $matches[2]
|
||||
}
|
||||
else {
|
||||
$version = $matches[2]
|
||||
}
|
||||
}
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($name) -or [string]::IsNullOrWhiteSpace($version)) {
|
||||
throw "Unable to read Rust package identity from $cargoTomlPath"
|
||||
}
|
||||
return [pscustomobject]@{ Name = $name; Version = $version }
|
||||
}
|
||||
|
||||
function Assert-RustArtifact {
|
||||
param($Spec, [bool]$RequireCargoMatch)
|
||||
|
||||
Assert-RegularFile -Path $Spec.ProductionPath -Label "$($Spec.Abi) production artifact"
|
||||
Assert-Elf -Path $Spec.ProductionPath -ExpectedClass $Spec.ElfClass -ExpectedMachine $Spec.ElfMachine -Abi $Spec.Abi
|
||||
|
||||
$goBuildInfo = [Text.Encoding]::ASCII.GetBytes("Go buildinf:")
|
||||
if (Test-BytePattern -Path $Spec.ProductionPath -Pattern $goBuildInfo) {
|
||||
throw "Go build metadata detected in production artifact for $($Spec.Abi)"
|
||||
}
|
||||
$transportIdentity = [Text.Encoding]::ASCII.GetBytes($transportMarker)
|
||||
if (-not (Test-BytePattern -Path $Spec.ProductionPath -Pattern $transportIdentity)) {
|
||||
throw "Rust TURN transport identity is missing for $($Spec.Abi)"
|
||||
}
|
||||
|
||||
if ($RequireCargoMatch) {
|
||||
Assert-RegularFile -Path $Spec.CargoPath -Label "$($Spec.Abi) Cargo artifact"
|
||||
$productionHash = Get-Sha256 -Path $Spec.ProductionPath
|
||||
$cargoHash = Get-Sha256 -Path $Spec.CargoPath
|
||||
if ($productionHash -ne $cargoHash) {
|
||||
throw "Production artifact does not match the Cargo output for $($Spec.Abi)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($Mode -eq "Write") {
|
||||
Assert-RegularFile -Path $cargoLockPath -Label "Cargo.lock"
|
||||
$package = Get-CargoPackage
|
||||
$buildInputHash = Get-BuildInputHash
|
||||
$artifacts = @()
|
||||
|
||||
foreach ($spec in $specs) {
|
||||
Assert-RustArtifact -Spec $spec -RequireCargoMatch $true
|
||||
$file = Get-Item -LiteralPath $spec.ProductionPath
|
||||
$artifacts += [ordered]@{
|
||||
abi = $spec.Abi
|
||||
target = $spec.Target
|
||||
path = $spec.RelativePath
|
||||
size = [long]$file.Length
|
||||
sha256 = Get-Sha256 -Path $spec.ProductionPath
|
||||
}
|
||||
}
|
||||
|
||||
$manifest = [ordered]@{
|
||||
schema = $schema
|
||||
marker = $marker
|
||||
producer = $producer
|
||||
runtime = "rust"
|
||||
buildSystem = "cargo-ndk"
|
||||
profile = "release"
|
||||
transport = $transport
|
||||
transportMarker = $transportMarker
|
||||
nativeCoreAbi = $nativeCoreAbi
|
||||
package = $package.Name
|
||||
version = $package.Version
|
||||
buildInputSha256 = $buildInputHash
|
||||
cargoTomlSha256 = Get-Sha256 -Path $cargoTomlPath
|
||||
cargoLockSha256 = Get-Sha256 -Path $cargoLockPath
|
||||
generatedAtUtc = [DateTime]::UtcNow.ToString("o")
|
||||
artifacts = $artifacts
|
||||
}
|
||||
|
||||
$json = $manifest | ConvertTo-Json -Depth 6
|
||||
$temporaryPath = "$manifestPath.tmp.$PID"
|
||||
[IO.File]::WriteAllText($temporaryPath, $json + [Environment]::NewLine, (New-Object Text.UTF8Encoding($false)))
|
||||
Move-Item -LiteralPath $temporaryPath -Destination $manifestPath -Force
|
||||
Write-Output "Wrote Rust native provenance: $manifestPath"
|
||||
exit 0
|
||||
}
|
||||
|
||||
Assert-RegularFile -Path $manifestPath -Label "Rust native provenance"
|
||||
|
||||
try {
|
||||
$manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json
|
||||
}
|
||||
catch {
|
||||
throw "Invalid Rust native provenance JSON: $manifestPath"
|
||||
}
|
||||
|
||||
if ($manifest.schema -ne $schema -or
|
||||
$manifest.marker -ne $marker -or
|
||||
$manifest.producer -ne $producer -or
|
||||
$manifest.runtime -ne "rust" -or
|
||||
$manifest.buildSystem -ne "cargo-ndk" -or
|
||||
$manifest.profile -ne "release" -or
|
||||
$manifest.transport -ne $transport -or
|
||||
$manifest.transportMarker -ne $transportMarker -or
|
||||
[int64]$manifest.nativeCoreAbi -ne $nativeCoreAbi) {
|
||||
throw "Rust native provenance identity mismatch: $manifestPath"
|
||||
}
|
||||
|
||||
$package = Get-CargoPackage
|
||||
if ($manifest.package -ne $package.Name -or $manifest.version -ne $package.Version) {
|
||||
throw "Rust package identity does not match provenance"
|
||||
}
|
||||
if ($manifest.cargoTomlSha256 -ne (Get-Sha256 -Path $cargoTomlPath)) {
|
||||
throw "Cargo.toml changed after the production native build"
|
||||
}
|
||||
if ($manifest.cargoLockSha256 -ne (Get-Sha256 -Path $cargoLockPath)) {
|
||||
throw "Cargo.lock changed after the production native build"
|
||||
}
|
||||
if ($manifest.buildInputSha256 -ne (Get-BuildInputHash)) {
|
||||
throw "Rust native source changed after the production native build"
|
||||
}
|
||||
|
||||
$manifestArtifacts = @($manifest.artifacts)
|
||||
if ($manifestArtifacts.Count -ne $specs.Count) {
|
||||
throw "Rust native provenance must contain exactly $($specs.Count) artifacts"
|
||||
}
|
||||
|
||||
foreach ($spec in $specs) {
|
||||
Assert-RustArtifact -Spec $spec -RequireCargoMatch $true
|
||||
$entries = @($manifestArtifacts | Where-Object { $_.abi -eq $spec.Abi })
|
||||
if ($entries.Count -ne 1) {
|
||||
throw "Rust native provenance must contain one entry for $($spec.Abi)"
|
||||
}
|
||||
$entry = $entries[0]
|
||||
$file = Get-Item -LiteralPath $spec.ProductionPath
|
||||
$hash = Get-Sha256 -Path $spec.ProductionPath
|
||||
if ($entry.target -ne $spec.Target -or
|
||||
$entry.path -ne $spec.RelativePath -or
|
||||
[long]$entry.size -ne [long]$file.Length -or
|
||||
$entry.sha256.ToUpperInvariant() -ne $hash) {
|
||||
throw "Rust native provenance artifact mismatch for $($spec.Abi)"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Output "Rust native provenance verified: $marker"
|
||||
@@ -0,0 +1,545 @@
|
||||
# SPDX-FileCopyrightText: 2026 amurcanov
|
||||
# SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[ValidateNotNullOrEmpty()]
|
||||
[long[]]$Seeds = @(104729, 32452843, 49979687, 67867967, 86028121),
|
||||
|
||||
[ValidateRange(1, 100000)]
|
||||
[int]$PassesPerSeed = 2,
|
||||
|
||||
[ValidateRange(1, 1000000)]
|
||||
[int]$LifecycleSeedsPerRun = 256,
|
||||
|
||||
[ValidateRange(1, 2147483647)]
|
||||
[int]$LifecycleSteps = 50000,
|
||||
|
||||
[ValidateRange(2, 2147483647)]
|
||||
[int]$ParserCases = 1000000,
|
||||
|
||||
[ValidateRange(60, 86400)]
|
||||
[int]$StepTimeoutSeconds = 1800,
|
||||
|
||||
[switch]$HarnessSelfTestOnly
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = "Stop"
|
||||
$script:FailureCode = 0
|
||||
$trackedEnvironment = @(
|
||||
"CSQTT_SOAK_SEED",
|
||||
"CSQTT_ANDROID_LIFECYCLE_SEEDS",
|
||||
"CSQTT_ANDROID_LIFECYCLE_STEPS",
|
||||
"CSQTT_ANDROID_PARSER_CASES"
|
||||
)
|
||||
$savedEnvironment = @{}
|
||||
$workspaceRoot = Split-Path -Parent $PSScriptRoot
|
||||
$gradleExecutable = Join-Path $workspaceRoot "gradlew.bat"
|
||||
$testResultRoot = Join-Path $workspaceRoot "app\build\test-results\testDebugUnitTest"
|
||||
$lifecycleClass = "com.csqtt.client.TunnelLifecycleStateChaosTest"
|
||||
$parserClass = "com.csqtt.client.TunnelEventParserTest"
|
||||
$gradleCommonArguments = @(
|
||||
"--no-daemon",
|
||||
"--no-build-cache",
|
||||
"--rerun-tasks",
|
||||
"--console=plain",
|
||||
"--stacktrace"
|
||||
)
|
||||
|
||||
function Set-ProcessEnvironment {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Name,
|
||||
|
||||
[AllowNull()]
|
||||
[string]$Value
|
||||
)
|
||||
|
||||
[Environment]::SetEnvironmentVariable($Name, $Value, "Process")
|
||||
}
|
||||
|
||||
function Stop-ExactProcessTree {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[Diagnostics.Process]$Process,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Name
|
||||
)
|
||||
|
||||
$Process.Refresh()
|
||||
if ($Process.HasExited) {
|
||||
return
|
||||
}
|
||||
|
||||
$taskKill = Join-Path $env:SystemRoot "System32\taskkill.exe"
|
||||
if (-not (Test-Path -LiteralPath $taskKill -PathType Leaf)) {
|
||||
throw "Cannot terminate $Name process tree because taskkill.exe is unavailable"
|
||||
}
|
||||
|
||||
$killer = New-Object Diagnostics.Process
|
||||
try {
|
||||
$killer.StartInfo = New-NativeProcessStartInfo `
|
||||
-Executable $taskKill `
|
||||
-ArgumentList @("/PID", $Process.Id.ToString([Globalization.CultureInfo]::InvariantCulture), "/T", "/F")
|
||||
if (-not $killer.Start()) {
|
||||
throw "Failed to start taskkill for $Name"
|
||||
}
|
||||
if (-not $killer.WaitForExit(10000)) {
|
||||
$killer.Kill()
|
||||
throw "taskkill timed out while terminating $Name process tree rooted at PID $($Process.Id)"
|
||||
}
|
||||
$killer.WaitForExit()
|
||||
$killer.Refresh()
|
||||
$killExitCodeValue = $killer.ExitCode
|
||||
if ($null -eq $killExitCodeValue -or $killExitCodeValue -isnot [int]) {
|
||||
throw "taskkill returned an invalid exit code while terminating $Name"
|
||||
}
|
||||
[int]$killExitCode = $killExitCodeValue
|
||||
} finally {
|
||||
$killer.Dispose()
|
||||
}
|
||||
$Process.Refresh()
|
||||
if ($killExitCode -ne 0 -or -not $Process.HasExited) {
|
||||
throw "Failed to terminate exact $Name process tree rooted at PID $($Process.Id); taskkill exit code $killExitCode"
|
||||
}
|
||||
}
|
||||
|
||||
function ConvertTo-NativeArgument {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[AllowEmptyString()]
|
||||
[string]$Value
|
||||
)
|
||||
|
||||
if ($Value.Length -gt 0 -and $Value -notmatch '[\s"]') {
|
||||
return $Value
|
||||
}
|
||||
|
||||
$builder = New-Object Text.StringBuilder
|
||||
[void]$builder.Append('"')
|
||||
[int]$backslashes = 0
|
||||
foreach ($character in $Value.ToCharArray()) {
|
||||
if ($character -eq '\') {
|
||||
$backslashes++
|
||||
} elseif ($character -eq '"') {
|
||||
[void]$builder.Append(('\' * (($backslashes * 2) + 1)))
|
||||
[void]$builder.Append('"')
|
||||
$backslashes = 0
|
||||
} else {
|
||||
if ($backslashes -gt 0) {
|
||||
[void]$builder.Append(('\' * $backslashes))
|
||||
$backslashes = 0
|
||||
}
|
||||
[void]$builder.Append($character)
|
||||
}
|
||||
}
|
||||
if ($backslashes -gt 0) {
|
||||
[void]$builder.Append(('\' * ($backslashes * 2)))
|
||||
}
|
||||
[void]$builder.Append('"')
|
||||
return $builder.ToString()
|
||||
}
|
||||
|
||||
function New-NativeProcessStartInfo {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Executable,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
[string[]]$ArgumentList
|
||||
)
|
||||
|
||||
$resolvedExecutable = $Executable
|
||||
if ([IO.Path]::IsPathRooted($Executable)) {
|
||||
if (-not (Test-Path -LiteralPath $Executable -PathType Leaf)) {
|
||||
throw "Executable not found at $Executable"
|
||||
}
|
||||
$resolvedExecutable = (Resolve-Path -LiteralPath $Executable).Path
|
||||
}
|
||||
|
||||
$startInfo = New-Object Diagnostics.ProcessStartInfo
|
||||
$startInfo.UseShellExecute = $false
|
||||
$startInfo.CreateNoWindow = $false
|
||||
$startInfo.WorkingDirectory = $workspaceRoot
|
||||
$extension = [IO.Path]::GetExtension($resolvedExecutable)
|
||||
if ($extension -ieq ".bat" -or $extension -ieq ".cmd") {
|
||||
$command = ConvertTo-NativeArgument -Value $resolvedExecutable
|
||||
if ($ArgumentList.Count -gt 0) {
|
||||
$command += " " + (($ArgumentList | ForEach-Object { ConvertTo-NativeArgument -Value $_ }) -join " ")
|
||||
}
|
||||
$startInfo.FileName = Join-Path $env:SystemRoot "System32\cmd.exe"
|
||||
$startInfo.Arguments = "/D /S /C `"$command`""
|
||||
} else {
|
||||
$startInfo.FileName = $resolvedExecutable
|
||||
$startInfo.Arguments = (($ArgumentList | ForEach-Object { ConvertTo-NativeArgument -Value $_ }) -join " ")
|
||||
}
|
||||
return $startInfo
|
||||
}
|
||||
|
||||
function Invoke-NativeStep {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Name,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Executable,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
[string[]]$ArgumentList,
|
||||
|
||||
[ValidateRange(1, 86400)]
|
||||
[int]$TimeoutSeconds = $StepTimeoutSeconds
|
||||
)
|
||||
|
||||
[Console]::Out.WriteLine("")
|
||||
[Console]::Out.WriteLine("=== $Name ===")
|
||||
$process = $null
|
||||
$started = $false
|
||||
$finished = $false
|
||||
try {
|
||||
$process = New-Object Diagnostics.Process
|
||||
$process.StartInfo = New-NativeProcessStartInfo `
|
||||
-Executable $Executable `
|
||||
-ArgumentList $ArgumentList
|
||||
if (-not $process.Start()) {
|
||||
throw "$Name failed to start"
|
||||
}
|
||||
$started = $true
|
||||
if (-not $process.WaitForExit($TimeoutSeconds * 1000)) {
|
||||
$script:FailureCode = 124
|
||||
Stop-ExactProcessTree -Process $process -Name $Name
|
||||
throw "$Name timed out after $TimeoutSeconds seconds; process tree rooted at PID $($process.Id) was terminated"
|
||||
}
|
||||
$process.WaitForExit()
|
||||
$process.Refresh()
|
||||
if (-not $process.HasExited) {
|
||||
throw "$Name process state is indeterminate after WaitForExit"
|
||||
}
|
||||
$finished = $true
|
||||
$exitCodeValue = $process.ExitCode
|
||||
if ($null -eq $exitCodeValue -or $exitCodeValue -isnot [int]) {
|
||||
throw "$Name returned an invalid exit code"
|
||||
}
|
||||
[int]$nativeCode = $exitCodeValue
|
||||
if ($nativeCode -ne 0) {
|
||||
if ($nativeCode -gt 0 -and $nativeCode -le 255) {
|
||||
$script:FailureCode = $nativeCode
|
||||
} else {
|
||||
$script:FailureCode = 1
|
||||
}
|
||||
throw "$Name failed with exit code $nativeCode"
|
||||
}
|
||||
} finally {
|
||||
if (-not $finished -and $null -ne $process -and $started) {
|
||||
$process.Refresh()
|
||||
if (-not $process.HasExited) {
|
||||
Stop-ExactProcessTree -Process $process -Name $Name
|
||||
}
|
||||
}
|
||||
if ($null -ne $process) {
|
||||
$process.Dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-NativeStepFailClosed {
|
||||
$savedFailureCode = $script:FailureCode
|
||||
Invoke-NativeStep `
|
||||
-Name "Harness child exit 0 probe" `
|
||||
-Executable $env:ComSpec `
|
||||
-ArgumentList @("/D", "/S", "/C", "exit 0") `
|
||||
-TimeoutSeconds 30
|
||||
|
||||
$caughtFailure = $false
|
||||
try {
|
||||
Invoke-NativeStep `
|
||||
-Name "Harness child exit 7 probe" `
|
||||
-Executable $env:ComSpec `
|
||||
-ArgumentList @("/D", "/S", "/C", "exit 7") `
|
||||
-TimeoutSeconds 30
|
||||
} catch {
|
||||
$caughtFailure = $true
|
||||
if ($script:FailureCode -ne 7) {
|
||||
throw "Harness exit 7 probe was caught with code $($script:FailureCode), expected 7"
|
||||
}
|
||||
if ($_.Exception.Message -notmatch 'exit code 7$') {
|
||||
throw "Harness exit 7 probe produced an unexpected failure: $($_.Exception.Message)"
|
||||
}
|
||||
} finally {
|
||||
$script:FailureCode = $savedFailureCode
|
||||
}
|
||||
if (-not $caughtFailure) {
|
||||
throw "Harness accepted a child process that exited with code 7"
|
||||
}
|
||||
[Console]::Out.WriteLine("Harness child exit probes passed")
|
||||
}
|
||||
|
||||
function Get-ResultStamp {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Path
|
||||
)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
|
||||
return $null
|
||||
}
|
||||
$item = Get-Item -LiteralPath $Path
|
||||
return "$($item.LastWriteTimeUtc.Ticks):$($item.Length)"
|
||||
}
|
||||
|
||||
function Get-ResultSnapshot {
|
||||
$snapshot = @{}
|
||||
if (-not (Test-Path -LiteralPath $testResultRoot -PathType Container)) {
|
||||
return $snapshot
|
||||
}
|
||||
foreach ($item in Get-ChildItem -LiteralPath $testResultRoot -Filter "TEST-*.xml" -File) {
|
||||
$snapshot[$item.FullName] = "$($item.LastWriteTimeUtc.Ticks):$($item.Length)"
|
||||
}
|
||||
return $snapshot
|
||||
}
|
||||
|
||||
function Read-TestSuite {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Path
|
||||
)
|
||||
|
||||
try {
|
||||
[xml]$document = Get-Content -LiteralPath $Path -Raw
|
||||
} catch {
|
||||
throw "Invalid JUnit XML at ${Path}: $($_.Exception.Message)"
|
||||
}
|
||||
if ($null -eq $document.testsuite) {
|
||||
throw "JUnit XML does not contain a testsuite at $Path"
|
||||
}
|
||||
return $document.testsuite
|
||||
}
|
||||
|
||||
function Assert-TestSuite {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Path,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
[long]$MinimumTests,
|
||||
|
||||
[AllowNull()]
|
||||
[AllowEmptyString()]
|
||||
[string]$ExpectedClass
|
||||
)
|
||||
|
||||
$suite = Read-TestSuite -Path $Path
|
||||
$tests = [long]$suite.tests
|
||||
$skipped = [long]$suite.skipped
|
||||
$failures = [long]$suite.failures
|
||||
$errors = [long]$suite.errors
|
||||
if ($tests -lt $MinimumTests) {
|
||||
throw "Expected at least $MinimumTests tests in $Path, but Gradle reported $tests"
|
||||
}
|
||||
if ($skipped -ne 0) {
|
||||
throw "Gradle skipped $skipped tests in $Path"
|
||||
}
|
||||
if ($failures -ne 0 -or $errors -ne 0) {
|
||||
throw "JUnit result contains $failures failures and $errors errors in $Path"
|
||||
}
|
||||
if (-not [string]::IsNullOrEmpty($ExpectedClass)) {
|
||||
if ([string]$suite.name -ne $ExpectedClass) {
|
||||
throw "Expected JUnit suite $ExpectedClass, found $($suite.name)"
|
||||
}
|
||||
foreach ($testCase in @($suite.testcase)) {
|
||||
if ([string]$testCase.classname -ne $ExpectedClass) {
|
||||
throw "Unexpected test class $($testCase.classname) in $Path"
|
||||
}
|
||||
}
|
||||
}
|
||||
return $tests
|
||||
}
|
||||
|
||||
function Assert-ExactTestResult {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$ClassName,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
[long]$MinimumTests,
|
||||
|
||||
[AllowNull()]
|
||||
[string]$PreviousStamp
|
||||
)
|
||||
|
||||
$path = Join-Path $testResultRoot "TEST-$ClassName.xml"
|
||||
$currentStamp = Get-ResultStamp -Path $path
|
||||
if ($null -eq $currentStamp) {
|
||||
throw "Gradle produced no JUnit result for required test class $ClassName"
|
||||
}
|
||||
if ($null -ne $PreviousStamp -and $currentStamp -eq $PreviousStamp) {
|
||||
throw "JUnit result for required test class $ClassName was not regenerated"
|
||||
}
|
||||
return Assert-TestSuite -Path $path -MinimumTests $MinimumTests -ExpectedClass $ClassName
|
||||
}
|
||||
|
||||
function Assert-FullTestResults {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[hashtable]$PreviousSnapshot
|
||||
)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $testResultRoot -PathType Container)) {
|
||||
throw "Gradle produced no test result directory at $testResultRoot"
|
||||
}
|
||||
|
||||
$files = @(Get-ChildItem -LiteralPath $testResultRoot -Filter "TEST-*.xml" -File)
|
||||
if ($files.Count -eq 0) {
|
||||
throw "Gradle produced zero JUnit test suites"
|
||||
}
|
||||
|
||||
[long]$totalTests = 0
|
||||
foreach ($file in $files) {
|
||||
$currentStamp = Get-ResultStamp -Path $file.FullName
|
||||
if ($PreviousSnapshot.ContainsKey($file.FullName) -and $PreviousSnapshot[$file.FullName] -eq $currentStamp) {
|
||||
throw "JUnit result was not regenerated for $($file.Name)"
|
||||
}
|
||||
$totalTests += Assert-TestSuite -Path $file.FullName -MinimumTests 1 -ExpectedClass $null
|
||||
}
|
||||
if ($totalTests -le 0) {
|
||||
throw "Gradle reported zero executed tests"
|
||||
}
|
||||
|
||||
Assert-ExactTestResult `
|
||||
-ClassName $lifecycleClass `
|
||||
-MinimumTests 4 `
|
||||
-PreviousStamp $PreviousSnapshot[(Join-Path $testResultRoot "TEST-$lifecycleClass.xml")] | Out-Null
|
||||
Assert-ExactTestResult `
|
||||
-ClassName $parserClass `
|
||||
-MinimumTests 6 `
|
||||
-PreviousStamp $PreviousSnapshot[(Join-Path $testResultRoot "TEST-$parserClass.xml")] | Out-Null
|
||||
return $totalTests
|
||||
}
|
||||
|
||||
function Get-EffectiveSeed {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[long]$BaseSeed,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
[int]$Pass
|
||||
)
|
||||
|
||||
[decimal]$wideSeed = [decimal]$BaseSeed + ([decimal]$Pass * [decimal]$LifecycleSeedsPerRun)
|
||||
[decimal]$lastLifecycleSeed = $wideSeed + [decimal]$LifecycleSeedsPerRun - 1
|
||||
if ($wideSeed -lt [decimal][long]::MinValue -or $lastLifecycleSeed -gt [decimal][long]::MaxValue) {
|
||||
throw "Seed range overflows signed 64-bit arithmetic for base seed $BaseSeed pass $Pass"
|
||||
}
|
||||
return [long]$wideSeed
|
||||
}
|
||||
|
||||
function Set-ChaosEnvironment {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[long]$Seed
|
||||
)
|
||||
|
||||
$culture = [Globalization.CultureInfo]::InvariantCulture
|
||||
Set-ProcessEnvironment "CSQTT_SOAK_SEED" $Seed.ToString($culture)
|
||||
Set-ProcessEnvironment "CSQTT_ANDROID_LIFECYCLE_SEEDS" $LifecycleSeedsPerRun.ToString($culture)
|
||||
Set-ProcessEnvironment "CSQTT_ANDROID_LIFECYCLE_STEPS" $LifecycleSteps.ToString($culture)
|
||||
Set-ProcessEnvironment "CSQTT_ANDROID_PARSER_CASES" $ParserCases.ToString($culture)
|
||||
}
|
||||
|
||||
if ($Seeds.Count -eq 0) {
|
||||
throw "At least one seed is required"
|
||||
}
|
||||
if (-not $HarnessSelfTestOnly -and -not (Test-Path -LiteralPath $gradleExecutable -PathType Leaf)) {
|
||||
throw "Gradle wrapper not found at $gradleExecutable"
|
||||
}
|
||||
|
||||
foreach ($name in $trackedEnvironment) {
|
||||
$savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, "Process")
|
||||
}
|
||||
|
||||
try {
|
||||
Assert-NativeStepFailClosed
|
||||
if ($HarnessSelfTestOnly) {
|
||||
[Console]::Out.WriteLine("Android stability harness self-test passed")
|
||||
} else {
|
||||
Set-ChaosEnvironment -Seed (Get-EffectiveSeed -BaseSeed $Seeds[0] -Pass 0)
|
||||
$fullSnapshot = Get-ResultSnapshot
|
||||
Invoke-NativeStep `
|
||||
-Name "Full Android debug unit test suite" `
|
||||
-Executable $gradleExecutable `
|
||||
-ArgumentList (@(":app:testDebugUnitTest") + $gradleCommonArguments)
|
||||
$fullTests = Assert-FullTestResults -PreviousSnapshot $fullSnapshot
|
||||
|
||||
Invoke-NativeStep `
|
||||
-Name "Android debug lint" `
|
||||
-Executable $gradleExecutable `
|
||||
-ArgumentList (@(":app:lintDebug") + $gradleCommonArguments)
|
||||
|
||||
[long]$executedChaosTests = 0
|
||||
[long]$executedChaosRuns = 0
|
||||
foreach ($baseSeed in $Seeds) {
|
||||
for ($pass = 0; $pass -lt $PassesPerSeed; $pass++) {
|
||||
$effectiveSeed = Get-EffectiveSeed -BaseSeed $baseSeed -Pass $pass
|
||||
Set-ChaosEnvironment -Seed $effectiveSeed
|
||||
$lifecyclePath = Join-Path $testResultRoot "TEST-$lifecycleClass.xml"
|
||||
$parserPath = Join-Path $testResultRoot "TEST-$parserClass.xml"
|
||||
$lifecycleStamp = Get-ResultStamp -Path $lifecyclePath
|
||||
$parserStamp = Get-ResultStamp -Path $parserPath
|
||||
Invoke-NativeStep `
|
||||
-Name "Android lifecycle and parser chaos seed $effectiveSeed pass $($pass + 1)" `
|
||||
-Executable $gradleExecutable `
|
||||
-ArgumentList (
|
||||
@(
|
||||
":app:testDebugUnitTest",
|
||||
"--tests",
|
||||
$lifecycleClass,
|
||||
"--tests",
|
||||
$parserClass
|
||||
) + $gradleCommonArguments
|
||||
)
|
||||
$executedChaosTests += Assert-ExactTestResult `
|
||||
-ClassName $lifecycleClass `
|
||||
-MinimumTests 4 `
|
||||
-PreviousStamp $lifecycleStamp
|
||||
$executedChaosTests += Assert-ExactTestResult `
|
||||
-ClassName $parserClass `
|
||||
-MinimumTests 6 `
|
||||
-PreviousStamp $parserStamp
|
||||
$executedChaosRuns++
|
||||
}
|
||||
}
|
||||
|
||||
$expectedChaosRuns = [long]$Seeds.Count * [long]$PassesPerSeed
|
||||
if ($executedChaosRuns -ne $expectedChaosRuns) {
|
||||
throw "Expected $expectedChaosRuns chaos runs, executed $executedChaosRuns"
|
||||
}
|
||||
if ($executedChaosTests -lt $expectedChaosRuns * 10) {
|
||||
throw "Expected at least $($expectedChaosRuns * 10) chaos tests, executed $executedChaosTests"
|
||||
}
|
||||
|
||||
[Console]::Out.WriteLine("")
|
||||
[Console]::Out.WriteLine("Android stability soak passed")
|
||||
[Console]::Out.WriteLine("Full debug tests: $fullTests")
|
||||
[Console]::Out.WriteLine("Chaos runs: $executedChaosRuns")
|
||||
[Console]::Out.WriteLine("Chaos tests: $executedChaosTests")
|
||||
[Console]::Out.WriteLine("Base seeds: $($Seeds -join ', ')")
|
||||
[Console]::Out.WriteLine("Lifecycle seeds per run: $LifecycleSeedsPerRun")
|
||||
[Console]::Out.WriteLine("Lifecycle steps per seed: $LifecycleSteps")
|
||||
[Console]::Out.WriteLine("Parser cases per run: $ParserCases")
|
||||
}
|
||||
} catch {
|
||||
if ($script:FailureCode -eq 0) {
|
||||
$script:FailureCode = 1
|
||||
}
|
||||
[Console]::Error.WriteLine($_.Exception.Message)
|
||||
} finally {
|
||||
foreach ($name in $trackedEnvironment) {
|
||||
Set-ProcessEnvironment $name $savedEnvironment[$name]
|
||||
}
|
||||
}
|
||||
|
||||
if ($script:FailureCode -ne 0) {
|
||||
exit $script:FailureCode
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidateSet("Write", "Verify")]
|
||||
[string]$Mode,
|
||||
[string]$Root
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($Root)) {
|
||||
$projectRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot ".."))
|
||||
}
|
||||
else {
|
||||
$projectRoot = [IO.Path]::GetFullPath($Root)
|
||||
}
|
||||
|
||||
$assetDirectory = Join-Path $projectRoot "app\src\main\assets"
|
||||
$manifestPath = Join-Path $assetDirectory "csqtt.server-provenance.json"
|
||||
$cargoTomlPath = Join-Path $projectRoot "rust-server\Cargo.toml"
|
||||
$cargoLockPath = Join-Path $projectRoot "rust-server\Cargo.lock"
|
||||
$wireProtocolPath = Join-Path $projectRoot "shared\wire_protocol.rs"
|
||||
$schema = "csqtt.server-asset-provenance.v2"
|
||||
$marker = "CSQTT_RUST_SERVER_PRODUCTION_V1"
|
||||
$assetSpecs = @(
|
||||
[pscustomobject]@{ AssetName = "csqtt-linux-amd64"; Target = "x86_64-unknown-linux-musl"; ElfClass = 2; ElfMachine = 62 },
|
||||
[pscustomobject]@{ AssetName = "csqtt-linux-arm64"; Target = "aarch64-unknown-linux-musl"; ElfClass = 2; ElfMachine = 183 },
|
||||
[pscustomobject]@{ AssetName = "csqtt-linux-armv7"; Target = "armv7-unknown-linux-musleabihf"; ElfClass = 1; ElfMachine = 40 }
|
||||
)
|
||||
|
||||
function Assert-RegularFile {
|
||||
param([string]$Path, [string]$Label)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
|
||||
throw "$Label not found: $Path"
|
||||
}
|
||||
if ((Get-Item -LiteralPath $Path).Length -le 0) {
|
||||
throw "$Label is empty: $Path"
|
||||
}
|
||||
}
|
||||
|
||||
function Get-Sha256 {
|
||||
param([string]$Path)
|
||||
|
||||
$stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
|
||||
$hasher = [Security.Cryptography.SHA256]::Create()
|
||||
try {
|
||||
return ([BitConverter]::ToString($hasher.ComputeHash($stream))).Replace("-", "")
|
||||
}
|
||||
finally {
|
||||
$hasher.Dispose()
|
||||
$stream.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
function Get-CargoPackage {
|
||||
Assert-RegularFile -Path $cargoTomlPath -Label "Server Cargo.toml"
|
||||
$insidePackage = $false
|
||||
$name = $null
|
||||
$version = $null
|
||||
foreach ($line in Get-Content -LiteralPath $cargoTomlPath) {
|
||||
$trimmed = $line.Trim()
|
||||
if ($trimmed -eq "[package]") {
|
||||
$insidePackage = $true
|
||||
continue
|
||||
}
|
||||
if ($insidePackage -and $trimmed.StartsWith("[")) {
|
||||
break
|
||||
}
|
||||
if ($insidePackage -and $trimmed -match '^(name|version)\s*=\s*"([^"]+)"') {
|
||||
if ($matches[1] -eq "name") {
|
||||
$name = $matches[2]
|
||||
}
|
||||
else {
|
||||
$version = $matches[2]
|
||||
}
|
||||
}
|
||||
}
|
||||
if ([string]::IsNullOrWhiteSpace($name) -or [string]::IsNullOrWhiteSpace($version)) {
|
||||
throw "Unable to read Rust server package identity"
|
||||
}
|
||||
return [pscustomobject]@{ Name = $name; Version = $version }
|
||||
}
|
||||
|
||||
function Get-WireProtocolRevision {
|
||||
Assert-RegularFile -Path $wireProtocolPath -Label "Wire protocol revision source"
|
||||
$match = [regex]::Match(
|
||||
[IO.File]::ReadAllText($wireProtocolPath),
|
||||
'WIRE_PROTOCOL_REVISION\s*:\s*&str\s*=\s*"([^"]+)"'
|
||||
)
|
||||
if (-not $match.Success) {
|
||||
throw "Wire protocol revision is missing"
|
||||
}
|
||||
return $match.Groups[1].Value
|
||||
}
|
||||
|
||||
function Get-BuildInputHash {
|
||||
$files = @(
|
||||
(Join-Path $projectRoot "rust-server\build_linux.bat"),
|
||||
(Join-Path $projectRoot "rust-server\build_linux.sh"),
|
||||
$cargoTomlPath,
|
||||
$cargoLockPath,
|
||||
$wireProtocolPath,
|
||||
(Join-Path $projectRoot "shared\selective_fec.rs"),
|
||||
(Join-Path $projectRoot "shared\striped_scheduler.rs"),
|
||||
$PSCommandPath
|
||||
)
|
||||
$files += Get-ChildItem -LiteralPath (Join-Path $projectRoot "rust-server") -File -Filter *.rs |
|
||||
ForEach-Object { $_.FullName }
|
||||
$rootPrefix = $projectRoot.TrimEnd([char[]]@('\', '/')) + [IO.Path]::DirectorySeparatorChar
|
||||
$builder = New-Object Text.StringBuilder
|
||||
foreach ($file in @($files | Sort-Object -Unique)) {
|
||||
Assert-RegularFile -Path $file -Label "Server build input"
|
||||
$fullPath = [IO.Path]::GetFullPath($file)
|
||||
if (-not $fullPath.StartsWith($rootPrefix, [StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw "Server build input escaped project root: $fullPath"
|
||||
}
|
||||
[void]$builder.Append($fullPath.Substring($rootPrefix.Length).Replace("\", "/"))
|
||||
[void]$builder.Append(":")
|
||||
[void]$builder.Append((Get-Sha256 -Path $fullPath))
|
||||
[void]$builder.Append("`n")
|
||||
}
|
||||
$hash = [Security.Cryptography.SHA256]::Create()
|
||||
try {
|
||||
return ([BitConverter]::ToString($hash.ComputeHash([Text.Encoding]::UTF8.GetBytes($builder.ToString())))).Replace("-", "")
|
||||
}
|
||||
finally {
|
||||
$hash.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-ServerBinary {
|
||||
param($Spec, [string]$Revision)
|
||||
|
||||
$binaryPath = Join-Path $assetDirectory $Spec.AssetName
|
||||
Assert-RegularFile -Path $binaryPath -Label "Linux server asset $($Spec.AssetName)"
|
||||
[byte[]]$bytes = [IO.File]::ReadAllBytes($binaryPath)
|
||||
if ($bytes.Length -lt 20 -or $bytes[0] -ne 0x7f -or $bytes[1] -ne 0x45 -or $bytes[2] -ne 0x4c -or $bytes[3] -ne 0x46) {
|
||||
throw "Linux server asset $($Spec.AssetName) is not ELF"
|
||||
}
|
||||
if ($bytes[4] -ne $Spec.ElfClass -or $bytes[5] -ne 1) {
|
||||
throw "ELF class or endianness mismatch for $($Spec.AssetName)"
|
||||
}
|
||||
$machine = [int]$bytes[18] -bor ([int]$bytes[19] -shl 8)
|
||||
if ($machine -ne $Spec.ElfMachine) {
|
||||
throw "ELF machine mismatch for $($Spec.AssetName): expected $($Spec.ElfMachine), got $machine"
|
||||
}
|
||||
if (-not ([Text.Encoding]::ASCII.GetString($bytes).Contains($Revision))) {
|
||||
throw "Linux server asset $($Spec.AssetName) does not expose wire protocol revision $Revision"
|
||||
}
|
||||
$file = Get-Item -LiteralPath $binaryPath
|
||||
return [pscustomobject]@{
|
||||
assetName = $Spec.AssetName
|
||||
target = $Spec.Target
|
||||
elfClass = $Spec.ElfClass
|
||||
elfMachine = $Spec.ElfMachine
|
||||
binarySize = [int64]$file.Length
|
||||
binarySha256 = Get-Sha256 -Path $binaryPath
|
||||
}
|
||||
}
|
||||
|
||||
$package = Get-CargoPackage
|
||||
$revision = Get-WireProtocolRevision
|
||||
$buildInputHash = Get-BuildInputHash
|
||||
|
||||
if ($Mode -eq "Write") {
|
||||
Assert-RegularFile -Path $cargoLockPath -Label "Server Cargo.lock"
|
||||
$artifacts = @($assetSpecs | ForEach-Object { Assert-ServerBinary -Spec $_ -Revision $revision })
|
||||
$manifest = [ordered]@{
|
||||
schema = $schema
|
||||
marker = $marker
|
||||
producer = "rust-server/build_linux.bat"
|
||||
runtime = "rust"
|
||||
package = $package.Name
|
||||
version = $package.Version
|
||||
wireProtocolRevision = $revision
|
||||
buildInputSha256 = $buildInputHash
|
||||
cargoTomlSha256 = Get-Sha256 -Path $cargoTomlPath
|
||||
cargoLockSha256 = Get-Sha256 -Path $cargoLockPath
|
||||
artifacts = $artifacts
|
||||
generatedAtUtc = [DateTime]::UtcNow.ToString("o")
|
||||
}
|
||||
$temporaryPath = "$manifestPath.tmp.$PID"
|
||||
[IO.File]::WriteAllText($temporaryPath, ($manifest | ConvertTo-Json -Depth 4) + [Environment]::NewLine, (New-Object Text.UTF8Encoding($false)))
|
||||
Move-Item -LiteralPath $temporaryPath -Destination $manifestPath -Force
|
||||
Write-Output "Wrote Rust server provenance: $manifestPath"
|
||||
exit 0
|
||||
}
|
||||
|
||||
Assert-RegularFile -Path $manifestPath -Label "Rust server provenance"
|
||||
try {
|
||||
$manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json
|
||||
}
|
||||
catch {
|
||||
throw "Invalid Rust server provenance JSON: $manifestPath"
|
||||
}
|
||||
|
||||
if ($manifest.schema -ne $schema -or
|
||||
$manifest.marker -ne $marker -or
|
||||
$manifest.producer -ne "rust-server/build_linux.bat" -or
|
||||
$manifest.runtime -ne "rust") {
|
||||
throw "Rust server provenance identity mismatch"
|
||||
}
|
||||
if ($manifest.package -ne $package.Name -or
|
||||
$manifest.version -ne $package.Version -or
|
||||
$manifest.wireProtocolRevision -ne $revision) {
|
||||
throw "Rust server package or wire protocol identity changed after build"
|
||||
}
|
||||
if ($manifest.cargoTomlSha256 -ne (Get-Sha256 -Path $cargoTomlPath) -or
|
||||
$manifest.cargoLockSha256 -ne (Get-Sha256 -Path $cargoLockPath) -or
|
||||
$manifest.buildInputSha256 -ne $buildInputHash) {
|
||||
throw "Rust server source changed after the production asset build"
|
||||
}
|
||||
$manifestArtifacts = @($manifest.artifacts)
|
||||
if ($manifestArtifacts.Count -ne $assetSpecs.Count) {
|
||||
throw "Rust server provenance artifact count mismatch"
|
||||
}
|
||||
foreach ($spec in $assetSpecs) {
|
||||
$matches = @($manifestArtifacts | Where-Object { $_.assetName -eq $spec.AssetName })
|
||||
if ($matches.Count -ne 1) {
|
||||
throw "Rust server provenance is missing $($spec.AssetName)"
|
||||
}
|
||||
$actual = Assert-ServerBinary -Spec $spec -Revision $revision
|
||||
$record = $matches[0]
|
||||
if ($record.target -ne $actual.target -or
|
||||
[int]$record.elfClass -ne [int]$actual.elfClass -or
|
||||
[int]$record.elfMachine -ne [int]$actual.elfMachine -or
|
||||
[int64]$record.binarySize -ne [int64]$actual.binarySize -or
|
||||
$record.binarySha256 -ne $actual.binarySha256) {
|
||||
throw "Rust server asset does not match provenance: $($spec.AssetName)"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Output "Rust server provenance verified: $marker"
|
||||
@@ -0,0 +1,208 @@
|
||||
#!/bin/bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
workspace="${CSQTT_WORKSPACE:-/path/to/your/csqtt}"
|
||||
peer_port="${CSQTT_TEST_PEER_PORT:-46900}"
|
||||
web_port="${CSQTT_TEST_WEB_PORT:-46902}"
|
||||
ssh_port="${CSQTT_TEST_SSH_PORT:-2222}"
|
||||
script_source="${workspace}/app/src/main/assets/deploy.sh"
|
||||
binary_source="${CSQTT_TEST_SERVER_BINARY:-${workspace}/app/src/main/assets/csqtt-linux-amd64}"
|
||||
|
||||
[ "$(id -u)" -eq 0 ] || { echo "run as root" >&2; exit 2; }
|
||||
[ -x "$binary_source" ] || { echo "missing executable server asset: $binary_source" >&2; exit 2; }
|
||||
[ -f "$script_source" ] || { echo "missing deploy asset: $script_source" >&2; exit 2; }
|
||||
command -v systemctl >/dev/null 2>&1 || { echo "systemctl is unavailable" >&2; exit 2; }
|
||||
command -v python3 >/dev/null 2>&1 || { echo "python3 is unavailable" >&2; exit 2; }
|
||||
command -v openssl >/dev/null 2>&1 || { echo "openssl is unavailable" >&2; exit 2; }
|
||||
|
||||
deploy_env=(
|
||||
"CSQTT_PEER_PORT=${peer_port}"
|
||||
"CSQTT_WEB_PORT=${web_port}"
|
||||
"CSQTT_SSH_PORT=${ssh_port}"
|
||||
"CSQTT_START_STABILITY_SECONDS=1"
|
||||
)
|
||||
|
||||
prepare_upload() {
|
||||
install -m 0755 "$script_source" /tmp/deploy.sh
|
||||
install -m 0755 "$binary_source" /tmp/.csqtt-upload-server
|
||||
install -m 0600 /dev/null /tmp/.csqtt-upload-web.env
|
||||
install -m 0600 /dev/null /tmp/.csqtt-upload-overrides.json
|
||||
printf '%s\n' 'CSQTT_WEB_USER=deploy-test' 'CSQTT_WEB_PASS=deploy-test-password' > /tmp/.csqtt-upload-web.env
|
||||
printf '%s\n' '{"main_password":"deploy-test-main-password","device_id":"deploy-wsl-matrix"}' > /tmp/.csqtt-upload-overrides.json
|
||||
chmod 0600 /tmp/.csqtt-upload-web.env /tmp/.csqtt-upload-overrides.json
|
||||
}
|
||||
|
||||
prepare_tls() {
|
||||
mkdir -p /etc/csqtt
|
||||
if ! openssl x509 -noout -in /etc/csqtt/web_cert.pem >/dev/null 2>&1 || \
|
||||
! openssl pkey -noout -in /etc/csqtt/web_key.pem >/dev/null 2>&1; then
|
||||
rm -f /etc/csqtt/web_cert.pem /etc/csqtt/web_key.pem
|
||||
openssl req -x509 -newkey rsa:2048 -nodes -days 2 \
|
||||
-subj '/CN=csqtt-wsl-deploy-test' \
|
||||
-keyout /etc/csqtt/web_key.pem \
|
||||
-out /etc/csqtt/web_cert.pem >/dev/null 2>&1
|
||||
chmod 600 /etc/csqtt/web_key.pem
|
||||
chmod 644 /etc/csqtt/web_cert.pem
|
||||
fi
|
||||
}
|
||||
|
||||
assert_running() {
|
||||
local mode="$1" code
|
||||
if [ "$mode" = "systemd" ]; then
|
||||
systemctl is-active --quiet csqtt
|
||||
else
|
||||
docker inspect --format '{{.State.Running}}' csqtt | grep -qx true
|
||||
fi
|
||||
ip link show csqtt1 >/dev/null 2>&1
|
||||
ss -H -lun "sport = :${peer_port}" | grep -q .
|
||||
code="$(curl -k -sS -o /dev/null -w '%{http_code}' --connect-timeout 2 --max-time 4 "https://127.0.0.1:${web_port}/" || true)"
|
||||
case "$code" in 200|301|302|401) return 0 ;; esac
|
||||
code="$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 2 --max-time 4 "http://127.0.0.1:${web_port}/" || true)"
|
||||
case "$code" in 200|301|302|401) return 0 ;; esac
|
||||
echo "web health check failed: https=${code}" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
deploy() {
|
||||
local mode="$1"
|
||||
prepare_upload
|
||||
env "${deploy_env[@]}" "CSQTT_DEPLOY_MODE=${mode}" bash /tmp/deploy.sh install
|
||||
assert_running "$mode"
|
||||
echo "PASS ${mode} deploy"
|
||||
}
|
||||
|
||||
panel_cookie=""
|
||||
|
||||
panel_login() {
|
||||
[ -n "$panel_cookie" ] && rm -f -- "$panel_cookie"
|
||||
panel_cookie="$(mktemp)"
|
||||
local code
|
||||
code="$(curl -k -sS -o /dev/null -w '%{http_code}' -c "$panel_cookie" \
|
||||
--connect-timeout 2 --max-time 4 -H 'content-type: application/json' \
|
||||
--data '{"user":"deploy-test","pass":"deploy-test-password"}' \
|
||||
"https://127.0.0.1:${web_port}/api/login" || true)"
|
||||
[ "$code" = "200" ] || { echo "panel login failed: ${code}" >&2; return 1; }
|
||||
}
|
||||
|
||||
panel_settings() {
|
||||
curl -k -fsS -b "$panel_cookie" --connect-timeout 2 --max-time 4 \
|
||||
"https://127.0.0.1:${web_port}/api/settings"
|
||||
}
|
||||
|
||||
assert_dns() {
|
||||
local expected="$1" settings
|
||||
settings="$(panel_settings)"
|
||||
python3 - "$expected" "$settings" <<'PY'
|
||||
import json
|
||||
import sys
|
||||
|
||||
expected = sys.argv[1]
|
||||
settings = json.loads(sys.argv[2])
|
||||
actual = ','.join(filter(None, [settings.get('dns_primary', ''), settings.get('dns_secondary', '')]))
|
||||
if actual != expected:
|
||||
raise SystemExit(f'DNS mismatch: expected {expected}, got {actual}')
|
||||
PY
|
||||
}
|
||||
|
||||
set_dns() {
|
||||
local payload="$1" code
|
||||
code="$(curl -k -sS -o /dev/null -w '%{http_code}' -b "$panel_cookie" \
|
||||
--connect-timeout 2 --max-time 4 -H 'content-type: application/json' \
|
||||
--data "$payload" "https://127.0.0.1:${web_port}/api/settings" || true)"
|
||||
[ "$code" = "200" ] || { echo "panel DNS update failed: ${code}" >&2; return 1; }
|
||||
}
|
||||
|
||||
start_udp_blocker() {
|
||||
python3 - "$peer_port" <<'PY' &
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.bind(("0.0.0.0", int(sys.argv[1])))
|
||||
while True:
|
||||
time.sleep(60)
|
||||
PY
|
||||
blocker_pid=$!
|
||||
for _ in $(seq 1 40); do
|
||||
ss -H -lunp "sport = :${peer_port}" 2>/dev/null | grep -q "pid=${blocker_pid}" && return 0
|
||||
sleep 0.05
|
||||
done
|
||||
kill -KILL "$blocker_pid" 2>/dev/null || true
|
||||
echo "cannot bind UDP/${peer_port} for the force-release check" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
set +e
|
||||
env "${deploy_env[@]}" bash /tmp/deploy.sh uninstall >/dev/null 2>&1
|
||||
docker rm -f csqtt csqtt-vpn >/dev/null 2>&1
|
||||
ip link del csqtt1 >/dev/null 2>&1
|
||||
[ -n "$panel_cookie" ] && rm -f -- "$panel_cookie"
|
||||
set -e
|
||||
}
|
||||
|
||||
clear_test_state() {
|
||||
cleanup
|
||||
[ "${CSQTT_TEST_WIPE_STATE:-0}" = "1" ] && rm -rf -- /etc/csqtt
|
||||
}
|
||||
|
||||
trap clear_test_state EXIT
|
||||
clear_test_state
|
||||
prepare_tls
|
||||
|
||||
deploy systemd
|
||||
panel_login
|
||||
assert_dns "77.88.8.8,77.88.8.1"
|
||||
|
||||
set_dns '{"dns_provider":"xbox"}'
|
||||
assert_dns "111.88.96.50,111.88.96.51"
|
||||
deploy systemd
|
||||
panel_login
|
||||
assert_dns "111.88.96.50,111.88.96.51"
|
||||
|
||||
set_dns '{"dns_primary":"203.0.113.7","dns_secondary":"198.51.100.9"}'
|
||||
assert_dns "203.0.113.7,198.51.100.9"
|
||||
deploy systemd
|
||||
panel_login
|
||||
assert_dns "77.88.8.8,77.88.8.1"
|
||||
|
||||
set_dns '{"dns_primary":"111.88.96.51","dns_secondary":"203.0.113.7"}'
|
||||
assert_dns "111.88.96.51,203.0.113.7"
|
||||
deploy systemd
|
||||
panel_login
|
||||
assert_dns "111.88.96.50,111.88.96.51"
|
||||
echo "PASS DNS deploy migration"
|
||||
|
||||
systemctl stop csqtt
|
||||
for _ in $(seq 1 40); do
|
||||
ss -H -lun "sport = :${peer_port}" | grep -q . || break
|
||||
sleep 0.1
|
||||
done
|
||||
start_udp_blocker
|
||||
deploy systemd
|
||||
if kill -0 "$blocker_pid" 2>/dev/null; then
|
||||
echo "configured UDP port blocker survived deploy" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "PASS force release UDP/${peer_port}"
|
||||
|
||||
if [ "${CSQTT_TEST_SKIP_DOCKER:-0}" = "1" ]; then
|
||||
echo "PASS systemd-only deploy matrix"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
command -v docker >/dev/null 2>&1 || { echo "docker is unavailable" >&2; exit 3; }
|
||||
docker info >/dev/null
|
||||
deploy docker
|
||||
panel_login
|
||||
assert_dns "111.88.96.50,111.88.96.51"
|
||||
deploy docker
|
||||
docker rename csqtt csqtt-vpn
|
||||
deploy systemd
|
||||
docker inspect csqtt-vpn >/dev/null 2>&1 && { echo "legacy Docker CSQTT container survived mode switch" >&2; exit 1; }
|
||||
echo "PASS docker-to-systemd cleanup"
|
||||
|
||||
deploy docker
|
||||
systemctl is-active --quiet csqtt && { echo "legacy systemd CSQTT runtime survived mode switch" >&2; exit 1; }
|
||||
echo "PASS systemd-to-docker cleanup"
|
||||
@@ -0,0 +1,22 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string[]]$Distributions = @("Ubuntu-22.04", "Ubuntu-24.04", "Ubuntu-26.04", "Debian"),
|
||||
[int]$PeerPort = 46900,
|
||||
[int]$WebPort = 46902,
|
||||
[switch]$SkipDocker
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$workspace = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path.Replace("\", "/")
|
||||
$linuxWorkspace = "/mnt/" + $workspace.Substring(0, 1).ToLowerInvariant() + $workspace.Substring(2)
|
||||
$scriptPath = "$linuxWorkspace/scripts/test_deploy_wsl.sh"
|
||||
|
||||
foreach ($distribution in $Distributions) {
|
||||
Write-Host "=== $distribution ==="
|
||||
$skipDockerEnvironment = if ($SkipDocker) { " CSQTT_TEST_SKIP_DOCKER=1" } else { "" }
|
||||
$command = "CSQTT_WORKSPACE='$linuxWorkspace' CSQTT_TEST_WIPE_STATE=1 CSQTT_TEST_PEER_PORT='$PeerPort' CSQTT_TEST_WEB_PORT='$WebPort'$skipDockerEnvironment bash '$scriptPath'"
|
||||
& wsl.exe -d $distribution -u root -- bash -lc $command
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "WSL deploy matrix failed in $distribution with exit code $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string[]]$Distributions = @("Ubuntu-22.04", "Ubuntu-24.04", "Ubuntu-26.04", "Debian"),
|
||||
[int]$PeerPort = 46910,
|
||||
[int]$WebPort = 46912,
|
||||
[string]$ServerBinary = "",
|
||||
[ValidateSet("systemd", "docker")]
|
||||
[string]$DeployMode = "systemd",
|
||||
[switch]$Redeploy
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$workspace = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path.Replace("\", "/")
|
||||
$linuxWorkspace = "/mnt/" + $workspace.Substring(0, 1).ToLowerInvariant() + $workspace.Substring(2)
|
||||
$serverScript = "$linuxWorkspace/scripts/test_e2e_wsl_server.sh"
|
||||
$serverBinaryEnv = if ([string]::IsNullOrWhiteSpace($ServerBinary)) { "" } else { "CSQTT_TEST_SERVER_BINARY='$ServerBinary' " }
|
||||
$clientManifest = Join-Path $workspace.Replace("/", "\") "rust-client\Cargo.toml"
|
||||
$tests = @(
|
||||
"turn::integration_tests::windows_client_reaches_wsl_server_through_a_real_turn_channel_and_dispatcher",
|
||||
"turn::integration_tests::nine_windows_workers_register_with_a_wsl_server_without_missing_or_duplicate_streams"
|
||||
)
|
||||
|
||||
foreach ($distribution in $Distributions) {
|
||||
Write-Host "=== $distribution ==="
|
||||
$serverCommand = "CSQTT_WORKSPACE='$linuxWorkspace' ${serverBinaryEnv}CSQTT_TEST_PEER_PORT='$PeerPort' CSQTT_TEST_WEB_PORT='$WebPort' CSQTT_TEST_DEPLOY_MODE='$DeployMode' bash '$serverScript' start"
|
||||
try {
|
||||
& wsl.exe -d $distribution -u root -- bash -lc $serverCommand
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "WSL E2E server startup failed in $distribution with exit code $LASTEXITCODE"
|
||||
}
|
||||
if ($Redeploy) {
|
||||
$redeployCommand = "CSQTT_WORKSPACE='$linuxWorkspace' ${serverBinaryEnv}CSQTT_TEST_PEER_PORT='$PeerPort' CSQTT_TEST_WEB_PORT='$WebPort' CSQTT_TEST_DEPLOY_MODE='$DeployMode' bash '$serverScript' redeploy"
|
||||
& wsl.exe -d $distribution -u root -- bash -lc $redeployCommand
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "WSL E2E redeploy failed in $distribution with exit code $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
$serverIpOutput = & wsl.exe -d $distribution -u root -- bash -lc 'hostname -I'
|
||||
$serverIp = [regex]::Match(([string]::Join(' ', [string[]]$serverIpOutput)), '\b(?:\d{1,3}\.){3}\d{1,3}\b').Value
|
||||
if ([string]::IsNullOrWhiteSpace($serverIp) -or $serverIp -notmatch '^\d{1,3}(\.\d{1,3}){3}$') {
|
||||
throw "WSL E2E server address was not resolved for $distribution"
|
||||
}
|
||||
$previousPeer = $env:CSQTT_E2E_PEER
|
||||
$env:CSQTT_E2E_PEER = "${serverIp}:$PeerPort"
|
||||
try {
|
||||
foreach ($test in $tests) {
|
||||
$testOutput = & cmd.exe /d /c "cargo test --manifest-path `"$clientManifest`" $test -- --ignored --exact 2>&1"
|
||||
$testExitCode = $LASTEXITCODE
|
||||
$testOutput | Write-Host
|
||||
$testText = [string]::Join("`n", $testOutput)
|
||||
if ($testExitCode -ne 0 -or -not $testText.Contains("test result: ok. 1 passed")) {
|
||||
throw "E2E client test $test failed for $distribution with exit code $testExitCode"
|
||||
}
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$env:CSQTT_E2E_PEER = $previousPeer
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$stopCommand = "CSQTT_WORKSPACE='$linuxWorkspace' CSQTT_TEST_PEER_PORT='$PeerPort' CSQTT_TEST_WEB_PORT='$WebPort' CSQTT_TEST_DEPLOY_MODE='$DeployMode' bash '$serverScript' stop"
|
||||
& wsl.exe -d $distribution -u root -- bash -lc $stopCommand
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
#!/bin/bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
workspace="${CSQTT_WORKSPACE:-/path/to/your/csqtt}"
|
||||
peer_port="${CSQTT_TEST_PEER_PORT:-46910}"
|
||||
web_port="${CSQTT_TEST_WEB_PORT:-46912}"
|
||||
ssh_port="${CSQTT_TEST_SSH_PORT:-2224}"
|
||||
script_source="${workspace}/app/src/main/assets/deploy.sh"
|
||||
binary_source="${CSQTT_TEST_SERVER_BINARY:-${workspace}/app/src/main/assets/csqtt-linux-amd64}"
|
||||
action="${1:-start}"
|
||||
deploy_mode="${CSQTT_TEST_DEPLOY_MODE:-systemd}"
|
||||
|
||||
[ "$(id -u)" -eq 0 ] || { echo "run as root" >&2; exit 2; }
|
||||
|
||||
deploy_env=(
|
||||
"CSQTT_PEER_PORT=${peer_port}"
|
||||
"CSQTT_WEB_PORT=${web_port}"
|
||||
"CSQTT_SSH_PORT=${ssh_port}"
|
||||
"CSQTT_START_STABILITY_SECONDS=1"
|
||||
"CSQTT_DEPLOY_MODE=${deploy_mode}"
|
||||
)
|
||||
|
||||
prepare_tls() {
|
||||
mkdir -p /etc/csqtt
|
||||
if ! openssl x509 -noout -in /etc/csqtt/web_cert.pem >/dev/null 2>&1 || \
|
||||
! openssl pkey -noout -in /etc/csqtt/web_key.pem >/dev/null 2>&1; then
|
||||
rm -f /etc/csqtt/web_cert.pem /etc/csqtt/web_key.pem
|
||||
openssl req -x509 -newkey rsa:2048 -nodes -days 2 \
|
||||
-subj '/CN=csqtt-wsl-e2e-test' \
|
||||
-keyout /etc/csqtt/web_key.pem \
|
||||
-out /etc/csqtt/web_cert.pem >/dev/null 2>&1
|
||||
chmod 600 /etc/csqtt/web_key.pem
|
||||
chmod 644 /etc/csqtt/web_cert.pem
|
||||
fi
|
||||
}
|
||||
|
||||
prepare_upload() {
|
||||
install -m 0755 "$script_source" /tmp/deploy.sh
|
||||
install -m 0755 "$binary_source" /tmp/.csqtt-upload-server
|
||||
install -m 0600 /dev/null /tmp/.csqtt-upload-web.env
|
||||
install -m 0600 /dev/null /tmp/.csqtt-upload-overrides.json
|
||||
printf '%s\n' 'CSQTT_WEB_USER=e2e-test' 'CSQTT_WEB_PASS=e2e-test-password' > /tmp/.csqtt-upload-web.env
|
||||
printf '%s\n' '{"main_password":"e2e-local-password-20260830","device_id":"e2e-windows-client"}' > /tmp/.csqtt-upload-overrides.json
|
||||
chmod 0600 /tmp/.csqtt-upload-web.env /tmp/.csqtt-upload-overrides.json
|
||||
}
|
||||
|
||||
verify_runtime() {
|
||||
case "$deploy_mode" in
|
||||
systemd)
|
||||
systemctl is-active --quiet csqtt
|
||||
;;
|
||||
docker)
|
||||
docker inspect --format '{{.State.Running}}' csqtt | grep -qx true
|
||||
;;
|
||||
*)
|
||||
echo "unsupported deploy mode: $deploy_mode" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
ss -H -lun "sport = :${peer_port}" | grep -q .
|
||||
ip link show csqtt1 >/dev/null 2>&1
|
||||
}
|
||||
|
||||
case "$action" in
|
||||
start)
|
||||
[ -x "$binary_source" ] || { echo "missing executable server asset" >&2; exit 2; }
|
||||
[ -f "$script_source" ] || { echo "missing deploy asset" >&2; exit 2; }
|
||||
prepare_tls
|
||||
prepare_upload
|
||||
env "${deploy_env[@]}" bash /tmp/deploy.sh uninstall >/dev/null 2>&1 || true
|
||||
prepare_tls
|
||||
prepare_upload
|
||||
env "${deploy_env[@]}" bash /tmp/deploy.sh install
|
||||
verify_runtime
|
||||
echo "READY ${peer_port}"
|
||||
;;
|
||||
redeploy)
|
||||
[ -x "$binary_source" ] || { echo "missing executable server asset" >&2; exit 2; }
|
||||
[ -f "$script_source" ] || { echo "missing deploy asset" >&2; exit 2; }
|
||||
prepare_tls
|
||||
prepare_upload
|
||||
env "${deploy_env[@]}" bash /tmp/deploy.sh install
|
||||
verify_runtime
|
||||
echo "REDEPLOYED ${peer_port}"
|
||||
;;
|
||||
stop)
|
||||
[ -f /tmp/deploy.sh ] || install -m 0755 "$script_source" /tmp/deploy.sh
|
||||
env "${deploy_env[@]}" bash /tmp/deploy.sh uninstall >/dev/null 2>&1 || true
|
||||
docker rm -f csqtt csqtt-vpn >/dev/null 2>&1 || true
|
||||
ip link del csqtt1 >/dev/null 2>&1 || true
|
||||
echo "STOPPED ${peer_port}"
|
||||
;;
|
||||
*)
|
||||
echo "usage: $0 start|redeploy|stop" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,47 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$ServerDistribution = "Ubuntu-26.04",
|
||||
[string]$ClientDistribution = "Ubuntu-24.04",
|
||||
[string]$WslUser = "your_user",
|
||||
[int]$PeerPort = 46930,
|
||||
[int]$WebPort = 46932
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$workspace = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path.Replace("\", "/")
|
||||
$linuxWorkspace = "/mnt/" + $workspace.Substring(0, 1).ToLowerInvariant() + $workspace.Substring(2)
|
||||
$serverBinary = "$linuxWorkspace/rust-server/target/x86_64-unknown-linux-gnu/release/csqtt"
|
||||
$serverScript = "$linuxWorkspace/scripts/test_e2e_wsl_server.sh"
|
||||
|
||||
function Invoke-WslRoot([string]$Distribution, [string]$Command) {
|
||||
$encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($Command))
|
||||
& wsl.exe -d $Distribution -u root -- bash -lc "echo $encoded | base64 -d | bash"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "WSL root command failed in $Distribution with exit code $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-WslUser([string]$Distribution, [string]$Command) {
|
||||
$encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($Command))
|
||||
& wsl.exe -d $Distribution -u $WslUser -- bash -lc "echo $encoded | base64 -d | bash"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "WSL user command failed in $Distribution with exit code $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Invoke-WslUser $ClientDistribution "cd '$linuxWorkspace/rust-client' && cargo test --target x86_64-unknown-linux-gnu --no-run"
|
||||
Invoke-WslUser $ClientDistribution "cd '$linuxWorkspace/rust-server' && cargo build --release --target x86_64-unknown-linux-gnu"
|
||||
Invoke-WslRoot $ServerDistribution "CSQTT_WORKSPACE='$linuxWorkspace' CSQTT_TEST_SERVER_BINARY='$serverBinary' CSQTT_TEST_PEER_PORT='$PeerPort' CSQTT_TEST_WEB_PORT='$WebPort' CSQTT_TEST_DEPLOY_MODE='systemd' bash '$serverScript' start"
|
||||
$serverIp = (((& wsl.exe -d $ServerDistribution -- hostname -I) -join " ").Trim() -split '\s+')[0]
|
||||
if ([string]::IsNullOrWhiteSpace($serverIp) -or $serverIp -notmatch '^\d{1,3}(\.\d{1,3}){3}$') {
|
||||
throw "Could not resolve the server WSL IPv4 address"
|
||||
}
|
||||
$test = "cd '$linuxWorkspace/rust-client' && test_binary=`$(find '$linuxWorkspace/rust-client/target/x86_64-unknown-linux-gnu/debug/deps' -maxdepth 1 -type f -name 'client-*' ! -name '*.d' -perm -111 -printf '%T@ %p\n' | sort -nr | head -n 1 | cut -d' ' -f2-); test -n `"`$test_binary`"; CSQTT_E2E_PEER='$($serverIp):$PeerPort' CSQTT_E2E_WEB='https://$($serverIp):$WebPort' `"`$test_binary`" turn::integration_tests::running_client_receives_hot_dns_configuration_without_reconnect --ignored --exact --nocapture"
|
||||
Invoke-WslUser $ClientDistribution $test
|
||||
Invoke-WslRoot $ServerDistribution "grep -q 'DNS configuration applied' <(journalctl -u csqtt --since '5 minutes ago' --no-pager)"
|
||||
'CSQTT_E2E_HOT_DNS=PASS'
|
||||
}
|
||||
finally {
|
||||
& wsl.exe -d $ServerDistribution -u root -- bash -lc "CSQTT_WORKSPACE='$linuxWorkspace' CSQTT_TEST_PEER_PORT='$PeerPort' CSQTT_TEST_WEB_PORT='$WebPort' CSQTT_TEST_DEPLOY_MODE='systemd' bash '$serverScript' stop"
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$ServerDistribution = "Ubuntu-26.04",
|
||||
[string]$ClientDistribution = "Ubuntu-24.04",
|
||||
[string]$WslUser = "your_user",
|
||||
[int]$PeerPort = 46910,
|
||||
[int]$WebPort = 46912,
|
||||
[int]$EchoPort = 47214,
|
||||
[int]$DurationSeconds = 12,
|
||||
[int]$TargetMbit = 160,
|
||||
[int]$MinimumMbit = 144,
|
||||
[int]$MinimumStreamKbit = 2000
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$workspace = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path.Replace("\", "/")
|
||||
$linuxWorkspace = "/mnt/" + $workspace.Substring(0, 1).ToLowerInvariant() + $workspace.Substring(2)
|
||||
$serverManifest = "$linuxWorkspace/rust-server/Cargo.toml"
|
||||
$clientManifest = "$linuxWorkspace/rust-client/Cargo.toml"
|
||||
$serverBinary = "$linuxWorkspace/rust-server/target/x86_64-unknown-linux-gnu/release/csqtt"
|
||||
$serverScript = "$linuxWorkspace/scripts/test_e2e_wsl_server.sh"
|
||||
$echoScript = "$linuxWorkspace/scripts/csqtt_e2e_echo.py"
|
||||
$echoPidFile = "/run/csqtt-e2e-echo.pid"
|
||||
$echoStats = "/run/csqtt-e2e-echo.json"
|
||||
|
||||
function Invoke-WslRoot([string]$Distribution, [string]$Command) {
|
||||
$encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($Command))
|
||||
& wsl.exe -d $Distribution -u root -- bash -lc "echo $encoded | base64 -d | bash"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "WSL command failed in $Distribution with exit code $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-WslUser([string]$Distribution, [string]$Command) {
|
||||
$encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($Command))
|
||||
& wsl.exe -d $Distribution -u $WslUser -- bash -lc "echo $encoded | base64 -d | bash"
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "WSL user command failed in $Distribution with exit code $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
|
||||
function Stop-Echo([string]$Distribution) {
|
||||
Invoke-WslRoot $Distribution "for pid in `$(pgrep -f '[c]sqtt_e2e_echo.py' || true); do kill -TERM `$pid 2>/dev/null || true; done; if test -s '$echoPidFile'; then kill `$(cat '$echoPidFile') 2>/dev/null || true; fi; rm -f '$echoPidFile'"
|
||||
}
|
||||
|
||||
$serverCpuStart = $null
|
||||
$serverCpuStartedAt = $null
|
||||
|
||||
function Read-ServerCpuSample([string]$Distribution) {
|
||||
$output = Invoke-WslRoot $Distribution "pid=`$(systemctl show --property=MainPID --value csqtt); test `"`$pid`" -gt 0; ticks=`$(awk '{print `$14 + `$15}' /proc/`$pid/stat); hz=`$(getconf CLK_TCK); printf '%s %s %s\n' `"`$pid`" `"`$ticks`" `"`$hz`""
|
||||
$line = @($output | Where-Object { $_ -match '^\d+ \d+ \d+$' })[-1]
|
||||
$parts = $line -split ' '
|
||||
[PSCustomObject]@{
|
||||
ProcessId = [int]$parts[0]
|
||||
Ticks = [double]$parts[1]
|
||||
Hertz = [double]$parts[2]
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Invoke-WslUser $ClientDistribution "cd '$linuxWorkspace/rust-client' && cargo test --release --target x86_64-unknown-linux-gnu --no-run"
|
||||
Invoke-WslUser $ClientDistribution "cd '$linuxWorkspace/rust-server' && cargo build --release --target x86_64-unknown-linux-gnu"
|
||||
$start = "CSQTT_WORKSPACE='$linuxWorkspace' CSQTT_TEST_SERVER_BINARY='$serverBinary' CSQTT_TEST_PEER_PORT='$PeerPort' CSQTT_TEST_WEB_PORT='$WebPort' CSQTT_TEST_DEPLOY_MODE='systemd' bash '$serverScript' start"
|
||||
Invoke-WslRoot $ServerDistribution $start
|
||||
$serverIp = (((& wsl.exe -d $ServerDistribution -- hostname -I) -join " ").Trim() -split '\s+')[0]
|
||||
if ([string]::IsNullOrWhiteSpace($serverIp) -or $serverIp -notmatch '^\d{1,3}(\.\d{1,3}){3}$') {
|
||||
throw "Could not resolve the server WSL IPv4 address"
|
||||
}
|
||||
Stop-Echo $ServerDistribution
|
||||
Invoke-WslRoot $ServerDistribution "rm -f '$echoStats' '$echoPidFile'; nohup python3 '$echoScript' --host 10.66.67.1 --port '$EchoPort' --stats '$echoStats' >/run/csqtt-e2e-echo.log 2>&1 & echo `$! >'$echoPidFile'; sleep 1; kill -0 `$(cat '$echoPidFile')"
|
||||
$serverCpuStart = Read-ServerCpuSample $ServerDistribution
|
||||
$serverCpuStartedAt = Get-Date
|
||||
$test = "cd '$linuxWorkspace/rust-client' && test_binary=`$(find '$linuxWorkspace/rust-client/target/x86_64-unknown-linux-gnu/release/deps' -maxdepth 1 -type f -name 'client-*' ! -name '*.d' -perm -111 -printf '%T@ %p\n' | sort -nr | head -n 1 | cut -d' ' -f2-); test -n `"`$test_binary`"; CSQTT_E2E_PEER='$serverIp`:$PeerPort' CSQTT_E2E_ECHO_PORT='$EchoPort' CSQTT_E2E_DURATION_SECONDS='$DurationSeconds' CSQTT_E2E_TARGET_MBIT='$TargetMbit' CSQTT_E2E_MIN_MBIT='$MinimumMbit' CSQTT_E2E_MIN_STREAM_KBIT='$MinimumStreamKbit' `"`$test_binary`" turn::integration_tests::seventy_two_linux_workers_hold_per_stream_rate_through_server_dataplane --ignored --exact --nocapture"
|
||||
Invoke-WslUser $ClientDistribution $test
|
||||
}
|
||||
finally {
|
||||
if ($null -ne $serverCpuStart -and $null -ne $serverCpuStartedAt) {
|
||||
$serverCpuEnd = Read-ServerCpuSample $ServerDistribution
|
||||
if ($serverCpuEnd.ProcessId -eq $serverCpuStart.ProcessId) {
|
||||
$wallSeconds = ((Get-Date) - $serverCpuStartedAt).TotalSeconds
|
||||
if ($wallSeconds -gt 0) {
|
||||
$cpuPercent = (($serverCpuEnd.Ticks - $serverCpuStart.Ticks) / $serverCpuStart.Hertz) * 100.0 / $wallSeconds
|
||||
"CSQTT_E2E_SERVER_CPU_PERCENT=$([Math]::Round($cpuPercent, 2))"
|
||||
}
|
||||
}
|
||||
}
|
||||
Stop-Echo $ServerDistribution
|
||||
& wsl.exe -d $ServerDistribution -u root -- bash -lc "CSQTT_WORKSPACE='$linuxWorkspace' CSQTT_TEST_PEER_PORT='$PeerPort' CSQTT_TEST_WEB_PORT='$WebPort' CSQTT_TEST_DEPLOY_MODE='systemd' bash '$serverScript' stop"
|
||||
& wsl.exe -d $ServerDistribution -u root -- bash -lc "test -f '$echoStats' && cat '$echoStats' || true"
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
# SPDX-FileCopyrightText: 2026 amurcanov
|
||||
# SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$ApkPath,
|
||||
|
||||
[string]$SourcePath = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ([string]::IsNullOrWhiteSpace($SourcePath)) {
|
||||
$SourcePath = Join-Path $PSScriptRoot "..\app\src\main\assets\deploy.sh"
|
||||
}
|
||||
|
||||
function Get-Sha256([byte[]]$Bytes) {
|
||||
$hasher = [System.Security.Cryptography.SHA256]::Create()
|
||||
try {
|
||||
return ([System.BitConverter]::ToString($hasher.ComputeHash($Bytes))).Replace("-", "").ToLowerInvariant()
|
||||
} finally {
|
||||
$hasher.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
$resolvedApk = (Resolve-Path -LiteralPath $ApkPath).Path
|
||||
$resolvedSource = (Resolve-Path -LiteralPath $SourcePath).Path
|
||||
$sourceBytes = [System.IO.File]::ReadAllBytes($resolvedSource)
|
||||
$assetDirectory = Split-Path -Parent $resolvedSource
|
||||
$serverAssetNames = @("csqtt-linux-amd64", "csqtt-linux-arm64", "csqtt-linux-armv7")
|
||||
$serverProvenancePath = Join-Path $assetDirectory "csqtt.server-provenance.json"
|
||||
$serverBinaryBytes = @{}
|
||||
foreach ($serverAssetName in $serverAssetNames) {
|
||||
$serverBinaryPath = Join-Path $assetDirectory $serverAssetName
|
||||
$serverBinaryBytes[$serverAssetName] = [System.IO.File]::ReadAllBytes((Resolve-Path -LiteralPath $serverBinaryPath).Path)
|
||||
}
|
||||
$serverProvenanceBytes = [System.IO.File]::ReadAllBytes((Resolve-Path -LiteralPath $serverProvenancePath).Path)
|
||||
|
||||
function Get-ArchiveEntryBytes {
|
||||
param($Archive, [string]$Name)
|
||||
|
||||
$entry = $Archive.GetEntry($Name)
|
||||
if ($null -eq $entry) {
|
||||
throw "APK does not contain ${Name}: $resolvedApk"
|
||||
}
|
||||
$entryStream = $entry.Open()
|
||||
$memory = New-Object System.IO.MemoryStream
|
||||
try {
|
||||
$entryStream.CopyTo($memory)
|
||||
return $memory.ToArray()
|
||||
}
|
||||
finally {
|
||||
$memory.Dispose()
|
||||
$entryStream.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
$archive = [System.IO.Compression.ZipFile]::OpenRead($resolvedApk)
|
||||
try {
|
||||
[byte[]]$apkAssetBytes = Get-ArchiveEntryBytes $archive "assets/deploy.sh"
|
||||
$apkServerBinaryBytes = @{}
|
||||
foreach ($serverAssetName in $serverAssetNames) {
|
||||
$apkServerBinaryBytes[$serverAssetName] = Get-ArchiveEntryBytes $archive "assets/$serverAssetName"
|
||||
}
|
||||
[byte[]]$apkServerProvenanceBytes = Get-ArchiveEntryBytes $archive "assets/csqtt.server-provenance.json"
|
||||
} finally {
|
||||
$archive.Dispose()
|
||||
}
|
||||
|
||||
$sourceHash = Get-Sha256 $sourceBytes
|
||||
$apkHash = Get-Sha256 $apkAssetBytes
|
||||
if ($sourceHash -ne $apkHash) {
|
||||
throw "deploy.sh hash mismatch: source=$sourceHash apk=$apkHash"
|
||||
}
|
||||
foreach ($serverAssetName in $serverAssetNames) {
|
||||
$sourceServerHash = Get-Sha256 $serverBinaryBytes[$serverAssetName]
|
||||
$apkServerHash = Get-Sha256 $apkServerBinaryBytes[$serverAssetName]
|
||||
if ($sourceServerHash -ne $apkServerHash) {
|
||||
throw "server asset hash mismatch for $serverAssetName`: source=$sourceServerHash apk=$apkServerHash"
|
||||
}
|
||||
}
|
||||
$sourceServerProvenanceHash = Get-Sha256 $serverProvenanceBytes
|
||||
$apkServerProvenanceHash = Get-Sha256 $apkServerProvenanceBytes
|
||||
if ($sourceServerProvenanceHash -ne $apkServerProvenanceHash) {
|
||||
throw "server provenance hash mismatch: source=$sourceServerProvenanceHash apk=$apkServerProvenanceHash"
|
||||
}
|
||||
|
||||
$assetText = [System.Text.Encoding]::UTF8.GetString($apkAssetBytes)
|
||||
if (-not $assetText.Contains("prepare_uploaded_release")) {
|
||||
throw "APK lacks the direct upload validation"
|
||||
}
|
||||
if (-not $assetText.Contains('readonly CSQTT_WIRE_PROTOCOL_REVISION="CSQTT-WIRE-3"') -or
|
||||
-not $assetText.Contains('"$UPLOAD_BINARY" --protocol-revision')) {
|
||||
throw "APK lacks the uploaded server wire protocol validation"
|
||||
}
|
||||
$cutoverIndex = $assetText.IndexOf('DEPLOY_PHASE="cutover"')
|
||||
$cleanupIndex = if ($cutoverIndex -ge 0) { $assetText.IndexOf('csqtt_cleanup', $cutoverIndex) } else { -1 }
|
||||
$binaryIndex = if ($cleanupIndex -ge 0) { $assetText.IndexOf('setup_csqtt_binary', $cleanupIndex) } else { -1 }
|
||||
if ($cutoverIndex -lt 0 -or $cleanupIndex -lt 0 -or $binaryIndex -lt $cleanupIndex) {
|
||||
throw "APK lacks the atomic runtime cleanup step"
|
||||
}
|
||||
if ($assetText.Contains("CSQTT_DEPLOY_READY_FOR_UPLOAD")) {
|
||||
throw "APK still contains the removed two-phase prepare protocol"
|
||||
}
|
||||
if (-not $assetText.Contains('install -m 0755 "$UPLOAD_BINARY" /usr/local/bin/csqtt')) {
|
||||
throw "APK lacks the direct runtime binary installation"
|
||||
}
|
||||
if ($assetText.Contains("verify_staged_release") -or $assetText.Contains("csqtt-stage")) {
|
||||
throw "APK still contains staged candidate deployment logic"
|
||||
}
|
||||
if (-not $assetText.Contains("CSQTT_DEPLOY_ERROR|")) {
|
||||
throw "APK lacks the deploy error protocol marker"
|
||||
}
|
||||
if (-not $assetText.Contains('docker build --network host') -or
|
||||
-not $assetText.Contains('DOCKER_BUILD_TIMEOUT_SECONDS') -or
|
||||
-not $assetText.Contains('CSQTT_BUILD_DNS_PRIMARY:-') -or
|
||||
-not $assetText.Contains('CSQTT_BUILD_DNS_PRIMARY=77.88.8.8') -or
|
||||
-not $assetText.Contains('CSQTT_BUILD_DNS_SECONDARY=77.88.8.1')) {
|
||||
throw "APK lacks the Docker DNS fallback"
|
||||
}
|
||||
|
||||
Write-Host "[OK] deploy.sh verified in $(Split-Path -Leaf $resolvedApk): SHA-256 $apkHash"
|
||||
Reference in new issue
Block a user