3x-ui/update.sh

818 lines
37 KiB
Bash
Raw Permalink Normal View History

#!/bin/bash
red='\033[0;31m'
green='\033[0;32m'
blue='\033[0;34m'
yellow='\033[0;33m'
plain='\033[0m'
xui_folder="${XUI_MAIN_FOLDER:=/usr/local/x-ui}"
xui_service="${XUI_SERVICE:=/etc/systemd/system}"
# Don't edit this config
b_source="${BASH_SOURCE[0]}"
while [ -h "$b_source" ]; do
2026-05-04 04:20:24 -07:00
b_dir="$(cd -P "$(dirname "$b_source")" > /dev/null 2>&1 && pwd || pwd -P)"
b_source="$(readlink "$b_source")"
[[ $b_source != /* ]] && b_source="$b_dir/$b_source"
done
2026-05-04 04:20:24 -07:00
cur_dir="$(cd -P "$(dirname "$b_source")" > /dev/null 2>&1 && pwd || pwd -P)"
script_name=$(basename "$0")
# Check command exist function
_command_exists() {
2026-05-04 04:20:24 -07:00
type "$1" &> /dev/null
}
# Fail, log and exit script function
_fail() {
local msg=${1}
echo -e "${red}${msg}${plain}"
exit 2
}
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
# Records this run's outcome for the panel's web updater to poll, since it
# launches this script detached and has no other way to learn whether it
# finished. Written to a fixed path outside XUI_MAIN_FOLDER so it survives
# the update regardless of what happens to that folder. The EXIT trap below
# covers every exit path in this file, including the bare `exit 1`/`exit 2`
# calls that don't go through _fail.
xui_update_run_id="${XUI_UPDATE_RUN_ID:-0}"
[[ "${xui_update_run_id}" =~ ^[0-9]+$ ]] || xui_update_run_id="0"
xui_update_status_file="${XUI_UPDATE_STATUS_FILE:-/etc/x-ui/update-status.json}"
_write_update_status() {
local state="$1"
local exit_code="$2"
local status_dir
status_dir="$(dirname "${xui_update_status_file}")"
mkdir -p "${status_dir}" > /dev/null 2>&1
local tmp_file="${xui_update_status_file}.tmp.$$"
printf '{"runId":"%s","state":"%s","exitCode":%s,"finishedAt":%s}\n' \
"${xui_update_run_id}" "${state}" "${exit_code}" "$(date +%s)" > "${tmp_file}" 2> /dev/null
mv -f "${tmp_file}" "${xui_update_status_file}" > /dev/null 2>&1
}
_report_update_exit() {
local code=$?
if [[ "${code}" -eq 0 ]]; then
_write_update_status "success" "0"
else
_write_update_status "failed" "${code}"
fi
}
trap _report_update_exit EXIT
trap 'exit 143' TERM
trap 'exit 130' INT
# check root
[[ $EUID -ne 0 ]] && _fail "FATAL ERROR: Please run this script with root privilege."
if _command_exists curl; then
curl_bin=$(which curl)
else
_fail "ERROR: Command 'curl' not found."
fi
# The panel sets XUI_UPDATE_PROXY to its egress bridge's socks5h URL for the GitHub downloads.
# The IP lookups use plain curl so they still report this server's own address.
[[ -n "${XUI_UPDATE_PROXY}" ]] && curl_bin="${curl_bin} --proxy ${XUI_UPDATE_PROXY}"
# Check OS and set release variable
if [[ -f /etc/os-release ]]; then
source /etc/os-release
release=$ID
2026-05-04 04:20:24 -07:00
elif [[ -f /usr/lib/os-release ]]; then
source /usr/lib/os-release
release=$ID
else
_fail "Failed to check the system OS, please contact the author!"
fi
echo "The OS release is: $release"
arch() {
case "$(uname -m)" in
x86_64 | x64 | amd64) echo 'amd64' ;;
i*86 | x86) echo '386' ;;
armv8* | armv8 | arm64 | aarch64) echo 'arm64' ;;
armv7* | armv7 | arm) echo 'armv7' ;;
armv6* | armv6) echo 'armv6' ;;
armv5* | armv5) echo 'armv5' ;;
s390x) echo 's390x' ;;
2026-05-04 04:20:24 -07:00
*) echo -e "${red}Unsupported CPU architecture!${plain}" && rm -f "${cur_dir}/${script_name}" > /dev/null 2>&1 && exit 2 ;;
esac
}
echo "Arch: $(arch)"
2025-12-27 15:03:33 -08:00
gen_random_string() {
local length="$1"
2026-05-04 04:20:24 -07:00
openssl rand -base64 $((length * 2)) \
| tr -dc 'a-zA-Z0-9' \
| head -c "$length"
2025-12-27 15:03:33 -08:00
}
xui_env_file_path() {
case "${release}" in
ubuntu | debian | armbian)
echo "/etc/default/x-ui"
;;
arch | manjaro | parch | alpine)
echo "/etc/conf.d/x-ui"
;;
*)
echo "/etc/sysconfig/x-ui"
;;
esac
}
load_xui_env() {
local env_file
env_file="$(xui_env_file_path)"
if [[ -r "$env_file" ]]; then
set -a
# shellcheck disable=SC1090
source "$env_file"
set +a
fi
}
install_base() {
echo -e "${green}Updating and install dependency packages...${plain}"
case "${release}" in
ubuntu | debian | armbian)
2026-05-04 04:20:24 -07:00
apt-get update > /dev/null 2>&1 && apt-get install -y -q cron curl tar tzdata socat openssl > /dev/null 2>&1
;;
fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
dnf makecache -y > /dev/null 2>&1 && dnf install -y -q cronie curl tar tzdata socat openssl > /dev/null 2>&1
2026-05-04 04:20:24 -07:00
;;
centos)
if [[ "${VERSION_ID}" =~ ^7 ]]; then
yum makecache -y > /dev/null 2>&1 && yum install -y -q cronie curl tar tzdata socat openssl > /dev/null 2>&1
else
dnf makecache -y > /dev/null 2>&1 && dnf install -y -q cronie curl tar tzdata socat openssl > /dev/null 2>&1
fi
2026-05-04 04:20:24 -07:00
;;
arch | manjaro | parch)
pacman -Sy --noconfirm cronie curl tar tzdata socat openssl > /dev/null 2>&1
2026-05-04 04:20:24 -07:00
;;
opensuse-tumbleweed | opensuse-leap)
2026-05-04 04:20:24 -07:00
zypper refresh > /dev/null 2>&1 && zypper -q install -y cron curl tar timezone socat openssl > /dev/null 2>&1
;;
alpine)
2026-05-04 04:20:24 -07:00
apk update > /dev/null 2>&1 && apk add dcron curl tar tzdata socat openssl > /dev/null 2>&1
;;
*)
2026-05-04 04:20:24 -07:00
apt-get update > /dev/null 2>&1 && apt install -y -q cron curl tar tzdata socat openssl > /dev/null 2>&1
;;
2025-12-27 15:03:33 -08:00
esac
}
config_after_update() {
local panel_needs_restart=0
echo -e "${yellow}x-ui settings:${plain}"
${xui_folder}/x-ui setting -show true
${xui_folder}/x-ui migrate
2026-05-04 04:20:24 -07:00
2025-12-27 15:03:33 -08:00
# Properly detect empty cert by checking if cert: line exists and has content after it
2026-05-04 04:20:24 -07:00
local existing_cert=$(${xui_folder}/x-ui setting -getCert true 2> /dev/null | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
local settings existing_webBasePath
if ! settings=$("${xui_folder}/x-ui" setting -show true) ||
! existing_webBasePath=$(printf '%s\n' "$settings" | awk '
/^get .* failed, error info:/ { failed = 1 }
/^hasDefaultCredential: (true|false)$/ { credentials++ }
/^port: [0-9]+$/ { ports++ }
/^webBasePath:/ { paths++; sub(/^webBasePath: ?/, ""); path = $0 }
END {
if (failed || credentials != 1 || ports != 1 || paths != 1 || (path != "" && path !~ /^\//)) exit 1
print path
}'); then
echo -e "${red}Unable to read webBasePath; leaving existing settings unchanged.${plain}" >&2
return 1
fi
existing_webBasePath=${existing_webBasePath#/}
local existing_port=$(printf '%s\n' "$settings" | awk '/^port: / {print $2}')
2026-05-04 04:20:24 -07:00
2025-12-27 15:03:33 -08:00
# Get server IP
local URL_lists=(
"https://api4.ipify.org"
"https://ipv4.icanhazip.com"
"https://v4.api.ipinfo.io/ip"
"https://ipv4.myexternalip.com/raw"
"https://4.ident.me"
"https://check-host.net/ip"
)
local server_ip=""
for ip_address in "${URL_lists[@]}"; do
2026-05-04 04:20:24 -07:00
local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
local http_code=$(echo "$response" | tail -n1)
local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
server_ip="${ip_result}"
2025-12-27 15:03:33 -08:00
break
fi
done
2026-05-04 04:20:24 -07:00
# Only used to print the access URL; never prompt, the web updater has no TTY.
if [[ -z "$server_ip" ]]; then
server_ip=$(hostname -I 2> /dev/null | awk '{print $1}')
server_ip="${server_ip:-<server-ip>}"
fi
# Only an unset or default root path needs initialization.
if [[ -z "$existing_webBasePath" ]]; then
echo -e "${yellow}WebBasePath is missing or set to root. Generating a new one...${plain}"
2025-12-27 15:03:33 -08:00
local config_webBasePath=$(gen_random_string 18)
${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}"
2025-12-27 15:03:33 -08:00
existing_webBasePath="${config_webBasePath}"
panel_needs_restart=1
2025-12-27 15:03:33 -08:00
echo -e "${green}New WebBasePath: ${config_webBasePath}${plain}"
fi
2026-05-04 04:20:24 -07:00
# An update only updates the panel: TLS stays exactly as configured. Set it up
# explicitly from the x-ui menu (SSL Certificate Management).
local access_scheme="http" access_host="${server_ip}"
if [[ -n "$existing_cert" ]]; then
access_scheme="https"
access_host=$(basename "$(dirname "$existing_cert")")
fi
echo ""
echo -e "${green}═══════════════════════════════════════════${plain}"
echo -e "${green} Panel Access Information ${plain}"
echo -e "${green}═══════════════════════════════════════════${plain}"
echo -e "${green}Access URL: ${access_scheme}://${access_host}:${existing_port}/${existing_webBasePath}${plain}"
echo -e "${green}═══════════════════════════════════════════${plain}"
2025-12-27 15:03:33 -08:00
if [[ -z "$existing_cert" ]]; then
echo -e "${yellow}No SSL certificate is configured; the panel is served over HTTP.${plain}"
echo -e "${yellow}Run 'x-ui' and choose SSL Certificate Management to set one up.${plain}"
2025-12-27 15:03:33 -08:00
fi
if [[ "$panel_needs_restart" -eq 1 ]]; then
echo -e "${yellow}Restarting panel to apply the new web base path...${plain}"
systemctl restart x-ui 2> /dev/null || rc-service x-ui restart 2> /dev/null
fi
}
# setup_fail2ban auto-installs and configures fail2ban for the IP Limit feature
# by invoking the freshly downloaded x-ui CLI. IP Limit is load-bearing on
# fail2ban (without it the panel disables the limitIp field and zeroes existing
# limits), so updating an older install should make it work without a manual
# trip through the IP Limit menu. Non-fatal: a fail2ban failure must never abort
# the update. XUI_ENABLE_FAIL2BAN is honored (load_xui_env exports it from the
# persisted env file, so a deliberate opt-out survives updates).
setup_fail2ban() {
if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then
echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban auto-setup.${plain}"
return 0
fi
if [[ ! -x /usr/bin/x-ui ]]; then
echo -e "${yellow}x-ui CLI not found; skipping Fail2ban auto-setup.${plain}"
return 0
fi
fix(install): fetch x-ui.sh and unit files from the installed release tag (#6391) * fix(install): fetch x-ui.sh and unit files from the installed release tag install.sh and update.sh pin the panel archive to a release tag but always took x-ui.sh, x-ui.rc and the service units from main, so the management script and the binary of one installation came from different commits: the fail2ban templates and setting flags the script writes drift silently against an older binary, two installs of the same tag differ, and a reviewed or digest-pinned installer still runs unreviewed code from main. Use the same ref as the archive, keeping main only for the rolling dev-latest build. The menu's "update menu" and update_shell paths now fetch the script matching the installed version and fall back to main with a visible notice when no script is published for it. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): fall back to main for files a pinned tag does not publish Review follow-ups. install.sh accepts tags down to v2.3.5, but x-ui.rc only exists from v2.8.4 and the split x-ui.service.* files are newer still, so pinning those to the tag made an Alpine install of an old tag 404 after the previous install was already removed. Probe the tag for each file and fall back to main with a notice when it is missing, as the menu already does for x-ui.sh. The fail2ban auto-setup probe also trusted the exit status of 'x-ui setup-fail2ban', but scripts before v3.4.0 have no such subcommand and exit 0 from the usage banner, so the installer reported a setup that never ran. Skip with a notice when the installed script does not know the subcommand. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): refuse a tag that does not publish a needed script Falling back to main reintroduced the binary/script mismatch the tag pinning exists to remove, and it fired at points where install.sh and update.sh have already stopped and removed the previous installation -- so the quiet path was also the one that could not be undone. Probe the tag instead, before anything is touched, for every file that is always fetched from GitHub (x-ui.sh, plus x-ui.rc on Alpine), and abort with the HTTP status when one is missing. The unit files stay unprobed: they are only fetched when the release tarball omits them, so an old tag that ships x-ui.service inside its tarball still installs. Their existing failure message now names the ref it tried. Also tighten the setup-fail2ban probe to the dispatcher's case arm rather than any mention of the string, which also matches a comment. --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-09-03 07:50:53 -07:00
# Scripts older than v3.4.0 have no setup-fail2ban and exit 0 from the
# usage banner, which would read as success here.
if ! grep -q '"setup-fail2ban")' /usr/bin/x-ui; then
echo -e "${yellow}This x-ui.sh predates 'x-ui setup-fail2ban'; skipping Fail2ban auto-setup.${plain}"
return 0
fi
echo -e "${green}Setting up Fail2ban for the IP Limit feature...${plain}"
if /usr/bin/x-ui setup-fail2ban; then
echo -e "${green}Fail2ban setup complete.${plain}"
else
echo -e "${yellow}Fail2ban setup did not finish; IP Limit stays disabled until you run 'x-ui' and open the IP Limit menu. Continuing.${plain}"
fi
return 0
}
fix(systemd): harden shipped x-ui unit files (#6718) * fix(systemd): harden shipped x-ui unit files The units ran the panel as root with no sandboxing: systemd-analyze security rates them 9.6 UNSAFE. Add NoNewPrivileges, ProtectSystem=full with ReadWritePaths for the default XUI_DB_FOLDER/XUI_BIN_FOLDER/XUI_LOG_FOLDER stores, kernel and clock protections, UMask=0077, RestrictAddressFamilies, a CapabilityBoundingSet with NET_ADMIN/NET_BIND_SERVICE/NET_RAW and SystemCallFilter=@system-service. PrivateTmp is deliberately omitted: the web updater hands a path inside the system temp directory to a systemd-run transient unit, which does not share the service's private tmpfs. ProtectHome stays read-only because installs keep TLS certificates under the root home directory. Fixes #6605 * fix(systemd): ship ReadWriteDirectories= alias for systemd < 231 ReadWritePaths= only exists since systemd 231; install.sh still supports CentOS 7 (systemd 219), where the directive is ignored and ProtectSystem=full would leave the panel state directory read-only, breaking its database. * fix(systemd): keep root's DAC bits and regenerate the write paths Two follow-ups to the hardening, both reported by review on #6718. CAP_DAC_OVERRIDE and CAP_DAC_READ_SEARCH were dropped from the bounding set. Root holds them normally, and a bounding set is subtracted from root too: the panel could no longer read a private key it does not own (a Caddy-issued certificate under its own state dir, an acme.sh home, any 0600 file owned by another account). That fails quietly for TLS -- the panel listener logs the tls.LoadX509KeyPair error and keeps serving plain HTTP, and Xray inbounds using that key stop -- so both bits stay. ProtectSystem=full plus a hard-coded ReadWritePaths list broke installs whose XUI_DB_FOLDER/XUI_LOG_FOLDER/XUI_BIN_FOLDER live outside the defaults, and the workaround of editing the unit did not survive an update, because install.sh and update.sh reinstall the unit from the release tarball. The folders actually in use are now resolved from the same env file the unit passes to the panel and regenerated into x-ui.service.d/10-xui-write-paths.conf on every install and update, so a relocated store stays writable and the list is not reset. The unit keeps the plain-install defaults plus XUI_SERVICE, which the in-panel updater needs when systemd-run is unavailable and it falls back to a child process that inherits this sandbox while update.sh lands the unit again. Uninstall removes the drop-in with the unit. * fix(systemd): keep the seccomp whitelist off old systemd, tighten the rest Review of the previous head found that SystemCallFilter=@system-service plus SystemCallErrorNumber=EPERM is a hard regression on the platforms this PR means to keep working. @-named filter groups exist from systemd 239 on, and older systemd does not ignore an unknown group name: on <231 the name fails to resolve and the filter stays the built-in whitelist of execve/exit/exit_group/ rt_sigreturn/sigreturn, on 231..238 it degrades to @default. Either way the panel then gets EPERM on read/openat/mmap/clone and cannot start -- a CentOS 7 or Ubuntu 18.04 install would come up dead after this update. The two directives now live in the generated drop-in and are written only when "systemctl --version" reports 239 or newer, so old hosts keep the rest of the hardening and simply go without seccomp. The same review listed three more items, all addressed here: - a comment claiming ProtectSystem=full "keeps everything outside /var, /run and the listed ReadWritePaths read-only" -- that is `strict`; `full` locks down /usr, /boot, /efi and /etc; - /etc/systemd/system was granted writable for the in-panel updater's fallback, but that fallback cannot work under this sandbox at all: update.sh also stages the release archive beside the main folder, replaces /usr/bin/x-ui and calls the package manager. The entry is gone and update.sh now stops up front with one clear message when the directories it needs are read-only, instead of failing halfway with "Failed to download x-ui"; - CAP_DAC_READ_SEARCH is redundant next to CAP_DAC_OVERRIDE, so the bounding set keeps just the latter. Relocating a store by editing the env file alone is documented in the unit and in the generated drop-in: the drop-in is only written by install/update, so one of those has to be re-run afterwards. Verified with a local harness (9 checks: plain defaults, relocated store read from the env file, the same list produced by update.sh, duplicate collapse, seccomp present at systemd 249 and absent at 238, read-only guard) and bash -n on install.sh, update.sh, x-ui.sh. systemd-analyze is not available here, so the unit files themselves are unverified by a parser. * fix(systemd): actually wire the read-only guard, drop the superseded drop-in Re-review of the previous head caught two leftovers from that commit: - require_writable_update_paths was defined but never called, so the guard the unit comments, the commit message and the PR comment promise did not exist at all. It is now called at the top level, before install_base, i.e. before anything with a side effect: a sandboxed fallback run stops with one clear message instead of failing halfway, which on a relocated main folder meant the old install removed and the service folder rewritten before dying on /usr/bin. - the drop-in this branch replaced (10-xui-write-paths.conf) is no longer written or referenced, but nothing removed it either. Whoever installed the build that wrote it keeps its wider list, including the writable service folder, until it is deleted by hand. Both generators now remove it. Harness extended to 11 checks: the superseded file is gone after a run, the guard is actually called, plus the previous nine (defaults, env-file relocation, same list from update.sh, dedupe, seccomp at 249 / absent at 238, read-only guard) and bash -n on the three scripts. * fix(systemd): correct two comments and keep spaces out of the path list Second-opinion review of the previous head (two models, both asked to state platforms and versions) produced three actionable items: a wrong comment kept from the earlier commits, a wrong generalisation about the filter groups, and a path-list case that would leave the panel unable to start. - the ProtectSystem= comment claimed strict leaves /var and /run writable. It does not: strict mounts the whole hierarchy read-only and only the kernel API filesystems stay as they are. The sentence was already wrong before this branch and moving it to ProtectSystem=full did not fix it. - "the @-named filter groups need systemd >= 239" is the wrong generalisation: named groups exist since 231, it is @system-service that arrived in 239. The unit files, both script comments and the drop-in body now name the group. - a folder containing whitespace (XUI_DB_FOLDER="/srv/panel data") was written into ReadWritePaths= verbatim. That directive is a whitespace-separated list, so the entry splits into "-/srv/panel" and "data", and systemd rejects the whole drop-in: the panel then does not start at all. Such folders are left out and reported to the operator instead; the other paths are still written. Harness extended with three checks for the whitespace case (folder left out, remaining paths intact, warning emitted) and the duplicate-store case now reads its own env file instead of the previous one, so it tests what it claims. 14 checks plus bash -n on the three scripts, all passing. * fix(systemd): act on the independent review of the drop-in generator A read-only review of the branch head (another model, given the diff and the sources, asked to cite only verified lines) confirmed the earlier work and turned up four items that are fixed here: - a folder name carrying a literal % went into ReadWritePaths= as it was, and systemd expands %-specifiers in unit files: with XUI_DB_FOLDER=/srv/x%-ui the entry no longer named the directory the panel writes to and the panel could not write its database. The path is now emitted as %%; the duplicate check keeps comparing the unescaped value. - systemd older than 229/242/244 does not know NoNewPrivileges, ProtectClock, ProtectHostname and ProtectKernelLogs. It logs them and carries on, so CentOS 7 (systemd 219, which install.sh explicitly supports) runs with less hardening than the unit lists. install.sh and update.sh now print which protections need a newer systemd, which ones still apply, and that upgrading systemd is what changes it. - the updater's writability guard asked [[ -w ]] about the parent directories. It creates and removes a probe file instead, so an immutable attribute or a full filesystem is caught as well (a read-only mount was already caught). - the generator's comment claimed to resolve the folders the service actually uses, while the shipped unit hard-codes WorkingDirectory= and ExecStart= under /usr/local/x-ui. The comment now states what XUI_MAIN_FOLDER really feeds -- the location install.sh/update.sh install into and the base for a relative XUI_BIN_FOLDER -- and that a relocated main folder needs the unit edited too. Rejected from the same review, with the evidence: that [[ -w ]] cannot see a read-only mount (access(W_OK)/faccessat consults __mnt_is_readonly before the mode bits), and that the /etc ReadWritePaths entry is an exception granted for /etc rather than a default store already in the list. Harness extended: 19 checks (escaped %, the old-systemd note, whitespace and duplicate folders, seccomp gating, the read-only guard) plus bash -n on the three scripts, all passing. * fix(systemd): name the hardening old systemd really ignores The old-systemd note fired only below 239 and listed wrong versions: RHEL 8 (239) and Debian 10 (241) silently lose ProtectHostname and RestrictSUIDSGID (242), ProtectKernelLogs (244) and ProtectClock (245) with no note, while CentOS 7 was told NoNewPrivileges (187) and ProtectHome=read-only (214) were not applied although both are. The note is now built from a directive/version table taken from systemd.exec(5) and lists only what the running systemd lacks. Also drop the removal of 10-xui-write-paths.conf: only an intermediate commit of this branch wrote that file, no release ever shipped it. --------- Co-authored-by: Кот <kot@zeroclaw.local> Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-10-05 09:47:10 -07:00
# The hardened unit makes /usr, /boot, /efi and /etc read-only. The panel's own
# updater is expected to escape that sandbox by running this script through a
# transient systemd-run unit; when systemd-run is unavailable it starts this
# script as a plain child instead, and that child inherits the sandbox and then
# cannot write anything this update needs. Say so once, up front, instead of
# dying partway through with "Failed to download x-ui".
require_writable_update_paths() {
local dir probe
for dir in "${xui_folder%/*}" "/usr/bin"; do
[[ -n "$dir" && -d "$dir" ]] || continue
probe="${dir}/.x-ui-write-test.$$"
# A real write test rather than [[ -w ]]: this runs as root, where a
# permission bit means little and the test only reflects the file mode
# and the mount flags, not an immutable attribute or a full filesystem.
if ! : > "$probe" 2> /dev/null; then
_fail "ERROR: ${dir} is not writable for this process (read-only mount, attribute or full filesystem). The panel's fallback updater cannot run inside the hardened systemd sandbox; update from the panel UI (which uses systemd-run) or run 'x-ui update' in a shell."
fi
rm -f "$probe"
done
}
# Major version of the local systemd, 0 when it cannot be determined. The
# SystemCallFilter=@system-service group only exists from systemd 239 on (other
# @-named groups exist since 231); on older versions an unknown group is not
# ignored safely, the filter stays in force and leaves a whitelist the panel
# cannot run under.
_xui_systemd_major_version() {
local version=""
if command -v systemctl > /dev/null 2>&1; then
version="$(systemctl --version 2>/dev/null | awk 'NR == 1 {print $2}')"
fi
if [[ ! "$version" =~ ^[0-9]+$ ]]; then
echo 0
return 0
fi
echo "$version"
}
# The shipped units list hardening that older systemd does not know: the
# directive is logged and ignored at load time rather than rejected, so the
# panel still starts, only without that protection. Each entry is the systemd
# release that introduced the directive (systemd.exec(5)); everything else in
# the unit predates the oldest systemd install.sh supports (CentOS 7 has 219).
# SystemCallFilter= is listed because the drop-in only writes it from 239 on.
_xui_warn_unsupported_hardening() {
local version entry missing=""
version="$(_xui_systemd_major_version)"
[[ "$version" -gt 0 ]] || return 0
for entry in RestrictRealtime:231 ReadWritePaths:231 ProtectKernelTunables:232 \
ProtectKernelModules:232 RestrictNamespaces:233 LockPersonality:235 \
SystemCallFilter:239 ProtectHostname:242 RestrictSUIDSGID:242 \
ProtectKernelLogs:244 ProtectClock:245; do
if [[ "$version" -lt "${entry##*:}" ]]; then
missing="${missing:+$missing, }${entry%%:*} (${entry##*:})"
fi
done
[[ -n "$missing" ]] || return 0
echo -e "${yellow}Note: systemd ${version} ignores part of the hardening in x-ui.service; the panel still starts.${plain}"
echo " Not applied, needs a newer systemd: ${missing}."
if [[ "$version" -lt 231 ]]; then
echo " The panel's folders stay writable through ReadWriteDirectories=, the alias this script installs."
fi
echo " The rest of the hardening is in force. Upgrade systemd to apply the above."
return 0
}
# ProtectSystem=full makes /usr, /boot, /efi and /etc read-only. ProtectSystem=
# strict would make the whole hierarchy read-only (only the kernel API
# filesystems stay as they are), and that would break the panel's own use of
# /tmp. The panel's stores are configurable (XUI_DB_FOLDER, XUI_LOG_FOLDER,
# XUI_BIN_FOLDER), and XUI_MAIN_FOLDER is the folder install.sh/update.sh place
# the files in -- the unit's WorkingDirectory on a stock install, and what a
# relative XUI_BIN_FOLDER is resolved against. So a hard-coded list in the unit
# either misses a relocated store -- the panel then cannot write its own SQLite
# database and sits in a Restart=on-failure loop -- or forces the operator to
# edit a file that every install/update overwrites from the release tarball.
# install.sh and update.sh therefore regenerate the drop-in from the folders
# actually in use, and the unit's own ReadWritePaths only carry the
# plain-install defaults. A relocated store means re-running install or update:
# the drop-in is only written here.
_xui_service_write_paths_dropin() {
# $1 is the env file to resolve the XUI_* folders from; callers pass nothing
# and get the OS-specific path the unit itself uses.
local env_file="${1:-}"
local dropin_dir dropin temp_file
local db_folder log_folder bin_folder main_folder
local path line="" whitespace_paths="" seen_paths="" escaped_path
if [[ -z "$env_file" ]]; then
env_file="$(xui_env_file_path)"
fi
if [[ -r "$env_file" ]]; then
set -a
# shellcheck disable=SC1090
source "$env_file"
set +a
fi
# XUI_* wins over the script's own default: the unit hands that same env
# file to the panel through EnvironmentFile=, so these are the folders it
# will actually use.
main_folder="${XUI_MAIN_FOLDER:-${xui_folder}}"
db_folder="${XUI_DB_FOLDER:-/etc/x-ui}"
log_folder="${XUI_LOG_FOLDER:-/var/log/x-ui}"
# An empty XUI_BIN_FOLDER resolves to "bin" relative to the panel's working
# directory, which the unit sets to the main folder.
bin_folder="${XUI_BIN_FOLDER:-bin}"
if [[ "$bin_folder" != /* ]]; then
bin_folder="${main_folder%/}/${bin_folder#./}"
fi
for path in "$db_folder" "$log_folder" "$bin_folder" "$main_folder"; do
[[ "$path" == /* ]] || continue
# ReadWritePaths= is a whitespace-separated list, and a folder whose
# name contains whitespace cannot be written into it without relying on
# quoting. A wrong entry makes systemd reject the whole drop-in and the
# panel would not start, so leave such a folder out and say so instead.
if [[ "$path" != "${path//[[:space:]]/}" ]]; then
whitespace_paths="${whitespace_paths:+$whitespace_paths }$path"
continue
fi
case " $seen_paths " in
*" $path "*) continue ;;
esac
seen_paths="${seen_paths}${seen_paths:+ }$path"
# systemd expands %-specifiers in unit files, so a folder name carrying
# a literal % has to be written as %%, or the entry stops naming the
# folder systemd is meant to keep writable.
escaped_path="${path//%/%%}"
line="${line} -${escaped_path}"
done
if [[ -n "$whitespace_paths" ]]; then
echo "Warning: these folders contain whitespace and were left out of" >&2
echo " 10-xui-sandbox.conf: $whitespace_paths" >&2
echo " The panel cannot write to them under the unit's sandbox." >&2
fi
line="${line# }"
[[ -n "$line" ]] || return 1
dropin_dir="${xui_service}/x-ui.service.d"
dropin="${dropin_dir}/10-xui-sandbox.conf"
temp_file="${dropin}.tmp.$$"
mkdir -p "$dropin_dir" || return 1
cat > "$temp_file" << EOF
# Regenerated by install.sh/update.sh on every install and update: edits here
# are lost, and the list only reflects the XUI_* variables read from
# ${env_file} at that moment. Re-run install/update after moving a store.
# It lists the folders the panel writes to. Put local additions in their own
# drop-in, for example 20-x-ui-local.conf, which nothing here touches.
[Service]
ReadWritePaths=${line}
ReadWriteDirectories=${line}
EOF
if [[ "$(_xui_systemd_major_version)" -ge 239 ]]; then
cat >> "$temp_file" << 'EOF'
# @system-service needs systemd >= 239; on older versions the unknown group
# would leave the panel with a filter it cannot start under (x-ui.service.*).
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM
EOF
fi
if [[ ! -s "$temp_file" ]]; then
rm -f "$temp_file"
return 1
fi
chmod 644 "$temp_file"
mv -f "$temp_file" "$dropin" || { rm -f "$temp_file"; return 1; }
if command -v systemctl > /dev/null 2>&1; then
systemctl daemon-reload > /dev/null 2>&1 || true
fi
return 0
}
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
# Lands a systemd unit file at ${xui_service}/x-ui.service via a temp file +
# atomic mv, so a failed cp/curl or an interrupted mv never leaves a
# truncated unit file at the live path -- systemd would then fail to parse
# it on the next daemon-reload/start. Same pattern already used for
# /usr/bin/x-ui elsewhere in this script. source_is_url picks cp (from a
# file already extracted from the release tarball) vs curl (GitHub fallback).
_install_xui_service_unit() {
local source="$1"
local source_is_url="$2"
local dest="${xui_service}/x-ui.service"
local temp_file="${dest}.tmp.$$"
rm -f "$temp_file"
if [[ "$source_is_url" == "true" ]]; then
${curl_bin} -fLRo "$temp_file" "$source" > /dev/null 2>&1
else
cp -f "$source" "$temp_file" > /dev/null 2>&1
fi
if [[ $? -ne 0 ]]; then
rm -f "$temp_file"
return 1
fi
if [[ ! -s "$temp_file" ]]; then
rm -f "$temp_file"
return 1
fi
mv -f "$temp_file" "$dest"
if [[ $? -ne 0 ]]; then
rm -f "$temp_file"
return 1
fi
fix(systemd): harden shipped x-ui unit files (#6718) * fix(systemd): harden shipped x-ui unit files The units ran the panel as root with no sandboxing: systemd-analyze security rates them 9.6 UNSAFE. Add NoNewPrivileges, ProtectSystem=full with ReadWritePaths for the default XUI_DB_FOLDER/XUI_BIN_FOLDER/XUI_LOG_FOLDER stores, kernel and clock protections, UMask=0077, RestrictAddressFamilies, a CapabilityBoundingSet with NET_ADMIN/NET_BIND_SERVICE/NET_RAW and SystemCallFilter=@system-service. PrivateTmp is deliberately omitted: the web updater hands a path inside the system temp directory to a systemd-run transient unit, which does not share the service's private tmpfs. ProtectHome stays read-only because installs keep TLS certificates under the root home directory. Fixes #6605 * fix(systemd): ship ReadWriteDirectories= alias for systemd < 231 ReadWritePaths= only exists since systemd 231; install.sh still supports CentOS 7 (systemd 219), where the directive is ignored and ProtectSystem=full would leave the panel state directory read-only, breaking its database. * fix(systemd): keep root's DAC bits and regenerate the write paths Two follow-ups to the hardening, both reported by review on #6718. CAP_DAC_OVERRIDE and CAP_DAC_READ_SEARCH were dropped from the bounding set. Root holds them normally, and a bounding set is subtracted from root too: the panel could no longer read a private key it does not own (a Caddy-issued certificate under its own state dir, an acme.sh home, any 0600 file owned by another account). That fails quietly for TLS -- the panel listener logs the tls.LoadX509KeyPair error and keeps serving plain HTTP, and Xray inbounds using that key stop -- so both bits stay. ProtectSystem=full plus a hard-coded ReadWritePaths list broke installs whose XUI_DB_FOLDER/XUI_LOG_FOLDER/XUI_BIN_FOLDER live outside the defaults, and the workaround of editing the unit did not survive an update, because install.sh and update.sh reinstall the unit from the release tarball. The folders actually in use are now resolved from the same env file the unit passes to the panel and regenerated into x-ui.service.d/10-xui-write-paths.conf on every install and update, so a relocated store stays writable and the list is not reset. The unit keeps the plain-install defaults plus XUI_SERVICE, which the in-panel updater needs when systemd-run is unavailable and it falls back to a child process that inherits this sandbox while update.sh lands the unit again. Uninstall removes the drop-in with the unit. * fix(systemd): keep the seccomp whitelist off old systemd, tighten the rest Review of the previous head found that SystemCallFilter=@system-service plus SystemCallErrorNumber=EPERM is a hard regression on the platforms this PR means to keep working. @-named filter groups exist from systemd 239 on, and older systemd does not ignore an unknown group name: on <231 the name fails to resolve and the filter stays the built-in whitelist of execve/exit/exit_group/ rt_sigreturn/sigreturn, on 231..238 it degrades to @default. Either way the panel then gets EPERM on read/openat/mmap/clone and cannot start -- a CentOS 7 or Ubuntu 18.04 install would come up dead after this update. The two directives now live in the generated drop-in and are written only when "systemctl --version" reports 239 or newer, so old hosts keep the rest of the hardening and simply go without seccomp. The same review listed three more items, all addressed here: - a comment claiming ProtectSystem=full "keeps everything outside /var, /run and the listed ReadWritePaths read-only" -- that is `strict`; `full` locks down /usr, /boot, /efi and /etc; - /etc/systemd/system was granted writable for the in-panel updater's fallback, but that fallback cannot work under this sandbox at all: update.sh also stages the release archive beside the main folder, replaces /usr/bin/x-ui and calls the package manager. The entry is gone and update.sh now stops up front with one clear message when the directories it needs are read-only, instead of failing halfway with "Failed to download x-ui"; - CAP_DAC_READ_SEARCH is redundant next to CAP_DAC_OVERRIDE, so the bounding set keeps just the latter. Relocating a store by editing the env file alone is documented in the unit and in the generated drop-in: the drop-in is only written by install/update, so one of those has to be re-run afterwards. Verified with a local harness (9 checks: plain defaults, relocated store read from the env file, the same list produced by update.sh, duplicate collapse, seccomp present at systemd 249 and absent at 238, read-only guard) and bash -n on install.sh, update.sh, x-ui.sh. systemd-analyze is not available here, so the unit files themselves are unverified by a parser. * fix(systemd): actually wire the read-only guard, drop the superseded drop-in Re-review of the previous head caught two leftovers from that commit: - require_writable_update_paths was defined but never called, so the guard the unit comments, the commit message and the PR comment promise did not exist at all. It is now called at the top level, before install_base, i.e. before anything with a side effect: a sandboxed fallback run stops with one clear message instead of failing halfway, which on a relocated main folder meant the old install removed and the service folder rewritten before dying on /usr/bin. - the drop-in this branch replaced (10-xui-write-paths.conf) is no longer written or referenced, but nothing removed it either. Whoever installed the build that wrote it keeps its wider list, including the writable service folder, until it is deleted by hand. Both generators now remove it. Harness extended to 11 checks: the superseded file is gone after a run, the guard is actually called, plus the previous nine (defaults, env-file relocation, same list from update.sh, dedupe, seccomp at 249 / absent at 238, read-only guard) and bash -n on the three scripts. * fix(systemd): correct two comments and keep spaces out of the path list Second-opinion review of the previous head (two models, both asked to state platforms and versions) produced three actionable items: a wrong comment kept from the earlier commits, a wrong generalisation about the filter groups, and a path-list case that would leave the panel unable to start. - the ProtectSystem= comment claimed strict leaves /var and /run writable. It does not: strict mounts the whole hierarchy read-only and only the kernel API filesystems stay as they are. The sentence was already wrong before this branch and moving it to ProtectSystem=full did not fix it. - "the @-named filter groups need systemd >= 239" is the wrong generalisation: named groups exist since 231, it is @system-service that arrived in 239. The unit files, both script comments and the drop-in body now name the group. - a folder containing whitespace (XUI_DB_FOLDER="/srv/panel data") was written into ReadWritePaths= verbatim. That directive is a whitespace-separated list, so the entry splits into "-/srv/panel" and "data", and systemd rejects the whole drop-in: the panel then does not start at all. Such folders are left out and reported to the operator instead; the other paths are still written. Harness extended with three checks for the whitespace case (folder left out, remaining paths intact, warning emitted) and the duplicate-store case now reads its own env file instead of the previous one, so it tests what it claims. 14 checks plus bash -n on the three scripts, all passing. * fix(systemd): act on the independent review of the drop-in generator A read-only review of the branch head (another model, given the diff and the sources, asked to cite only verified lines) confirmed the earlier work and turned up four items that are fixed here: - a folder name carrying a literal % went into ReadWritePaths= as it was, and systemd expands %-specifiers in unit files: with XUI_DB_FOLDER=/srv/x%-ui the entry no longer named the directory the panel writes to and the panel could not write its database. The path is now emitted as %%; the duplicate check keeps comparing the unescaped value. - systemd older than 229/242/244 does not know NoNewPrivileges, ProtectClock, ProtectHostname and ProtectKernelLogs. It logs them and carries on, so CentOS 7 (systemd 219, which install.sh explicitly supports) runs with less hardening than the unit lists. install.sh and update.sh now print which protections need a newer systemd, which ones still apply, and that upgrading systemd is what changes it. - the updater's writability guard asked [[ -w ]] about the parent directories. It creates and removes a probe file instead, so an immutable attribute or a full filesystem is caught as well (a read-only mount was already caught). - the generator's comment claimed to resolve the folders the service actually uses, while the shipped unit hard-codes WorkingDirectory= and ExecStart= under /usr/local/x-ui. The comment now states what XUI_MAIN_FOLDER really feeds -- the location install.sh/update.sh install into and the base for a relative XUI_BIN_FOLDER -- and that a relocated main folder needs the unit edited too. Rejected from the same review, with the evidence: that [[ -w ]] cannot see a read-only mount (access(W_OK)/faccessat consults __mnt_is_readonly before the mode bits), and that the /etc ReadWritePaths entry is an exception granted for /etc rather than a default store already in the list. Harness extended: 19 checks (escaped %, the old-systemd note, whitespace and duplicate folders, seccomp gating, the read-only guard) plus bash -n on the three scripts, all passing. * fix(systemd): name the hardening old systemd really ignores The old-systemd note fired only below 239 and listed wrong versions: RHEL 8 (239) and Debian 10 (241) silently lose ProtectHostname and RestrictSUIDSGID (242), ProtectKernelLogs (244) and ProtectClock (245) with no note, while CentOS 7 was told NoNewPrivileges (187) and ProtectHome=read-only (214) were not applied although both are. The note is now built from a directive/version table taken from systemd.exec(5) and lists only what the running systemd lacks. Also drop the removal of 10-xui-write-paths.conf: only an intermediate commit of this branch wrote that file, no release ever shipped it. --------- Co-authored-by: Кот <kot@zeroclaw.local> Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-10-05 09:47:10 -07:00
if ! _xui_service_write_paths_dropin; then
echo -e "${yellow}Warning: could not refresh ${xui_service}/x-ui.service.d/10-xui-sandbox.conf.${plain}"
echo -e "${yellow}If XUI_DB_FOLDER or XUI_LOG_FOLDER points outside /etc/x-ui and /var/log/x-ui, the panel may not be able to write to it under ProtectSystem=full.${plain}"
fi
_xui_warn_unsupported_hardening
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
return 0
}
fix(install): fetch x-ui.sh and unit files from the installed release tag (#6391) * fix(install): fetch x-ui.sh and unit files from the installed release tag install.sh and update.sh pin the panel archive to a release tag but always took x-ui.sh, x-ui.rc and the service units from main, so the management script and the binary of one installation came from different commits: the fail2ban templates and setting flags the script writes drift silently against an older binary, two installs of the same tag differ, and a reviewed or digest-pinned installer still runs unreviewed code from main. Use the same ref as the archive, keeping main only for the rolling dev-latest build. The menu's "update menu" and update_shell paths now fetch the script matching the installed version and fall back to main with a visible notice when no script is published for it. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): fall back to main for files a pinned tag does not publish Review follow-ups. install.sh accepts tags down to v2.3.5, but x-ui.rc only exists from v2.8.4 and the split x-ui.service.* files are newer still, so pinning those to the tag made an Alpine install of an old tag 404 after the previous install was already removed. Probe the tag for each file and fall back to main with a notice when it is missing, as the menu already does for x-ui.sh. The fail2ban auto-setup probe also trusted the exit status of 'x-ui setup-fail2ban', but scripts before v3.4.0 have no such subcommand and exit 0 from the usage banner, so the installer reported a setup that never ran. Skip with a notice when the installed script does not know the subcommand. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): refuse a tag that does not publish a needed script Falling back to main reintroduced the binary/script mismatch the tag pinning exists to remove, and it fired at points where install.sh and update.sh have already stopped and removed the previous installation -- so the quiet path was also the one that could not be undone. Probe the tag instead, before anything is touched, for every file that is always fetched from GitHub (x-ui.sh, plus x-ui.rc on Alpine), and abort with the HTTP status when one is missing. The unit files stay unprobed: they are only fetched when the release tarball omits them, so an old tag that ships x-ui.service inside its tarball still installs. Their existing failure message now names the ref it tried. Also tighten the setup-fail2ban probe to the dispatcher's case arm rather than any mention of the string, which also matches a comment. --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-09-03 07:50:53 -07:00
# Older tags predate some of these files (x-ui.rc arrived in v2.8.4). Serving
# main's copy against an old binary is the mismatch this pinning exists to
# prevent, so probe before the old install is removed and refuse the tag.
require_repo_files() {
local ref="$1" name status
shift
[[ "${ref}" == "main" ]] && return 0
for name in "$@"; do
status=$(${curl_bin} -sIL --retry 3 --connect-timeout 15 -o /dev/null -w '%{http_code}' "https://raw.githubusercontent.com/MHSanaei/3x-ui/${ref}/${name}")
if [[ "${status}" != "200" ]]; then
_fail "ERROR: ${name} is not available for ${ref} (HTTP ${status}). Update to a release that ships it, or to 'dev-latest'. The current installation is untouched."
fi
done
}
update_x-ui() {
cd ${xui_folder%/x-ui}/
2026-05-04 04:20:24 -07:00
load_xui_env
if [ -f "${xui_folder}/x-ui" ]; then
current_xui_version=$(${xui_folder}/x-ui -v)
echo -e "${green}Current x-ui version: ${current_xui_version}${plain}"
else
_fail "ERROR: Current x-ui version: unknown"
fi
2026-05-04 04:20:24 -07:00
echo -e "${green}Downloading new x-ui version...${plain}"
2026-05-04 04:20:24 -07:00
# XUI_UPDATE_TAG lets the panel target a specific release tag (e.g. the
# rolling dev-latest pre-release). Empty keeps the default latest-stable flow.
if [[ -n "${XUI_UPDATE_TAG}" ]]; then
tag_version="${XUI_UPDATE_TAG}"
echo -e "${green}Using update tag: ${tag_version}${plain}"
else
tag_version=$(${curl_bin} -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" 2> /dev/null | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
if [[ ! -n "$tag_version" ]]; then
_fail "ERROR: Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later"
fi
fi
echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
# x-ui.rc and the unit files must come from the binary's own release; only the
# rolling dev build tracks main. x-ui.sh ships in the archive and needs no GitHub check.
fix(install): fetch x-ui.sh and unit files from the installed release tag (#6391) * fix(install): fetch x-ui.sh and unit files from the installed release tag install.sh and update.sh pin the panel archive to a release tag but always took x-ui.sh, x-ui.rc and the service units from main, so the management script and the binary of one installation came from different commits: the fail2ban templates and setting flags the script writes drift silently against an older binary, two installs of the same tag differ, and a reviewed or digest-pinned installer still runs unreviewed code from main. Use the same ref as the archive, keeping main only for the rolling dev-latest build. The menu's "update menu" and update_shell paths now fetch the script matching the installed version and fall back to main with a visible notice when no script is published for it. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): fall back to main for files a pinned tag does not publish Review follow-ups. install.sh accepts tags down to v2.3.5, but x-ui.rc only exists from v2.8.4 and the split x-ui.service.* files are newer still, so pinning those to the tag made an Alpine install of an old tag 404 after the previous install was already removed. Probe the tag for each file and fall back to main with a notice when it is missing, as the menu already does for x-ui.sh. The fail2ban auto-setup probe also trusted the exit status of 'x-ui setup-fail2ban', but scripts before v3.4.0 have no such subcommand and exit 0 from the usage banner, so the installer reported a setup that never ran. Skip with a notice when the installed script does not know the subcommand. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): refuse a tag that does not publish a needed script Falling back to main reintroduced the binary/script mismatch the tag pinning exists to remove, and it fired at points where install.sh and update.sh have already stopped and removed the previous installation -- so the quiet path was also the one that could not be undone. Probe the tag instead, before anything is touched, for every file that is always fetched from GitHub (x-ui.sh, plus x-ui.rc on Alpine), and abort with the HTTP status when one is missing. The unit files stay unprobed: they are only fetched when the release tarball omits them, so an old tag that ships x-ui.service inside its tarball still installs. Their existing failure message now names the ref it tried. Also tighten the setup-fail2ban probe to the dispatcher's case arm rather than any mention of the string, which also matches a comment. --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-09-03 07:50:53 -07:00
script_ref="${tag_version}"
if [[ "${tag_version}" == "dev-latest" ]]; then
script_ref="main"
fi
# The unit files are only fetched when the release tarball lacks them, so
# they are checked at that point instead of here.
[[ $release == "alpine" ]] && require_repo_files "${script_ref}" "x-ui.rc"
2026-05-04 04:20:24 -07:00
${curl_bin} -fLRo ${xui_folder}-linux-$(arch).tar.gz https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz 2> /dev/null
if [[ $? -ne 0 ]]; then
_fail "ERROR: Failed to download x-ui, please be sure that your server can access GitHub"
fi
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
rm ${xui_folder}-linux-$(arch).tar.gz -f > /dev/null 2>&1
_fail "ERROR: Downloaded x-ui release archive is empty, please be sure that your server can access GitHub"
fi
# Releases publish <asset>.sha256 next to each archive. A mismatch or a
# failed sidecar download aborts the update; only a 404 (releases
# predating the sidecar) is tolerated with a warning.
archive="${xui_folder}-linux-$(arch).tar.gz"
rm -f "${archive}.sha256"
sidecar_code=$(${curl_bin} -sL --retry 3 --retry-delay 3 --connect-timeout 15 --max-time 60 -o "${archive}.sha256" -w '%{http_code}' "https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz.sha256" 2> /dev/null)
if [[ "${sidecar_code}" == "200" ]]; then
expected_sha256=$(awk 'NR == 1 {print $1}' "${archive}.sha256")
actual_sha256=$(sha256sum "${archive}" | awk '{print $1}')
rm -f "${archive}.sha256"
if [[ ! "${expected_sha256}" =~ ^[0-9a-f]{64}$ || "${expected_sha256}" != "${actual_sha256}" ]]; then
rm -f "${archive}"
_fail "ERROR: Checksum mismatch for $(basename "${archive}"): expected ${expected_sha256:-<none>}, got ${actual_sha256}"
fi
echo -e "${green}Checksum verified: ${actual_sha256}${plain}"
elif [[ "${sidecar_code}" == "404" ]]; then
rm -f "${archive}.sha256"
echo -e "${yellow}No checksum published for this release, skipping verification${plain}"
else
rm -f "${archive}.sha256" "${archive}"
_fail "ERROR: Failed to download the checksum for x-ui-linux-$(arch).tar.gz (HTTP ${sidecar_code})"
fi
2026-05-04 04:20:24 -07:00
# Download everything before x-ui stops, because its Xray and any panel egress bridge
# stop with it. Alpine's init script is the only file the archive lacks.
if [[ $release == "alpine" ]]; then
echo -e "${green}Downloading startup unit x-ui.rc...${plain}"
xui_rc_temp="/etc/init.d/x-ui.tmp.$$"
rm -f "${xui_rc_temp}"
${curl_bin} -fLRo "${xui_rc_temp}" "https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.rc" > /dev/null 2>&1
if [[ $? -ne 0 ]]; then
rm -f "${xui_rc_temp}" "${archive}"
_fail "ERROR: Failed to download startup unit x-ui.rc, please be sure that your server can access GitHub"
fi
if [[ ! -s "${xui_rc_temp}" ]]; then
rm -f "${xui_rc_temp}" "${archive}"
_fail "ERROR: Downloaded startup unit x-ui.rc is empty, please be sure that your server can access GitHub"
fi
fi
if [[ -e ${xui_folder}/ ]]; then
echo -e "${green}Stopping x-ui...${plain}"
if [[ $release == "alpine" ]]; then
if [ -f "/etc/init.d/x-ui" ]; then
2026-05-04 04:20:24 -07:00
rc-service x-ui stop > /dev/null 2>&1
rc-update del x-ui > /dev/null 2>&1
echo -e "${green}Removing old service unit version...${plain}"
2026-05-04 04:20:24 -07:00
rm -f /etc/init.d/x-ui > /dev/null 2>&1
else
2026-05-04 04:20:24 -07:00
rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
_fail "ERROR: x-ui service unit not installed."
fi
else
if [ -f "${xui_service}/x-ui.service" ]; then
2026-05-04 04:20:24 -07:00
systemctl stop x-ui > /dev/null 2>&1
systemctl disable x-ui > /dev/null 2>&1
echo -e "${green}Removing old systemd unit version...${plain}"
2026-05-04 04:20:24 -07:00
rm ${xui_service}/x-ui.service -f > /dev/null 2>&1
systemctl daemon-reload > /dev/null 2>&1
else
2026-05-04 04:20:24 -07:00
rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
_fail "ERROR: x-ui systemd unit not installed."
fi
fi
fix(mtproto): reap orphaned mtg, fix SysLog viewer, mtg log visibility, export remark (#5105) (#5107) * fix(logs): render journalctl output in the SysLog viewer The log viewer's parseLogLine only understood the app-log format (2006/01/02 15:04:05 LEVEL - body). With SysLog ticked the backend returns journalctl lines (Mon DD HH:MM:SS host ident[pid]: LEVEL - body), so the parser mistook the journal time for the level and dropped the body, leaving only timestamps. Detect and strip the journald prefix, keep the journal timestamp as the stamp, then parse the real level and body from the remainder. * feat(mtproto): surface mtg output and add status reporting mtg's stdout/stderr was captured by a writer that kept only the last line and showed it nowhere, so the reason a proxy could not reach Telegram was invisible. Stream mtg output line-by-line into the x-ui log, tagged per inbound, so it appears in the panel log viewer and journald. Also fix mangled log lines: logger.Info uses fmt.Sprint, which drops the space between adjacent string operands, producing output like 'inbound3on0.0.0.0:8443'. Switch the affected mtproto calls to the formatted (*f) variants. Add show_mtproto_status to x-ui.sh so 'x-ui status' reports each mtproto inbound's mtg process state and bind address. * fix(logs): parse all journalctl message shapes in SysLog viewer Real journalctl output mixes four message shapes after the 'Mon DD HH:MM:SS host ident[pid]:' prefix: go-logging 'LEVEL - msg' (x-ui/xray), Go std-log with an embedded date (net/http, runtime), telego's '[timestamp] LEVEL msg', and systemd lines. The viewer only understood the first, so std-log and telego lines — which never contain ' - ' — collapsed to a bare timestamp (e.g. the 8s telego 409 spam). Extract the parser into a pure, testable module and teach it the other shapes: strip the redundant Go std-log date, lift the level out of telego brackets, and always keep the message body. Add a unit test covering each shape with real captured lines. * fix(mtproto): reap orphaned mtg sidecars so a stale one can't break new clients On Linux x-ui does not kill its mtg children when it dies (no kill-on-exit, unlike the Windows job object). After a crash, OOM, kill -9, or update, a stale mtg keeps holding the inbound port with an OLD secret, so new clients fail the FakeTLS handshake and get silently domain-fronted to the fakeTLS domain instead of proxied to Telegram (a few MB of traffic, never connects). Sweep orphans at startup: on the first reconcile, before x-ui starts any of its own mtg, scan /proc and SIGKILL any process whose executable is our mtg-<goos>-<goarch> binary. x-ui is the sole owner of mtg, so anything alive then is an orphan. Runs once per process (swept guard), survives the binary-deleted-during-update case via /proc/<pid>/cmdline, and is a no-op on Windows (job object) and other platforms. Also clear stray mtg in update.sh/install.sh after stopping x-ui, anchored to the 'mtg-linux-<arch> run ' invocation so the pattern can't match unrelated command lines (e.g. x-ui.sh's own 'grep mtg-linux'). * fix(logs): drop dead body initializer flagged by eslint no-useless-assignment * fix(mtproto): drop remark fragment from tg://proxy export link The mtproto export link appended the inbound remark as a URL fragment (tg://proxy?server=...&port=...&secret=...#remark). Telegram Desktop rejects a proxy deep link with a trailing fragment as 'This proxy link is invalid', breaking one-click import, and a remark is meaningless for proxy links across clients. Stop adding it in both the panel link (genMtprotoLink) and the subscription service. Fixes #5105. * fix(x-ui.sh): remove unused check_mtproto_status helper show_mtproto_status does its own process check, so check_mtproto_status was dead code. Drop it (per Copilot review on #5107).
2026-06-08 19:01:33 -07:00
# Kill any leftover mtg (MTProto) sidecars. x-ui runs them outside its own
# lifecycle, so on Linux a stale one can survive the stop and keep holding
# an inbound port with an outdated secret, silently breaking new clients.
# The new panel respawns a clean mtg per inbound on next start.
pkill -f 'mtg-linux-[^ ]* run ' > /dev/null 2>&1 || true
Feature/tuic v5 (#6337) * Feat(tuic): Implement native TUIC v5 protocol support via Rust sidecar daemon - Add internal/tuic package for official tuic-server sidecar lifecycle management, configuration generation, and graceful process control - Bridge decrypted TUIC QUIC traffic into loopback Xray SOCKS5 inbounds (63200+id) for traffic accounting, statistics, and routing rules - Implement periodic reconciliation job (cadence @every 10s) and immediate runtime synchronization on inbound/client mutations - Add TUIC inbound & multi-user client settings (UUID + Password authentication) in Web UI with SNI auto-fill and panel certificate loader - Integrate tuic:// subscription links and Clash.Meta (Mihomo) proxy generation for TUIC - Update install.sh to automatically download and install official tuic-server release for x86_64, aarch64, and armv7 - Add full localization for TUIC protocol across all 13 supported languages * Feat(install): Support custom repository and branch in install and update scripts * Ci(release): Enable publish-dev for feature branch and workflow dispatch * Feat(sub): Add TUIC to subscription resolution and client QR config generator - Add 'tuic' to getInboundsBySubId SQL allowlist to resolve TUIC inbounds in subscriptions and sub links - Enhance buildTuicProxy in Clash subscription generator with robust host and credentials resolution - Add tuicConfig.ts to generate standalone Clash/Mihomo YAML configuration - Add dedicated TUIC Config tab in ClientQrModal with QR code and .yaml download button - Add localization keys for TUIC config across all 13 supported languages * Fix(tuic): Exclude TUIC from native Xray inbounds and strip udp_relay_mode from server config - Exclude model.TUIC from native Xray inbounds in GetXrayConfig to prevent Xray startup failure - Remove udp_relay_mode from tuic-server JSON configuration builder - Update install.sh to install tuic-server binary to both xui_folder/bin and /usr/local/bin * Fix(install): Fallback to dev-latest when releases/latest is not present on fork * Feat(tuic): Add real-time online status and LastOnline tracking for TUIC clients - Track client activity by mapping client UUID in tuic-server logs to email - Integrate TUIC active clients into XrayTrafficJob to refresh local online clients - Bump LastOnline timestamp in database and broadcast live online status over WebSocket * Feat(tuic): Implement real-time traffic statistics and live speed reporting for TUIC - Collect precise I/O traffic deltas for tuic-server child processes via /proc/<pid>/io - Aggregate and attribute TUIC traffic deltas per client in tuic Manager - Integrate TUIC traffic deltas into XrayTrafficJob to update database and broadcast live speed * Feat(tuic): Finalize TUIC v5 integration with 1:1 traffic counting and orphan process cleanup - Use exact 1:1 byte delta accounting from /proc/<pid>/io - Add killStrayTuicProcesses to terminate orphan sidecars on panel startup - Fully integrate TUIC with subscriptions, live speed meter, and all 13 locales * Feat(frontend): Polish TUIC UI, support bulk operations, and update translations - Align TUIC inbound certificate form with standard 3X-UI layout (Set Default Cert, Clear) - Remove extra subtitle hint text from TUIC inbound form fields - Support TUIC in client bulk attach/detach and bulk add modals - Add TUIC badge color to client info modal, clients table, and host list - Update password tooltip across all 13 locales to include TUIC - Remove obsolete dead translation keys across all 13 locales * Chore(ci): Finalize TUIC v5 bundling across release workflow, Docker, and scripts * Feat(openapi): Update OpenAPI generator and schemas for TUIC types * Fix(backend): Address core review findings for TUIC types, port checks, and xray bridge * Refactor(traffic): Isolate proc reading with build tags and decouple TUIC metering into TuicJob * Feat(client): Add TuicServer to InboundOption, fix config export and clean share links * Fix(frontend): Register TUIC in multi-user helpers, tracked protocols, and tag derivation * Chore(openapi): Re-generate OpenAPI specification and sync Zod schemas * Chore(scripts): Add Alpine musl binaries, 386 and Windows packaging, and anchor pkill * Fix(review): Remove stale import, correct binary names, switch to musl, and drop unreachable relay gate * Feat(frontend): Show share link in Inbound Info and display UDP tag for TUIC * Docs: Add TUIC v5 configuration guide and link specifications * Docs(tuic): Correct Clash Meta configuration parameter to reduce-rtt * Fix(tuic): Generate client credentials on copy, enforce ID/password validation, and add i386 to DockerInit * Fix(tuic): drop unused relay, fix traffic accounting, and honor host endpoints - Drop unused loopback SOCKS relay and eliminate port collision with AmneziaWG - Correct inbound traffic calculation without double-counting - Drop heuristic client traffic division while retaining online tracking - Support externalProxy host fan-out and conditional parameters in share links - Scope orphan process termination to managed config directory * Fix(tuic): enforce client quotas, decouple Xray restart, and sync openapi schemas - Regenerate OpenAPI, Zod schemas, and TypeScript types without route_through_xray - Populate clientTraffics in TuicJob to enforce client quotas and first-use expiry - Split process I/O delta into up and down in Process.CollectTraffic - Remove SetNeedRestart from updateTuicInbound to prevent Xray session drops - Use InstanceFromInbound for default ALPN and UDP relay mode in tuic:// share links - Support allow_insecure on externalProxy host endpoints without parameter collision * Fix(tuic): attribute client traffic only on single-user inbounds and sync link defaults - Attribute I/O deltas to the client only when the inbound has exactly one configured client, avoiding false billing and disablings on multi-user inbounds - Aggregate client traffic by email in TuicJob so clients on multiple inbounds don't lose deltas - Match frontend genTuicLink defaults for alpn and udp_relay_mode with backend subscription links * Fix(tuic): gate client traffic by total sidecar clients and require client email * Fix(tuic): enforce inbound-only traffic limits and disable client totalGB * fix(tuic): restore delayed start, remove client totalGB rejection, and document linux-only limits * fix(tuic): anchor pkill, fix io baseline/split, escape yaml, and deduplicate start errors * fix(tuic): prevent traffic double-counting, ensure info log level for delayed start, and broaden pkill matching * fix(tuic): address review round 11 findings - internal/sub/json_service: skip tuic protocol in json subscription to prevent direct routing leak - internal/sub/clash_service: honor externalProxy/host row allowInsecure, sni, and alpn in buildTuicProxy - internal/web/runtime: decouple tuic inbound add/delete from xray restart - internal/tuic/config: restore user log-level options (warn, error) without forced info clamp - frontend/src/lib/xray/inbound-link: fix duplicate remark suffix and apply externalProxy TLS overrides - frontend/src/schemas/protocols/stream/external-proxy: propagate allowInsecure through host mapping - tests: add coverage for json sub skip, clash proxy overrides, and link generation * fix(tuic): meter inbound traffic through a UDP relay and bracket IPv6 binds Review repairs on the TUIC v5 sidecar integration: - Inbound traffic was read from the sidecar's /proc/<pid>/io rchar, but the kernel only counts read()/write() there and tuic-server moves its sockets with recvfrom/recvmmsg/sendmmsg/sendto, so an inbound's up/down stayed at 0 forever and inbound total limits never tripped (measured: 12 MiB relayed, rchar delta 0). The panel now owns the inbound's public UDP port with a small relay and runs tuic-server behind it on a loopback port, counting up/down exactly on every OS. tuic-server therefore logs 127.0.0.1 as every client's address; per-client attribution stays unsupported since QUIC is opaque. - Instance.BindTo formatted an IPv6 listen address as ":::8443", which tuic-server rejects with "invalid socket address syntax", so an inbound listening on "::" or any IPv6 literal never started. It now uses net.JoinHostPort; IPv4 output is unchanged. - The log level is passed to the sidecar as chosen. Online status, last-online and delayed start are read from its Info lines, so the Log Level field now says that Warn and Error switch them off for the inbound, and the docs say the same. - Drop two frontend tests that only exercised a getter and a set lookup, and strip the trailing blank line that made gofumpt fail on two of the new Go test files. * fix(tuic): harden tag updates, runtime routing, and relay stability --------- Co-authored-by: poise52 <equipoise52@gmail.com> Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-09-12 01:15:48 -07:00
pkill -f 'tuic-server.*-c .*bin/tuic/tuic_[0-9]+\.json' > /dev/null 2>&1 || true
echo -e "${green}Removing old x-ui version...${plain}"
2026-05-04 04:20:24 -07:00
rm ${xui_folder} -f > /dev/null 2>&1
rm ${xui_folder}/x-ui.service -f > /dev/null 2>&1
rm ${xui_folder}/x-ui.service.debian -f > /dev/null 2>&1
rm ${xui_folder}/x-ui.service.arch -f > /dev/null 2>&1
rm ${xui_folder}/x-ui.service.rhel -f > /dev/null 2>&1
rm ${xui_folder}/x-ui -f > /dev/null 2>&1
rm ${xui_folder}/x-ui.sh -f > /dev/null 2>&1
echo -e "${green}Removing old mtg version...${plain}"
rm ${xui_folder}/bin/mtg-linux-$(arch) -f > /dev/null 2>&1
echo -e "${green}Removing old xray version...${plain}"
rm ${xui_folder}/bin/xray-linux-$(arch) -f > /dev/null 2>&1
echo -e "${green}Removing old README and LICENSE file...${plain}"
2026-05-04 04:20:24 -07:00
rm ${xui_folder}/bin/README.md -f > /dev/null 2>&1
rm ${xui_folder}/bin/LICENSE -f > /dev/null 2>&1
feat(tuic): implement native in-process Go TUIC v5 server (#6577) * feat(tuic): implement native in-process Go TUIC v5 server - Implement native TUIC v5 protocol server on pure Go using quic-go - Bridge decrypted TCP/UDP traffic into Xray-core via loopback SOCKS5 inbound - Support full Xray routing rules (geosite/geoip) and cascading outbounds - Implement atomic per-client traffic accounting with TotalGB and ExpiryTime - Add automatic legacy cleanup for older Rust tuic-server binaries, configs, and orphaned processes - Eliminate external Rust tuic-server downloads from install/CI scripts * fix(tuic): address traffic accounting, client reload, and socket lifecycle issues * fix(service): update checkTuicSocksReverseConflict to use bindAddr for listenOverlaps * fix(tuic): resolve traffic double-accounting, UDP fragmentation, and socket lifecycle issues * feat(tuic): complete native Go integration and address audit findings - Integrate an isolated QUIC fork pinned to a specific commit - Preserve original QUIC dependencies for Xray, Hysteria and Gin - Apply BBR, CUBIC and Reno to server connections and exported client profiles - Bridge Xray BBR with correct monotonic time and congestion type conversions - Handle congestion sender recreation after PMTU changes - Update congestion control for new connections without restarting the listener - Preserve existing connections and their selected congestion controller - Apply per-inbound log levels through the shared panel logger - Add lifecycle, authentication and TCP/UDP relay events without exposing secrets - Rate-limit repeated authentication and relay warnings - Support native and QUIC UDP relay modes on the same listener - Recover UDP associations after relay worker failures - Fix TCP relay cancellation, idle shutdown and half-close handling - Close active sessions when client credentials are revoked or disabled - Track traffic by immutable client statistics IDs across email and UUID changes - Prevent ambiguous accounting and duplicate UUIDs within TUIC inbounds - Persist pending traffic in a durable shutdown journal - Replay journal batches transactionally without duplicate accounting - Report server shutdown failures through the shared logger - Preserve legacy flat and nested TUIC settings compatibility - Normalize congestion controller values consistently across backend and frontend - Preserve controller, UDP mode and SNI in client links and subscriptions - Separate client profile options from server settings in the TUIC form - Keep certificate path autofill explicit when changing client SNI - Align UDP packet size validation with protocol limits - Simplify and localize TUIC field hints and certificate autofill messages - Add controller, TCP/UDP, logging and live settings update tests - Add accounting identity, journal replay and shutdown regression tests - Add relay recovery, session revocation and legacy frontend form tests * fix(service): alias the TUIC duplicate-UUID subquery for PostgreSQL < 16 syncInboundClients runs a COUNT(*) FROM (subquery) for every client sync, whatever the protocol. PostgreSQL before 16 rejects a FROM subquery with no alias, so on the distro PostgreSQL install.sh provisions (14 on Ubuntu 22.04, 15 on Debian 12) every client add or edit failed with SQLSTATE 42601. Reproduced against postgres:15 with the new env-gated test. * fix(database): create tuic_traffic_receipts through the model migration AddTuicTrafficBatch issued CREATE TABLE IF NOT EXISTS at runtime, a schema change outside db.go. The table was invisible to allModels and migrationModels, so x-ui migrate-db dropped the receipts and a retained journal could be counted twice after a SQLite to PostgreSQL move. It is now a GORM model in both lists, and the insert uses OnConflict DoNothing. * chore(tuic): skip the ICMP-dependent relay test on Windows, drop dead collectors Go disables SIO_UDP_CONNRESET on Windows, so a dead UDP bridge never fails a read there and TestAudit3UDPAssociationMustRecoverAfterBridgeReadFailure was red on every Windows run. Server.CollectTotalTraffic and Manager.CollectTraffic had no caller. * refactor(tuic): serve TUIC on apernet/quic-go instead of a personal fork The native server depended on github.com/poise52/quic-go, a personal fork of apernet/quic-go patched only to pick the congestion controller before the handshake. That put a second QUIC/TLS stack in the binary that no upstream security fix reaches. apernet/quic-go is already in the graph through xray-core and exposes SetCongestionControl, so BBR is now installed on each accepted connection with Xray's own congestion.UseBBR; the cross-module BBR adapter is gone. apernet ships New Reno as its only built-in sender, so a cubic setting is served as new_reno server-side (clients still get cubic in their profile). The test inspectors now read the sender under congestionMutex, which the post-handshake install writes under. Linux loopback, single stream through Xray: 2428 -> 3383 Mbit/s (bbr). --------- Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-10-02 17:56:02 -07:00
rm ${xui_folder}/bin/tuic-server -f > /dev/null 2>&1
rm ${xui_folder}/bin/tuic -rf > /dev/null 2>&1
else
2026-05-04 04:20:24 -07:00
rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
_fail "ERROR: x-ui not installed."
fi
2026-05-04 04:20:24 -07:00
echo -e "${green}Installing new x-ui version...${plain}"
2026-05-04 04:20:24 -07:00
tar zxvf x-ui-linux-$(arch).tar.gz > /dev/null 2>&1
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
if [[ $? -ne 0 ]]; then
rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
_fail "ERROR: Failed to extract the x-ui release archive -- the previous installation has already been removed, so the panel will not start until this is fixed; try running the update again"
fi
2026-05-04 04:20:24 -07:00
rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
cd x-ui > /dev/null 2>&1
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
if [[ $? -ne 0 || ! -s x-ui ]]; then
_fail "ERROR: Extracted x-ui archive is missing the x-ui binary -- the previous installation has already been removed, so the panel will not start until this is fixed; try running the update again"
fi
2026-05-04 04:20:24 -07:00
chmod +x x-ui > /dev/null 2>&1
# Check the system's architecture and rename the file accordingly.
# The panel binary maps GOARCH=arm to "arm32" (internal/xray/process.go),
# so the Xray binary must be named xray-linux-arm32; mtg keeps plain "arm".
if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
mv bin/xray-linux-$(arch) bin/xray-linux-arm32 > /dev/null 2>&1
chmod +x bin/xray-linux-arm32 > /dev/null 2>&1
if [[ -f bin/mtg-linux-$(arch) ]]; then
mv bin/mtg-linux-$(arch) bin/mtg-linux-arm > /dev/null 2>&1
chmod +x bin/mtg-linux-arm > /dev/null 2>&1
fi
fi
2026-05-04 04:20:24 -07:00
chmod +x x-ui bin/xray-linux-$(arch) > /dev/null 2>&1
if [[ -f bin/mtg-linux-arm ]]; then
chmod +x bin/mtg-linux-arm > /dev/null 2>&1
elif [[ -f bin/mtg-linux-$(arch) ]]; then
chmod +x bin/mtg-linux-$(arch) > /dev/null 2>&1
fi
2026-05-04 04:20:24 -07:00
# The archive's x-ui.sh is built from the same commit as the binary.
echo -e "${green}Installing x-ui.sh script...${plain}"
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
local xui_script_temp="/usr/bin/x-ui-temp.$$"
if ! cp -f x-ui.sh "${xui_script_temp}" || ! mv -f "${xui_script_temp}" /usr/bin/x-ui; then
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
rm -f "${xui_script_temp}"
_fail "ERROR: Failed to install x-ui.sh script"
fi
2026-05-04 04:20:24 -07:00
chmod +x ${xui_folder}/x-ui.sh > /dev/null 2>&1
chmod +x /usr/bin/x-ui > /dev/null 2>&1
mkdir -p /var/log/x-ui > /dev/null 2>&1
echo -e "${green}Changing owner...${plain}"
2026-05-04 04:20:24 -07:00
chown -R root:root ${xui_folder} > /dev/null 2>&1
if [ -f "${xui_folder}/bin/config.json" ]; then
echo -e "${green}Changing on config file permissions...${plain}"
2026-05-04 04:20:24 -07:00
chmod 640 ${xui_folder}/bin/config.json > /dev/null 2>&1
fi
2026-05-04 04:20:24 -07:00
# Finish the schema/data migrations before the service starts, so the service and
# config_after_update's CLI calls never run them on the same database at once (#6728).
echo -e "${green}Migrating database...${plain}"
"${xui_folder}/x-ui" migrate
if [[ $release == "alpine" ]]; then
echo -e "${green}Installing startup unit x-ui.rc...${plain}"
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
mv -f "${xui_rc_temp}" /etc/init.d/x-ui
if [[ $? -ne 0 ]]; then
rm -f "${xui_rc_temp}"
_fail "ERROR: Failed to install startup unit x-ui.rc"
fi
2026-05-04 04:20:24 -07:00
chmod +x /etc/init.d/x-ui > /dev/null 2>&1
chown root:root /etc/init.d/x-ui > /dev/null 2>&1
rc-update add x-ui > /dev/null 2>&1
rc-service x-ui start > /dev/null 2>&1
else
if [ -f "x-ui.service" ]; then
echo -e "${green}Installing systemd unit...${plain}"
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
if ! _install_xui_service_unit "x-ui.service" "false"; then
2026-01-02 22:27:39 -08:00
echo -e "${red}Failed to copy x-ui.service${plain}"
exit 1
fi
else
2026-01-02 22:27:39 -08:00
service_installed=false
case "${release}" in
ubuntu | debian | armbian)
2026-01-02 22:27:39 -08:00
if [ -f "x-ui.service.debian" ]; then
echo -e "${green}Installing debian-like systemd unit...${plain}"
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
if _install_xui_service_unit "x-ui.service.debian" "false"; then
2026-01-02 22:27:39 -08:00
service_installed=true
fi
fi
2026-05-04 04:20:24 -07:00
;;
arch | manjaro | parch)
if [ -f "x-ui.service.arch" ]; then
echo -e "${green}Installing arch-like systemd unit...${plain}"
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
if _install_xui_service_unit "x-ui.service.arch" "false"; then
service_installed=true
fi
fi
2026-05-04 04:20:24 -07:00
;;
*)
2026-01-02 22:27:39 -08:00
if [ -f "x-ui.service.rhel" ]; then
echo -e "${green}Installing rhel-like systemd unit...${plain}"
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
if _install_xui_service_unit "x-ui.service.rhel" "false"; then
2026-01-02 22:27:39 -08:00
service_installed=true
fi
fi
2026-05-04 04:20:24 -07:00
;;
esac
2026-05-04 04:20:24 -07:00
2026-01-02 22:27:39 -08:00
# If service file not found in tar.gz, download from GitHub
if [ "$service_installed" = false ]; then
echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
case "${release}" in
ubuntu | debian | armbian)
fix(install): fetch x-ui.sh and unit files from the installed release tag (#6391) * fix(install): fetch x-ui.sh and unit files from the installed release tag install.sh and update.sh pin the panel archive to a release tag but always took x-ui.sh, x-ui.rc and the service units from main, so the management script and the binary of one installation came from different commits: the fail2ban templates and setting flags the script writes drift silently against an older binary, two installs of the same tag differ, and a reviewed or digest-pinned installer still runs unreviewed code from main. Use the same ref as the archive, keeping main only for the rolling dev-latest build. The menu's "update menu" and update_shell paths now fetch the script matching the installed version and fall back to main with a visible notice when no script is published for it. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): fall back to main for files a pinned tag does not publish Review follow-ups. install.sh accepts tags down to v2.3.5, but x-ui.rc only exists from v2.8.4 and the split x-ui.service.* files are newer still, so pinning those to the tag made an Alpine install of an old tag 404 after the previous install was already removed. Probe the tag for each file and fall back to main with a notice when it is missing, as the menu already does for x-ui.sh. The fail2ban auto-setup probe also trusted the exit status of 'x-ui setup-fail2ban', but scripts before v3.4.0 have no such subcommand and exit 0 from the usage banner, so the installer reported a setup that never ran. Skip with a notice when the installed script does not know the subcommand. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): refuse a tag that does not publish a needed script Falling back to main reintroduced the binary/script mismatch the tag pinning exists to remove, and it fired at points where install.sh and update.sh have already stopped and removed the previous installation -- so the quiet path was also the one that could not be undone. Probe the tag instead, before anything is touched, for every file that is always fetched from GitHub (x-ui.sh, plus x-ui.rc on Alpine), and abort with the HTTP status when one is missing. The unit files stay unprobed: they are only fetched when the release tarball omits them, so an old tag that ships x-ui.service inside its tarball still installs. Their existing failure message now names the ref it tried. Also tighten the setup-fail2ban probe to the dispatcher's case arm rather than any mention of the string, which also matches a comment. --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-09-03 07:50:53 -07:00
service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.debian"
2026-05-04 04:20:24 -07:00
;;
arch | manjaro | parch)
fix(install): fetch x-ui.sh and unit files from the installed release tag (#6391) * fix(install): fetch x-ui.sh and unit files from the installed release tag install.sh and update.sh pin the panel archive to a release tag but always took x-ui.sh, x-ui.rc and the service units from main, so the management script and the binary of one installation came from different commits: the fail2ban templates and setting flags the script writes drift silently against an older binary, two installs of the same tag differ, and a reviewed or digest-pinned installer still runs unreviewed code from main. Use the same ref as the archive, keeping main only for the rolling dev-latest build. The menu's "update menu" and update_shell paths now fetch the script matching the installed version and fall back to main with a visible notice when no script is published for it. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): fall back to main for files a pinned tag does not publish Review follow-ups. install.sh accepts tags down to v2.3.5, but x-ui.rc only exists from v2.8.4 and the split x-ui.service.* files are newer still, so pinning those to the tag made an Alpine install of an old tag 404 after the previous install was already removed. Probe the tag for each file and fall back to main with a notice when it is missing, as the menu already does for x-ui.sh. The fail2ban auto-setup probe also trusted the exit status of 'x-ui setup-fail2ban', but scripts before v3.4.0 have no such subcommand and exit 0 from the usage banner, so the installer reported a setup that never ran. Skip with a notice when the installed script does not know the subcommand. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): refuse a tag that does not publish a needed script Falling back to main reintroduced the binary/script mismatch the tag pinning exists to remove, and it fired at points where install.sh and update.sh have already stopped and removed the previous installation -- so the quiet path was also the one that could not be undone. Probe the tag instead, before anything is touched, for every file that is always fetched from GitHub (x-ui.sh, plus x-ui.rc on Alpine), and abort with the HTTP status when one is missing. The unit files stay unprobed: they are only fetched when the release tarball omits them, so an old tag that ships x-ui.service inside its tarball still installs. Their existing failure message now names the ref it tried. Also tighten the setup-fail2ban probe to the dispatcher's case arm rather than any mention of the string, which also matches a comment. --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-09-03 07:50:53 -07:00
service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.arch"
2026-05-04 04:20:24 -07:00
;;
2026-01-02 22:27:39 -08:00
*)
fix(install): fetch x-ui.sh and unit files from the installed release tag (#6391) * fix(install): fetch x-ui.sh and unit files from the installed release tag install.sh and update.sh pin the panel archive to a release tag but always took x-ui.sh, x-ui.rc and the service units from main, so the management script and the binary of one installation came from different commits: the fail2ban templates and setting flags the script writes drift silently against an older binary, two installs of the same tag differ, and a reviewed or digest-pinned installer still runs unreviewed code from main. Use the same ref as the archive, keeping main only for the rolling dev-latest build. The menu's "update menu" and update_shell paths now fetch the script matching the installed version and fall back to main with a visible notice when no script is published for it. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): fall back to main for files a pinned tag does not publish Review follow-ups. install.sh accepts tags down to v2.3.5, but x-ui.rc only exists from v2.8.4 and the split x-ui.service.* files are newer still, so pinning those to the tag made an Alpine install of an old tag 404 after the previous install was already removed. Probe the tag for each file and fall back to main with a notice when it is missing, as the menu already does for x-ui.sh. The fail2ban auto-setup probe also trusted the exit status of 'x-ui setup-fail2ban', but scripts before v3.4.0 have no such subcommand and exit 0 from the usage banner, so the installer reported a setup that never ran. Skip with a notice when the installed script does not know the subcommand. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): refuse a tag that does not publish a needed script Falling back to main reintroduced the binary/script mismatch the tag pinning exists to remove, and it fired at points where install.sh and update.sh have already stopped and removed the previous installation -- so the quiet path was also the one that could not be undone. Probe the tag instead, before anything is touched, for every file that is always fetched from GitHub (x-ui.sh, plus x-ui.rc on Alpine), and abort with the HTTP status when one is missing. The unit files stay unprobed: they are only fetched when the release tarball omits them, so an old tag that ships x-ui.service inside its tarball still installs. Their existing failure message now names the ref it tried. Also tighten the setup-fail2ban probe to the dispatcher's case arm rather than any mention of the string, which also matches a comment. --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-09-03 07:50:53 -07:00
service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.rhel"
2026-05-04 04:20:24 -07:00
;;
2026-01-02 22:27:39 -08:00
esac
2026-05-04 04:20:24 -07:00
fix: make all self-managed file downloads/installs atomic, with real completion status (#5711) * fix(script): download the live x-ui.sh script atomically before replacing it update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same inode a currently-running x-ui process may still be reading from. A network hiccup or slow write during that overwrite leaves a half-old/half-new script on disk, which then fails with bogus syntax errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into place instead, matching the atomic pattern install.sh already uses. Also fixes update_menu() checking chmod's exit code instead of curl's, which meant a failed download could still report "Update successful." * fix(script): close remaining gaps in the atomic script-update path Code review of the previous commit found the atomic mv fix was itself incomplete: - None of the mv -f calls checked their exit status, so a failed move fell through to chmod and "success" messaging while /usr/bin/x-ui stayed on the old file. - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z got a 304, nothing to do" from "a stale temp file survived an earlier crashed run" -- the latter could get moved into place with no freshness check. - update_menu(), update_shell(), and update_x-ui() all hardcoded the same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a cron auto-update racing an interactive menu update) could collide. - update.sh's update_x-ui() was missing the non-empty-file guard update_shell() already had. x-ui.sh's update_menu() and update_shell() now share a replace_xui_script() helper that uses a PID-suffixed temp path (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and checks the exit status of curl, the non-empty test, and mv before treating the update as successful. update.sh's update_x-ui() gets the same sequence inlined (it's fetched as a standalone script and can't call x-ui.sh's function), closing the missing-guard gap and using its own unique temp path. * fix(script,panel): harden the remaining self-update download paths install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two already-fixed scripts had: no exit-status check on mv, and a fixed temp name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it its own PID-suffixed temp path, an empty-file guard, and an mv exit-status check, matching the pattern used there. Audited the web dashboard's Go-native updater (panel.go) for the same bug class: it already uses os.CreateTemp for a genuinely unique temp file and cleans up via both a deferred Remove and a shell EXIT trap, so it was never exposed to the fixed-path race. It was missing a check for a zero-byte download (a 200 OK with an empty body would chmod +x and exec an empty script) -- added that alongside the existing size cap. Not addressed here: once startUpdate()'s child process starts, the Go service releases it and returns success immediately. If update.sh fails partway through, the still-running old panel keeps answering /status, so the frontend's poll can report success with no update having happened. Fixing that needs update.sh to signal completion status back and the frontend to check it -- a separate follow-up. * feat(panel): report real completion status for the web self-update Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once startUpdate() launches update.sh detached, the Go service had no way to learn whether it actually succeeded. If update.sh failed partway (network drop, disk full, permission denied), the still-running old panel kept answering /status, so the frontend's poll reported success with nothing having changed. update.sh now writes its outcome to a small JSON status file (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which covers every exit path in the script -- including the two bare `exit 1` call sites that don't go through the existing _fail() helper. The Go service generates a run ID before launching, passes it and the status path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a new GET /panel/api/server/getUpdateStatus endpoint reports it back. The frontend now polls that instead of blindly trusting HTTP reachability, and shows a distinct error or "couldn't confirm" message instead of silently reloading into a false success. Adversarial review of this surfaced three more issues, fixed here: - No lock stopped two concurrent /updatePanel calls from launching two update.sh runs that would race each other on the actual update work (tar extraction, service unit swap). Added an in-memory guard with a 5-minute self-expiring window, so a run that never reaches a terminal state doesn't lock out retries indefinitely. - XUI_UPDATE_RUN_ID is read from the environment and was interpolated unquoted into the status JSON; a malformed value would produce invalid JSON. Now validated as digits-only before use. - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON number it would lose precision in JavaScript (past Number.MAX_SAFE_INTEGER), letting two different runs round to the same value on the wire and defeat the whole comparison. It's now a decimal string end to end (Go, the status file, and the generated frontend type). install.sh's equivalent temp-file/mv path and the Go-native downloadPanelUpdater() path were audited for the same bug classes during this work; findings from that audit were addressed separately. * fix(panel): release the update lock as soon as the run finishes An exhaustive multi-angle review of the whole branch (12 finder angles, 3-vote adversarial verification, a fresh-eyes sweep) surfaced a real bug in the concurrency guard added in the previous commit, plus several smaller issues; this fixes what's actionable now. The bug: acquireUpdateSlot only ever released on the 5-minute stale timeout or if launching itself failed. If update.sh launched fine but failed fast (bad GitHub API response, "x-ui not installed", any of its early exit paths), the status file correctly reported "failed" within seconds, but a retry was still rejected with "a panel update is already in progress" for up to 5 more minutes -- the guard never looked at the very status file this branch built to know a run was done. It now tracks which run ID currently holds the slot and checks that run's own status before falling back to the timeout, so a fast failure clears the way for an immediate retry. Added a regression test for this, plus one confirming a stale, unrelated runID can't be mistaken for the current run finishing. Also: - Added a genuinely concurrent test for the guard: 200 goroutines racing acquireUpdateSlot, asserting exactly one wins. The previous tests only ever called it from one goroutine, so they gave no signal if the mutex's check-then-set were silently broken -- verified this by temporarily removing the lock and confirming the old tests still passed while the new one caught it immediately under -race. - Removed the redundant upfront "pending" status write: GetUpdateStatus already defaults a missing/stale file to pending, and the frontend matches by run ID regardless, so the write changed no observable behavior. Deleted writeUpdateStatus entirely since that was its only caller. - Renamed replace_xui_script()'s unclear "conditional" parameter to use_if_modified_since, matching what it actually controls. - Added HTTP-level tests for the new getUpdateStatus endpoint, including a regression test that the runId wire format is a JSON string (decoding into a Go string field fails outright if it were ever a bare number). updatePanel's actual launch path is not covered: on a Linux test runner it would make a real network call and could exec a real update.sh, so only its non-Linux guard path is safely testable without mocking. Not fixed here, tracked separately: the same unsafe-overwrite pattern this branch eliminated for /usr/bin/x-ui is still present for the systemd unit file install in update.sh and install.sh (lower severity since systemd only reads it on daemon-reload, not continuously); and startUpdate's systemd-run-vs-detached-fallback branching has no test coverage since testing it safely needs dependency injection this fix doesn't warrant bundling in. * fix(script): make systemd unit file installation atomic Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every site that lands the systemd unit at ${xui_service}/x-ui.service -- copying it from the extracted release tarball, or falling back to a GitHub download per distro family -- wrote straight onto the live path via cp/curl, no temp file, no verification. A network drop mid-download or an interrupted cp leaves the unit file truncated; systemd then fails to parse it on the next daemon-reload/start, leaving the panel unable to come up until an operator manually re-copies a good unit file. Lower severity than the /usr/bin/x-ui case (systemd only reads this file on demand at daemon-reload time, not continuously the way bash interprets a running script line by line), but it's the identical gap, just left uncovered when that fix landed. Added a small shared helper in both update.sh and install.sh -- _install_xui_service_unit() -- covering both source types (cp from the tarball, curl from GitHub): write to a PID-suffixed temp file, verify the copy/download succeeded and the result is non-empty, then mv -f into place and check that exit status too, matching the pattern already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl fallback in each file now go through it; verified no other site writes new content to the unit path (the remaining ${xui_service} references are a pre-install existence check, an rm during old-version cleanup, and the chown/chmod that already ran after the file is safely in place -- none of those need atomicity). Verified with bash -n on both files, plus a standalone scratch test exercising cp-success, cp-with-missing-source, cp-with-empty-source, and curl-failure paths: on every failure the previous, good unit file content is left untouched and no temp file is leaked behind. * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment A final maximum-rigor review of the whole PR (12 finder angles including a repo-wide sweep for any remaining instance of the bug class this PR fixes) found two more real issues: - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare `curl -fLRo` straight onto the live path in both update.sh and install.sh -- the exact same unguarded-overwrite pattern already fixed for /usr/bin/x-ui and the systemd unit file, just left uncovered on the OpenRC side. A network drop mid-download truncates the live init script; OpenRC then fails to source/execute it on the next start, leaving the panel unable to come up. Fixed with the same temp-file + non-empty check + mv -f (with its own exit-status check) pattern used everywhere else in this PR. Verified with bash -n and a standalone scratch-script test covering success, empty-download, and destination-preserved-on-failure paths. - internal/web/service/panel/panel_test.go had one line-level `//` comment on a call site, which the root CLAUDE.md's hard rule ("No // line comments in committed Go/TS... rename instead of annotating") explicitly prohibits. The comment duplicated context already stated in the test's own doc comment two lines above, so it's simply removed rather than reworded. Also flagged, deliberately not bundled here since it's a different subsystem: x-ui.sh's update_geofiles() downloads Xray's live geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked as its own follow-up. * fix(script): make geo-data file downloads atomic Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the Alpine init script fixed in prior PRs: update_geofiles() downloaded Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl writing straight onto the exact path Xray reads at runtime (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp file, no verification. The existing check only inspected the reported HTTP status via -w '%{http_code}', not file integrity, so a network drop mid-download could leave a truncated .dat file on disk that passes the status check. Xray then fails to parse it on the next restart/reload, breaking any routing rules that reference geoip:/ geosite:. The -z conditional-GET usage needed care here: the original code pointed both -z and -o at the same live path. Fixed by pointing -z at the live file (to keep the "already current" freshness check) while -o writes to a PID-suffixed temp file, matching the pattern already proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP server that a 304 response leaves the temp file untouched/nonexistent (so the existing "already up to date" branch still works unchanged), and added a non-empty check plus a checked mv -f before treating a download as installed. Verified with bash -n and an end-to-end scratch test against a local server covering: fresh download, 304-not-modified, empty response body, and a 404 -- confirming a failure at any stage leaves the previous good .dat file completely untouched and no temp file behind. * fix(script): verify the release tarball extraction, not just the download The final maximum-rigor review found the most significant remaining gap in this whole effort: update.sh and install.sh check the tarball download's exit status, but never check tar's exit status, and never verify the extracted x-ui binary actually exists before continuing. Worse, by the time extraction runs, the previous installation has already been stopped and deleted -- there's no rollback. A truncated download that still passes curl's own check, or a tar failure (disk full, killed process), left the panel silently in a broken half-state: chmod/config/service-install all continued to run against a missing or empty binary, with no error surfaced anywhere. This is the same bug class as everything else in this PR (unverified write to a path something then depends on), just for the tarball itself rather than a single file -- and it also covers the geo-data files this PR already fixed once for the interactive/cron path, since they ship inside this same tarball on every panel update. Added: a non-empty check on the downloaded archive (both files, both install.sh call sites) and a check that tar succeeded and produced a non-empty x-ui binary before proceeding, failing loudly with a message that explicitly says the previous install is already gone, since silently continuing here is worse than anywhere else in this PR. This doesn't make the multi-file extraction fully atomic (that would mean extracting to a temp directory and atomically swapping the whole install tree into place, a materially larger restructuring than anything else in this PR) -- but it closes the "fails silently, user discovers it days later when Xray can't start" gap, which was the actual reported problem this whole effort traces back to. Also fixed, all much smaller: - replace_xui_script() in x-ui.sh implicitly returned chmod's exit status instead of success, so a successful atomic install could be reported as failed if chmod transiently failed after the mv already landed the new script. Added an explicit `return 0`. - update_geofiles() had no default case branch; an unrecognized argument would silently reuse whatever dat_files/dat_source values a previous call left in the un-scoped globals instead of failing. Currently unreachable (all three call sites pass fixed literals) but cheap, defensive, and worth having. - internal/web/controller/server.go's updatePanel has one branch (an unparseable "dev" form value) that's both untested and safe to test on any platform, since it's rejected before any real exec/network call. Added the missing test case. Verified: bash -n on all three scripts; an empirical scratch test covering an empty downloaded archive, a corrupt (non-gzip) archive, and a successfully-extracting-but-empty archive, confirming each is caught before the script proceeds; full go build/vet/test -race across the whole module; frontend generation confirmed still in sync. * fix(panel): base the update-slot staleness fallback on process liveness Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711). Blocking finding: acquireUpdateSlot's staleness fallback freed the update slot purely on elapsed wall-clock time (5 minutes), with no check on whether the update.sh process it launched was actually still running. update.sh runs install_base() (apt-get/dnf/pacman update and install) before update_x-ui even starts, plus several GitHub downloads (release tarball, x-ui.sh, and possibly a service unit or x-ui.rc) -- on a slow or throttled host, a small VPS being the typical deployment target for this project, that alone can plausibly exceed 5 minutes with nothing wrong. A second /updatePanel call arriving in that window (an admin retrying after the frontend's 90s poll times out, or overlapping master-node bulk-update calls) would launch a second update.sh, racing the exact rm/tar/mv/systemctl sequence this whole PR exists to make safe. Fixed by recording the launched process's PID (detached-fallback path only; the systemd-run path's own process has already exited by the time startUpdate returns, so it never learns update.sh's real PID) and checking it via the standard POSIX kill(pid, 0) liveness probe before treating a run as stale, following the existing panel_unix.go / panel_other.go platform-split pattern already used for setDetachedProcess. A confirmed-alive process now keeps the slot held past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline for the systemd-run path, which still has no way to check liveness directly). updateHardCeiling (2 hours) is an absolute backstop so a genuinely wedged run can never lock out retries permanently even on the PID-tracked path. Added two regression tests exercising the new logic (gated to Linux, since processAlive is a no-op stub elsewhere): a live PID keeps the slot held past the stale window, and the hard ceiling overrides liveness. Traced both by hand against the new acquireUpdateSlot logic; could not execute-verify processAlive itself on this Windows dev machine (no WSL distro installed, and installing one felt disproportionate to validate kill(pid, 0), an extremely well-established POSIX primitive), but cross-compiled clean for linux/amd64 and this repo's CI runs the real test suite on Linux. Also fixed, both suggestions from the same review: - install.sh: two failure paths right after tarball extraction were exiting without cleaning up the already-downloaded x-ui.sh temp file (xui_script_temp), leaving it behind. Every other new failure branch in this PR removes its temp file before exiting; these two now do too. - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry did not reflect that a successful response now carries an obj with runId. Added an inline response example matching the existing pattern used for other ad hoc (non-schema-backed) responses like getWebCertFiles. Verified: go build/vet clean on both windows (native) and a linux/amd64 cross-compile; full go test ./... clean; go test -race on the panel and controller packages; bash -n on all three shell scripts; npm run gen confirms the openapi.json diff is exactly the new response example with no stray changes to src/generated; TestAPIRoutesDocumented still passes.
2026-07-02 09:19:33 -07:00
if ! _install_xui_service_unit "$service_unit_url" "true"; then
fix(install): fetch x-ui.sh and unit files from the installed release tag (#6391) * fix(install): fetch x-ui.sh and unit files from the installed release tag install.sh and update.sh pin the panel archive to a release tag but always took x-ui.sh, x-ui.rc and the service units from main, so the management script and the binary of one installation came from different commits: the fail2ban templates and setting flags the script writes drift silently against an older binary, two installs of the same tag differ, and a reviewed or digest-pinned installer still runs unreviewed code from main. Use the same ref as the archive, keeping main only for the rolling dev-latest build. The menu's "update menu" and update_shell paths now fetch the script matching the installed version and fall back to main with a visible notice when no script is published for it. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): fall back to main for files a pinned tag does not publish Review follow-ups. install.sh accepts tags down to v2.3.5, but x-ui.rc only exists from v2.8.4 and the split x-ui.service.* files are newer still, so pinning those to the tag made an Alpine install of an old tag 404 after the previous install was already removed. Probe the tag for each file and fall back to main with a notice when it is missing, as the menu already does for x-ui.sh. The fail2ban auto-setup probe also trusted the exit status of 'x-ui setup-fail2ban', but scripts before v3.4.0 have no such subcommand and exit 0 from the usage banner, so the installer reported a setup that never ran. Skip with a notice when the installed script does not know the subcommand. Assisted-by: Claude Code:claude-fable-5-1 * fix(install): refuse a tag that does not publish a needed script Falling back to main reintroduced the binary/script mismatch the tag pinning exists to remove, and it fired at points where install.sh and update.sh have already stopped and removed the previous installation -- so the quiet path was also the one that could not be undone. Probe the tag instead, before anything is touched, for every file that is always fetched from GitHub (x-ui.sh, plus x-ui.rc on Alpine), and abort with the HTTP status when one is missing. The unit files stay unprobed: they are only fetched when the release tarball omits them, so an old tag that ships x-ui.service inside its tarball still installs. Their existing failure message now names the ref it tried. Also tighten the setup-fail2ban probe to the dispatcher's case arm rather than any mention of the string, which also matches a comment. --------- Co-authored-by: Claude <noreply@anthropic.com>
2026-09-03 07:50:53 -07:00
echo -e "${red}Failed to install x-ui.service from GitHub (${script_ref}) -- the release tarball did not ship one either${plain}"
2026-01-02 22:27:39 -08:00
exit 1
fi
fi
fi
2026-05-04 04:20:24 -07:00
chown root:root ${xui_service}/x-ui.service > /dev/null 2>&1
chmod 644 ${xui_service}/x-ui.service > /dev/null 2>&1
systemctl daemon-reload > /dev/null 2>&1
systemctl enable x-ui > /dev/null 2>&1
systemctl start x-ui > /dev/null 2>&1
fi
2026-05-04 04:20:24 -07:00
config_after_update
2026-05-04 04:20:24 -07:00
# IP Limit relies on fail2ban; install + configure it now so the feature
# works out of the box on update too (no-op when XUI_ENABLE_FAIL2BAN=false).
# Never fatal.
setup_fail2ban
echo -e "${green}x-ui ${tag_version}${plain} updating finished, it is running now..."
echo -e ""
echo -e "┌───────────────────────────────────────────────────────┐
│ ${blue}x-ui control menu usages (subcommands):${plain} │
│ │
│ ${blue}x-ui${plain} - Admin Management Script │
│ ${blue}x-ui start${plain} - Start │
│ ${blue}x-ui stop${plain} - Stop │
│ ${blue}x-ui restart${plain} - Restart │
│ ${blue}x-ui status${plain} - Current Status │
│ ${blue}x-ui settings${plain} - Current Settings │
│ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
│ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
│ ${blue}x-ui log${plain} - Check logs │
│ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
│ ${blue}x-ui update${plain} - Update │
│ ${blue}x-ui legacy${plain} - Legacy version │
│ ${blue}x-ui install${plain} - Install │
│ ${blue}x-ui uninstall${plain} - Uninstall │
2025-12-03 15:05:21 -08:00
└───────────────────────────────────────────────────────┘"
}
echo -e "${green}Running...${plain}"
fix(systemd): harden shipped x-ui unit files (#6718) * fix(systemd): harden shipped x-ui unit files The units ran the panel as root with no sandboxing: systemd-analyze security rates them 9.6 UNSAFE. Add NoNewPrivileges, ProtectSystem=full with ReadWritePaths for the default XUI_DB_FOLDER/XUI_BIN_FOLDER/XUI_LOG_FOLDER stores, kernel and clock protections, UMask=0077, RestrictAddressFamilies, a CapabilityBoundingSet with NET_ADMIN/NET_BIND_SERVICE/NET_RAW and SystemCallFilter=@system-service. PrivateTmp is deliberately omitted: the web updater hands a path inside the system temp directory to a systemd-run transient unit, which does not share the service's private tmpfs. ProtectHome stays read-only because installs keep TLS certificates under the root home directory. Fixes #6605 * fix(systemd): ship ReadWriteDirectories= alias for systemd < 231 ReadWritePaths= only exists since systemd 231; install.sh still supports CentOS 7 (systemd 219), where the directive is ignored and ProtectSystem=full would leave the panel state directory read-only, breaking its database. * fix(systemd): keep root's DAC bits and regenerate the write paths Two follow-ups to the hardening, both reported by review on #6718. CAP_DAC_OVERRIDE and CAP_DAC_READ_SEARCH were dropped from the bounding set. Root holds them normally, and a bounding set is subtracted from root too: the panel could no longer read a private key it does not own (a Caddy-issued certificate under its own state dir, an acme.sh home, any 0600 file owned by another account). That fails quietly for TLS -- the panel listener logs the tls.LoadX509KeyPair error and keeps serving plain HTTP, and Xray inbounds using that key stop -- so both bits stay. ProtectSystem=full plus a hard-coded ReadWritePaths list broke installs whose XUI_DB_FOLDER/XUI_LOG_FOLDER/XUI_BIN_FOLDER live outside the defaults, and the workaround of editing the unit did not survive an update, because install.sh and update.sh reinstall the unit from the release tarball. The folders actually in use are now resolved from the same env file the unit passes to the panel and regenerated into x-ui.service.d/10-xui-write-paths.conf on every install and update, so a relocated store stays writable and the list is not reset. The unit keeps the plain-install defaults plus XUI_SERVICE, which the in-panel updater needs when systemd-run is unavailable and it falls back to a child process that inherits this sandbox while update.sh lands the unit again. Uninstall removes the drop-in with the unit. * fix(systemd): keep the seccomp whitelist off old systemd, tighten the rest Review of the previous head found that SystemCallFilter=@system-service plus SystemCallErrorNumber=EPERM is a hard regression on the platforms this PR means to keep working. @-named filter groups exist from systemd 239 on, and older systemd does not ignore an unknown group name: on <231 the name fails to resolve and the filter stays the built-in whitelist of execve/exit/exit_group/ rt_sigreturn/sigreturn, on 231..238 it degrades to @default. Either way the panel then gets EPERM on read/openat/mmap/clone and cannot start -- a CentOS 7 or Ubuntu 18.04 install would come up dead after this update. The two directives now live in the generated drop-in and are written only when "systemctl --version" reports 239 or newer, so old hosts keep the rest of the hardening and simply go without seccomp. The same review listed three more items, all addressed here: - a comment claiming ProtectSystem=full "keeps everything outside /var, /run and the listed ReadWritePaths read-only" -- that is `strict`; `full` locks down /usr, /boot, /efi and /etc; - /etc/systemd/system was granted writable for the in-panel updater's fallback, but that fallback cannot work under this sandbox at all: update.sh also stages the release archive beside the main folder, replaces /usr/bin/x-ui and calls the package manager. The entry is gone and update.sh now stops up front with one clear message when the directories it needs are read-only, instead of failing halfway with "Failed to download x-ui"; - CAP_DAC_READ_SEARCH is redundant next to CAP_DAC_OVERRIDE, so the bounding set keeps just the latter. Relocating a store by editing the env file alone is documented in the unit and in the generated drop-in: the drop-in is only written by install/update, so one of those has to be re-run afterwards. Verified with a local harness (9 checks: plain defaults, relocated store read from the env file, the same list produced by update.sh, duplicate collapse, seccomp present at systemd 249 and absent at 238, read-only guard) and bash -n on install.sh, update.sh, x-ui.sh. systemd-analyze is not available here, so the unit files themselves are unverified by a parser. * fix(systemd): actually wire the read-only guard, drop the superseded drop-in Re-review of the previous head caught two leftovers from that commit: - require_writable_update_paths was defined but never called, so the guard the unit comments, the commit message and the PR comment promise did not exist at all. It is now called at the top level, before install_base, i.e. before anything with a side effect: a sandboxed fallback run stops with one clear message instead of failing halfway, which on a relocated main folder meant the old install removed and the service folder rewritten before dying on /usr/bin. - the drop-in this branch replaced (10-xui-write-paths.conf) is no longer written or referenced, but nothing removed it either. Whoever installed the build that wrote it keeps its wider list, including the writable service folder, until it is deleted by hand. Both generators now remove it. Harness extended to 11 checks: the superseded file is gone after a run, the guard is actually called, plus the previous nine (defaults, env-file relocation, same list from update.sh, dedupe, seccomp at 249 / absent at 238, read-only guard) and bash -n on the three scripts. * fix(systemd): correct two comments and keep spaces out of the path list Second-opinion review of the previous head (two models, both asked to state platforms and versions) produced three actionable items: a wrong comment kept from the earlier commits, a wrong generalisation about the filter groups, and a path-list case that would leave the panel unable to start. - the ProtectSystem= comment claimed strict leaves /var and /run writable. It does not: strict mounts the whole hierarchy read-only and only the kernel API filesystems stay as they are. The sentence was already wrong before this branch and moving it to ProtectSystem=full did not fix it. - "the @-named filter groups need systemd >= 239" is the wrong generalisation: named groups exist since 231, it is @system-service that arrived in 239. The unit files, both script comments and the drop-in body now name the group. - a folder containing whitespace (XUI_DB_FOLDER="/srv/panel data") was written into ReadWritePaths= verbatim. That directive is a whitespace-separated list, so the entry splits into "-/srv/panel" and "data", and systemd rejects the whole drop-in: the panel then does not start at all. Such folders are left out and reported to the operator instead; the other paths are still written. Harness extended with three checks for the whitespace case (folder left out, remaining paths intact, warning emitted) and the duplicate-store case now reads its own env file instead of the previous one, so it tests what it claims. 14 checks plus bash -n on the three scripts, all passing. * fix(systemd): act on the independent review of the drop-in generator A read-only review of the branch head (another model, given the diff and the sources, asked to cite only verified lines) confirmed the earlier work and turned up four items that are fixed here: - a folder name carrying a literal % went into ReadWritePaths= as it was, and systemd expands %-specifiers in unit files: with XUI_DB_FOLDER=/srv/x%-ui the entry no longer named the directory the panel writes to and the panel could not write its database. The path is now emitted as %%; the duplicate check keeps comparing the unescaped value. - systemd older than 229/242/244 does not know NoNewPrivileges, ProtectClock, ProtectHostname and ProtectKernelLogs. It logs them and carries on, so CentOS 7 (systemd 219, which install.sh explicitly supports) runs with less hardening than the unit lists. install.sh and update.sh now print which protections need a newer systemd, which ones still apply, and that upgrading systemd is what changes it. - the updater's writability guard asked [[ -w ]] about the parent directories. It creates and removes a probe file instead, so an immutable attribute or a full filesystem is caught as well (a read-only mount was already caught). - the generator's comment claimed to resolve the folders the service actually uses, while the shipped unit hard-codes WorkingDirectory= and ExecStart= under /usr/local/x-ui. The comment now states what XUI_MAIN_FOLDER really feeds -- the location install.sh/update.sh install into and the base for a relative XUI_BIN_FOLDER -- and that a relocated main folder needs the unit edited too. Rejected from the same review, with the evidence: that [[ -w ]] cannot see a read-only mount (access(W_OK)/faccessat consults __mnt_is_readonly before the mode bits), and that the /etc ReadWritePaths entry is an exception granted for /etc rather than a default store already in the list. Harness extended: 19 checks (escaped %, the old-systemd note, whitespace and duplicate folders, seccomp gating, the read-only guard) plus bash -n on the three scripts, all passing. * fix(systemd): name the hardening old systemd really ignores The old-systemd note fired only below 239 and listed wrong versions: RHEL 8 (239) and Debian 10 (241) silently lose ProtectHostname and RestrictSUIDSGID (242), ProtectKernelLogs (244) and ProtectClock (245) with no note, while CentOS 7 was told NoNewPrivileges (187) and ProtectHome=read-only (214) were not applied although both are. The note is now built from a directive/version table taken from systemd.exec(5) and lists only what the running systemd lacks. Also drop the removal of 10-xui-write-paths.conf: only an intermediate commit of this branch wrote that file, no release ever shipped it. --------- Co-authored-by: Кот <kot@zeroclaw.local> Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-10-05 09:47:10 -07:00
require_writable_update_paths
install_base
update_x-ui $1