From 8ac9f8407881fb9caff948b8af413e8aca4d5332 Mon Sep 17 00:00:00 2001 From: kzolotarev95 Date: Tue, 13 Oct 2026 17:15:32 +0400 Subject: [PATCH] Fix direct WAN startup with missing routing tables --- files/usr/lib/owrt-remote/wan.sh | 45 ++++++-- files/usr/sbin/owrt-remote | 6 +- tests/WAN_STABILITY.md | 59 ++++++++++ tests/test_host_policy.py | 61 +++++++++++ tests/test_wan_stability_deploy.py | 86 +++++++++++++++ vps/deploy-wan-stability-fix.ps1 | 170 +++++++++++++++++++++++++++++ 6 files changed, 416 insertions(+), 11 deletions(-) create mode 100644 tests/WAN_STABILITY.md create mode 100644 tests/test_wan_stability_deploy.py create mode 100644 vps/deploy-wan-stability-fix.ps1 diff --git a/files/usr/lib/owrt-remote/wan.sh b/files/usr/lib/owrt-remote/wan.sh index 43e4154..b997155 100644 --- a/files/usr/lib/owrt-remote/wan.sh +++ b/files/usr/lib/owrt-remote/wan.sh @@ -247,8 +247,42 @@ wan_remove_legacy_firewall() { fi } +wan_table_names() { + local file + printf '%s\n' "$WAN_TABLE" + for file in /etc/iproute2/rt_tables /usr/lib/iproute2/rt_tables /etc/iproute2/rt_tables.d/*.conf /usr/lib/iproute2/rt_tables.d/*.conf; do + [ ! -r "$file" ] || awk -v table="$WAN_TABLE" '$1 == table && NF >= 2 { print $2 }' "$file" + done +} + +wan_table_routes() { + local family routes error names + family="$1"; error="$WAN_STATE/table-error.$$" + if routes="$(ip -"$family" route show table "$WAN_TABLE" 2>"$error")"; then + printf '%s\n' "$routes" + elif [ -z "$routes" ] && grep -qi 'FIB table does not exist' "$error"; then + # iproute2 explicitly identifies an absent, not-yet-created table. + : + elif [ -z "$routes" ] && grep -Eqi '^[[:space:]]*([[:alnum:]_-]+: )?Dump terminated[[:space:]]*$' "$error"; then + # Some OpenWrt ip builds report only "Dump terminated" for this case. + # Confirm it with a successful dump of all tables; never assume that a + # failed/partial dump means an empty table, or overwrite foreign routes. + if ! routes="$(ip -"$family" route show table all 2>"$error")"; then + cat "$error" >&2; rm -f "$error"; return 1 + fi + names="$(wan_table_names)" + printf '%s\n' "$routes" | awk -v names="$names" ' + BEGIN { n=split(names, a, "\n"); for(i=1;i<=n;i++) tables[a[i]]=1 } + { for(i=1;i&2; rm -f "$error"; return 1 + fi + rm -f "$error" +} + wan_check_table() { - local family rules routes own error + local family rules routes own family="$1" rules="$(ip -"$family" rule show)" || return 1 own="$(wan_owned_rule_pattern)" @@ -256,14 +290,7 @@ wan_check_table() { if printf '%s\n' "$rules" | grep -E "^$WAN_PRIORITY:|lookup $WAN_TABLE([[:space:]]|$)" | grep -Ev "$own" | grep -q .; then log "WAN IPv$family table $WAN_TABLE or priority $WAN_PRIORITY is already used by another rule"; return 1 fi - error="$WAN_STATE/table-error.$$" - if ! routes="$(ip -"$family" route show table "$WAN_TABLE" 2>"$error")"; then - # iproute2 returns an error for an empty, not-yet-created table. - if ! grep -qi 'FIB table does not exist' "$error"; then - cat "$error" >&2; rm -f "$error"; return 1 - fi - fi - rm -f "$error" + routes="$(wan_table_routes "$family")" || return 1 if [ -n "$routes" ] && [ ! -f "$WAN_STATE/route-owner-$family" ] && ! printf '%s\n' "$rules" | grep -Eq "$own"; then log "WAN IPv$family table $WAN_TABLE is not empty and does not belong to Remote"; return 1 fi diff --git a/files/usr/sbin/owrt-remote b/files/usr/sbin/owrt-remote index 2caa2f7..a5e3eb3 100644 --- a/files/usr/sbin/owrt-remote +++ b/files/usr/sbin/owrt-remote @@ -654,7 +654,8 @@ run_xray() { ensure_xray_available xray_bin="$(xray_bin_path)" - xray_config="$(render_client_config)" + xray_config="$(render_client_config)" || die "не удалось создать конфигурацию Xray" + [ -n "$xray_config" ] && [ -s "$xray_config" ] || die "конфигурация Xray отсутствует или пуста" [ -x "$xray_bin" ] || die "xray не найден или не исполняемый: $xray_bin" if "$xray_bin" help 2>/dev/null | grep -q 'run'; then @@ -1223,7 +1224,8 @@ run_xray() { ensure_xray_available_with_retry || die "cannot prepare Xray for tunnel" xray_bin="$(xray_bin_path)" - xray_config="$(render_client_config)" + xray_config="$(render_client_config)" || die "cannot create Xray configuration" + [ -n "$xray_config" ] && [ -s "$xray_config" ] || die "Xray configuration is missing or empty" [ -x "$xray_bin" ] || die "xray not found or not executable: $xray_bin" if "$xray_bin" help 2>/dev/null | grep -q 'run'; then diff --git a/tests/WAN_STABILITY.md b/tests/WAN_STABILITY.md new file mode 100644 index 0000000..a598c02 --- /dev/null +++ b/tests/WAN_STABILITY.md @@ -0,0 +1,59 @@ +# Исправление запуска прямого WAN в v114 + +На проблемном роутере обычный `wan` был поднят, имел IPv4-адрес, +маршрут и рабочий DNS. Проверка `ip -4 route show table 210` возвращала +`Dump terminated`, а `wan-preflight` — код 1. Генерация Xray-конфигурации +прерывалась, но агент всё равно запускал Xray с пустым аргументом `-config`. +В журнале появлялось `Failed to get format of`, затем procd останавливал +instance после шести падений. Из-за остановленного туннеля Hub показывал +роутер офлайн и ошибки proxy. + +Теперь после такой ошибки чтения таблицы выполняется дополнительное +чтение всех таблиц. Только успешный полный вывод позволяет проверить, +пуста ли таблица 210. Учитываются её числовой ID и имена из `rt_tables`. +Чужая таблица или неудачный повторный запрос по-прежнему блокируют +подготовку WAN. Ошибка генерации, пустой путь или отсутствующий файл +конфигурации останавливают агент до запуска Xray. + +Изменены только `files/usr/lib/owrt-remote/wan.sh` и +`files/usr/sbin/owrt-remote`. Версия остаётся v114. Настройки Podkop, +LAN и источники установки GitHub/GitLab не меняются. Обновление VPS +для этого исправления не требуется. + +Установка из PowerShell Windows 11: + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-wan-stability-fix.ps1" -Router "root@192.168.1.1" -Action Install +``` + +Скрипт перед заменой проверяет синтаксис и подготовку WAN новым helper, +сохраняет агент, helper, UCI и Xray-конфигурацию в +`/root/owrt-remote-backup-before-wan-stability-v114`. Сохранённая копия +не перезаписывается при повторной установке. После замены выполняются +перезапуск, проверка процесса Xray и настоящий heartbeat до Hub. +При ошибке восстанавливается состояние до текущей попытки. +Успех подтверждается `WAN_STABILITY_ROUTER_Install_OK`. + +Откат из того же PowerShell: + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-wan-stability-fix.ps1" -Router "root@192.168.1.1" -Action Rollback +``` + +Откат возвращает также настройки, сохранённые перед установкой. Если +в момент сохранения старый WAN-режим уже был включён и сломан, откат +вернёт и этот режим; его можно выключить в панели роутера. +Резервная копия хранится на конкретном роутере: установка на одном +IP не создаёт копию на другом. При отсутствии или неполноте копии +скрипт сообщает причину и завершает откат до остановки сервиса. + +Локальные тесты с подменёнными OpenWrt UCI/ip/netifd проверяют ошибку +пустой таблицы, именованную чужую таблицу, отказ в чтении, запрет +пустой конфигурации и успешный запуск с корректной конфигурацией. +Также запускаются существующие проверки резервирования WAN, формы +выбора интерфейсов и применения Xray-команд. Все 64 проверки прошли; +PowerShell и подготовленные shell-скрипты установки/отката прошли +проверку синтаксиса, payload подготовлен в UTF-8 без BOM с LF. +Три дополнительные проверки отката подтверждают восстановление +полной копии и отсутствие изменений при отсутствующей/неполной копии. +Реальное устройство проверяет пользователь. diff --git a/tests/test_host_policy.py b/tests/test_host_policy.py index c984e92..386d3a6 100644 --- a/tests/test_host_policy.py +++ b/tests/test_host_policy.py @@ -115,8 +115,16 @@ ip() { priority) echo '104: from all fwmark 0x10000 lookup 105' ;; esac ;; '-4 route show table 210') + case "${TABLE_QUERY_ERROR:-}" in + busybox) echo 'Dump terminated' >&2; return 2 ;; + denied) echo 'RTNETLINK answers: Operation not permitted' >&2; return 2 ;; + esac if [ "${TABLE_MISSING:-0}" = 1 ]; then echo 'Error: ipv4: FIB table does not exist.' >&2; return 2; fi [ "${TABLE_CONFLICT:-}" != route ] || echo 'default via 192.0.2.1 dev other-wan' ;; + '-4 route show table all') + [ "${ALL_TABLES_FAIL:-0}" = 0 ] || { echo 'Dump terminated' >&2; return 2; } + echo 'default via 10.0.0.1 dev pppoe-wan table main' + [ "${ALL_TABLES_FOREIGN:-0}" = 0 ] || echo "default via 192.0.2.1 dev other-wan table ${ALL_TABLES_NAME:-210}" ;; esac return 0 } @@ -426,6 +434,59 @@ printf '%s' "$(uci_get hub_url '')" self.assertIn("<--post302>", args) self.assertIn("<--post303>", args) + def test_busybox_empty_table_is_confirmed_before_wan_start(self): + self.config(vps_host="193.233.82.38", hub_url="https://hub.example", wan_direct="1", vless_uuid="test-uuid") + result = self.run_shell('render_client_config --stdout', TABLE_QUERY_ERROR="busybox") + self.assertEqual(result.returncode, 0, result.stderr) + config = json.loads(result.stdout) + self.assertEqual(config["outbounds"][2]["settings"]["address"], "193.233.82.38") + routes = self.directory.joinpath("ip").read_text() + self.assertIn("-4 route show table all", routes) + self.assertIn("-4 route replace default", routes) + self.assertEqual(self.directory.joinpath("owrt-remote-wan/active-interface").read_text().strip(), "wan") + + def test_table_dump_error_does_not_hide_foreign_routes_or_read_failures(self): + self.config(vps_host="193.233.82.38") + for settings in ({"TABLE_QUERY_ERROR": "busybox", "ALL_TABLES_FOREIGN": "1"}, + {"TABLE_QUERY_ERROR": "busybox", "ALL_TABLES_FAIL": "1"}, + {"TABLE_QUERY_ERROR": "denied"}): + with self.subTest(settings=settings): + result = self.run_shell('wan_prepare', **settings) + self.assertNotEqual(result.returncode, 0) + self.assertNotIn("route replace", self.directory.joinpath("ip").read_text()) + + def test_table_dump_fallback_recognizes_named_foreign_table(self): + self.config(vps_host="193.233.82.38") + result = self.run_shell(''' +wan_table_names() { printf '210\nremote_named\n'; } +wan_prepare +''', TABLE_QUERY_ERROR="busybox", ALL_TABLES_FOREIGN="1", ALL_TABLES_NAME="remote_named") + self.assertNotEqual(result.returncode, 0) + self.assertIn("does not belong to Remote", result.stderr) + self.assertNotIn("route replace", self.directory.joinpath("ip").read_text()) + + def test_xray_is_not_executed_with_a_failed_or_empty_configuration(self): + executable = self.directory / "fake-xray" + executable.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >>"$TEST_ROOT/xray-called"\n', encoding="utf-8", newline="\n") + executable.chmod(0o755) + self.config(enabled="1", xray_bin=executable.as_posix()) + for render in ('return 7', 'return 0', 'printf "%s" "$TEST_ROOT/missing-config"'): + with self.subTest(render=render): + result = self.run_shell('ensure_xray_available_with_retry() { return 0; }; render_client_config() { ' + render + '; }; run_xray') + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.directory.joinpath("xray-called").exists()) + + def test_xray_runs_with_the_successfully_rendered_configuration(self): + executable = self.directory / "fake-xray" + executable.write_text('#!/bin/sh\n[ "$1" != help ] || { echo run; exit; }; printf "%s\\n" "$*" >"$TEST_ROOT/xray-called"\n', encoding="utf-8", newline="\n") + executable.chmod(0o755) + config = self.directory / "valid-config.json" + config.write_text('{"outbounds": []}') + self.config(enabled="1", xray_bin=executable.as_posix()) + result = self.run_shell('ensure_xray_available_with_retry() { return 0; }; render_client_config() { printf "%s" "$TEST_ROOT/valid-config.json"; }; run_xray') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.directory.joinpath("xray-called").read_text().strip(), 'run -config ' + config.as_posix()) + def test_plain_http_heartbeat_accepts_json_after_redirect_follow(self): self.config(vps_host="193.233.82.38", vps_host_mode="manual") result = self.run_shell(''' diff --git a/tests/test_wan_stability_deploy.py b/tests/test_wan_stability_deploy.py new file mode 100644 index 0000000..8a72904 --- /dev/null +++ b/tests/test_wan_stability_deploy.py @@ -0,0 +1,86 @@ +"""Execute rollback locally with fake router paths; never connect to a router.""" +import os +from pathlib import Path +import shlex +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +GIT_BIN = Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "Git/usr/bin" +SH = shutil.which("sh") +if os.name == "nt" and (GIT_BIN / "sh.exe").exists(): + SH = str(GIT_BIN / "sh.exe") + + +@unittest.skipUnless(SH, "A POSIX shell is required") +class WanStabilityRollbackTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="owrt-wan-rollback-") + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.stage = self.root / "stage" + self.stage.mkdir() + self.backup = self.root / "backup" + self.files = {name: self.root / name for name in ("config", "agent", "wan.sh", "xray")} + for name, path in self.files.items(): + path.write_text("current-" + name, encoding="utf-8") + service = self.root / "service" + service.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >>"$TEST_ROOT/service-calls"\n', encoding="utf-8", newline="\n") + source = (ROOT / "vps/deploy-wan-stability-fix.ps1").read_text(encoding="utf-8") + script = source.split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0] + script = script.replace('stage=/tmp/__UPLOAD_NAME__', 'stage=' + shlex.quote(self.stage.as_posix())) + script = script.replace('backup=/root/owrt-remote-backup-before-wan-stability-v114', 'backup=' + shlex.quote(self.backup.as_posix())) + script = script.replace('config=/etc/config/owrtremote', 'config=' + shlex.quote(self.files["config"].as_posix())) + for name, original in (("agent", "/usr/sbin/owrt-remote"), ("wan.sh", "/usr/lib/owrt-remote/wan.sh")): + script = script.replace('printf ' + original + ' ;;', "printf '%s' " + shlex.quote(self.files[name].as_posix()) + ' ;;') + script = script.replace('/etc/init.d/owrt-remote', 'sh ' + shlex.quote(service.as_posix())) + script = script.replace('__ACTION__', 'Rollback') + script = script.replace('xray_config=$(uci -q get owrtremote.main.xray_config || echo /etc/xray/owrt-remote-client.json)', + 'xray_config=' + shlex.quote(self.files["xray"].as_posix())) + self.script = script + self.env = {**os.environ, "TEST_ROOT": self.root.as_posix()} + if os.name == "nt": + self.env["PATH"] = str(GIT_BIN) + os.pathsep + self.env["PATH"] + + def run_rollback(self): + return subprocess.run([SH], input=self.script, encoding="utf-8", capture_output=True, + env=self.env, timeout=20) + + def assert_unchanged(self): + for name, path in self.files.items(): + self.assertEqual(path.read_text(), "current-" + name) + self.assertFalse(self.root.joinpath("service-calls").exists()) + + def test_missing_backup_explains_failure_without_stopping_service(self): + result = self.run_rollback() + self.assertNotEqual(result.returncode, 0) + self.assertIn("No backup on this router:", result.stderr) + self.assertIn("Nothing changed.", result.stderr) + self.assert_unchanged() + + def test_incomplete_backup_is_rejected_before_restore(self): + self.backup.mkdir() + self.backup.joinpath("complete").touch() + result = self.run_rollback() + self.assertNotEqual(result.returncode, 0) + self.assertIn("Backup is incomplete:", result.stderr) + self.assert_unchanged() + + def test_complete_backup_restores_files_and_settings_then_restarts(self): + self.backup.mkdir() + for name in self.files: + self.backup.joinpath(name).write_text("saved-" + name) + self.backup.joinpath("xray-path").write_text(self.files["xray"].as_posix()) + self.backup.joinpath("complete").touch() + result = self.run_rollback() + self.assertEqual(result.returncode, 0, result.stderr) + for name, path in self.files.items(): + self.assertEqual(path.read_text(), "saved-" + name) + self.assertEqual(self.root.joinpath("service-calls").read_text(), "stop\nrestart\n") + self.assertIn("WAN_STABILITY_ROUTER_Rollback_OK", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/vps/deploy-wan-stability-fix.ps1 b/vps/deploy-wan-stability-fix.ps1 new file mode 100644 index 0000000..ded6533 --- /dev/null +++ b/vps/deploy-wan-stability-fix.ps1 @@ -0,0 +1,170 @@ +param( + [Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Router, + [ValidateSet('Install', 'Rollback')][string]$Action = 'Install', + [switch]$PrepareOnly +) + +$ErrorActionPreference = 'Stop' +$RepoRoot = Split-Path -Parent $PSScriptRoot +$UploadName = 'owrt-wan-stability-' + [guid]::NewGuid().ToString('N') +$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName +$Utf8 = [System.Text.UTF8Encoding]::new($false) +$Payloads = @{ + 'agent' = 'files\usr\sbin\owrt-remote' + 'wan.sh' = 'files\usr\lib\owrt-remote\wan.sh' +} +$RemoteScript = @' +#!/bin/sh +set -eu +stage=/tmp/__UPLOAD_NAME__ +backup=/root/owrt-remote-backup-before-wan-stability-v114 +config=/etc/config/owrtremote +changed=0 +fail() { + printf 'ERROR: %s\n' "$*" >&2 + exit 1 +} +item_path() { + case "$1" in + agent) printf /usr/sbin/owrt-remote ;; + wan.sh) printf /usr/lib/owrt-remote/wan.sh ;; + esac +} +save_files() { + dir=$1 + mkdir -p "$dir" + chmod 700 "$dir" + cp -p "$config" "$dir/config" + for item in agent wan.sh; do + path=$(item_path "$item") + if [ -f "$path" ]; then cp -p "$path" "$dir/$item"; else touch "$dir/$item.absent"; fi + done + xray_config=$(uci -q get owrtremote.main.xray_config || echo /etc/xray/owrt-remote-client.json) + [ -n "$xray_config" ] || xray_config=/etc/xray/owrt-remote-client.json + printf '%s' "$xray_config" >"$dir/xray-path" + if [ -f "$xray_config" ]; then cp -p "$xray_config" "$dir/xray"; else touch "$dir/xray.absent"; fi + chmod 600 "$dir/config" "$dir/xray-path" + [ ! -f "$dir/xray" ] || chmod 600 "$dir/xray" + touch "$dir/complete" +} +validate_backup() { + local dir item + dir=$1 + [ -f "$dir/complete" ] && [ -s "$dir/config" ] && [ -s "$dir/xray-path" ] || return 1 + for item in agent wan.sh xray; do + [ -s "$dir/$item" ] || [ -f "$dir/$item.absent" ] || return 1 + done +} +restore_files() { + dir=$1 + validate_backup "$dir" || { echo "Incomplete backup: $dir" >&2; return 1; } + /etc/init.d/owrt-remote stop >/dev/null 2>&1 || true + cp -p "$dir/config" "$config" + for item in agent wan.sh; do + path=$(item_path "$item") + if [ -f "$dir/$item.absent" ]; then rm -f "$path"; else cp -p "$dir/$item" "$path"; fi + done + xray_config=$(cat "$dir/xray-path") + if [ -f "$dir/xray.absent" ]; then rm -f "$xray_config"; else cp -p "$dir/xray" "$xray_config"; fi + /etc/init.d/owrt-remote restart +} +cleanup() { + code=$? + trap - EXIT + if [ "$code" -ne 0 ] && [ "$changed" = 1 ]; then + echo 'Operation failed; restoring the previous files and settings.' >&2 + restore_files "$stage/previous" || echo 'Restore failed; use the retained backup.' >&2 + fi + for item in agent wan.sh; do + path=$(item_path "$item") + rm -f "$path.new-__UPLOAD_NAME__" + done + rm -rf "$stage" + exit "$code" +} +trap cleanup EXIT +test -s "$config" || fail "Router configuration is missing: $config. Nothing changed." +if [ '__ACTION__' = Install ]; then + for item in agent wan.sh; do test -s "$stage/$item"; sh -n "$stage/$item"; done + grep -F -q 'wan_table_routes()' "$stage/wan.sh" + grep -F -q 'Xray configuration is missing or empty' "$stage/agent" + if [ "$(uci -q get owrtremote.main.wan_direct || echo 0)" = 1 ]; then + # Validate the candidate helper, including empty-table compatibility, + # before stopping the installed service or modifying its files. + OWRT_REMOTE_WAN_HELPER="$stage/wan.sh" sh "$stage/agent" wan-preflight + fi + if [ ! -e "$backup" ]; then + save_files "$stage/retained-backup" + mv "$stage/retained-backup" "$backup" + fi + validate_backup "$backup" || fail "Retained backup is incomplete: $backup. Nothing changed." + save_files "$stage/previous" + changed=1 + /etc/init.d/owrt-remote stop + mkdir -p /usr/lib/owrt-remote + for item in agent wan.sh; do + path=$(item_path "$item") + cp "$stage/$item" "$path.new-__UPLOAD_NAME__" + case "$item" in wan.sh) chmod 644 "$path.new-__UPLOAD_NAME__" ;; *) chmod 755 "$path.new-__UPLOAD_NAME__" ;; esac + mv -f "$path.new-__UPLOAD_NAME__" "$path" + done + /etc/init.d/owrt-remote restart + if [ "$(uci -q get owrtremote.main.enabled || echo 0)" = 1 ]; then + ready=0 + for attempt in 1 2 3 4 5 6 7 8 9 10; do + if /usr/sbin/owrt-remote status | grep -q '^xray_state: running'; then ready=1; break; fi + sleep 2 + done + if [ "$ready" != 1 ]; then + echo 'Xray did not start.' >&2 + logread | tail -n 50 >&2 || true + exit 1 + fi + ready=0 + for attempt in 1 2 3; do + if /usr/sbin/owrt-remote heartbeat >"$stage/heartbeat" 2>&1 && grep -Eq '"ok"[[:space:]]*:[[:space:]]*true' "$stage/heartbeat"; then ready=1; break; fi + sleep 2 + done + if [ "$ready" != 1 ]; then + echo 'Heartbeat did not reach Hub.' >&2 + cat "$stage/heartbeat" >&2 + exit 1 + fi + echo 'Xray: running; Heartbeat: OK' + fi + for item in agent wan.sh; do path=$(item_path "$item"); cmp "$stage/$item" "$path"; done +else + if [ ! -d "$backup" ]; then + fail "No backup on this router: $backup. Rollback requires a previous Install on this same router. Nothing changed." + fi + validate_backup "$backup" || fail "Backup is incomplete: $backup. Nothing changed." + save_files "$stage/previous" + changed=1 + restore_files "$backup" +fi +printf '\nBackup: %s\nWAN_STABILITY_ROUTER_%s_OK\n' "$backup" '__ACTION__' +'@ +$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action) +try { + [System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null + [System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8) + if ($Action -eq 'Install') { + foreach ($Item in $Payloads.GetEnumerator()) { + $Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Item.Value)).Replace("`r`n", "`n") + [System.IO.File]::WriteAllText((Join-Path $StageRoot $Item.Key), $Content, $Utf8) + } + } + if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return } + & scp -O -r -- $StageRoot "${Router}:/tmp/" + if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Installation has not started.' } + & ssh -T -o ConnectTimeout=10 $Router "sh /tmp/$UploadName/run.sh" + if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." } + Write-Host "WAN stability fix $Action finished successfully." +} finally { + if (-not $PrepareOnly) { + $Resolved = [System.IO.Path]::GetFullPath($StageRoot) + $Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName)) + if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) { throw 'Unsafe staging cleanup path.' } + if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force } + } +}