Add per-router VPS log archives available offline, live delivery and last reported service state. Keep router logs in RAM with bounded rotation and deduplication. Align log pages and mobile statistics, and bump application and deployment tools to v116.
1358 lines
37 KiB
Bash
1358 lines
37 KiB
Bash
#!/bin/sh
|
|
|
|
export PATH="/bin:/sbin:/usr/bin:/usr/sbin:${PATH:-}"
|
|
|
|
CONFIG="owrtremote"
|
|
SECTION="main"
|
|
XRAY_RELEASE_BASE_URL="${XRAY_RELEASE_BASE_URL:-https://github.com/XTLS/Xray-core/releases/latest/download}"
|
|
|
|
log() {
|
|
# procd already captures stderr. Use only logger for managed processes.
|
|
[ "${OWRT_REMOTE_SERVICE_LOG:-0}" = 1 ] || printf '%s\n' "$*" >&2
|
|
logger -t owrt-remote "$*" 2>/dev/null || true
|
|
}
|
|
|
|
die() {
|
|
log "ОШИБКА: $*"
|
|
exit 1
|
|
}
|
|
|
|
usage() {
|
|
cat <<'EOF'
|
|
Использование:
|
|
owrt-remote status
|
|
owrt-remote doctor
|
|
owrt-remote install-xray-tmp
|
|
owrt-remote stop-xray
|
|
owrt-remote render-client [--stdout]
|
|
owrt-remote run
|
|
owrt-remote heartbeat
|
|
owrt-remote heartbeat-loop
|
|
owrt-remote logs-sync
|
|
owrt-remote network-diagnostics
|
|
|
|
Настройки лежат в /etc/config/owrtremote.
|
|
EOF
|
|
}
|
|
|
|
uci_get() {
|
|
local key default value
|
|
key="$1"
|
|
default="$2"
|
|
value="$(uci -q get "$CONFIG.$SECTION.$key" 2>/dev/null || true)"
|
|
[ -n "$value" ] && {
|
|
printf '%s' "$value"
|
|
return
|
|
}
|
|
printf '%s' "$default"
|
|
}
|
|
|
|
truthy() {
|
|
case "$1" in
|
|
1|yes|true|on|enabled) return 0 ;;
|
|
*) return 1 ;;
|
|
esac
|
|
}
|
|
|
|
json_escape() {
|
|
printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g; s/ /\\t/g'
|
|
}
|
|
|
|
json_string() {
|
|
printf '"%s"' "$(json_escape "$1")"
|
|
}
|
|
|
|
safe_num() {
|
|
case "$1" in
|
|
''|*[!0-9]*) printf '%s' "$2" ;;
|
|
*) printf '%s' "$1" ;;
|
|
esac
|
|
}
|
|
|
|
safe_id() {
|
|
printf '%s' "$1" | tr -cs 'A-Za-z0-9._-' '-'
|
|
}
|
|
|
|
normalize_url_base() {
|
|
local value
|
|
value="${1%/}"
|
|
printf '%s' "$value"
|
|
}
|
|
|
|
json_unescape_basic() {
|
|
printf '%s' "$1" | sed 's/\\"/"/g; s/\\\\/\\/g'
|
|
}
|
|
|
|
json_extract_object_string() {
|
|
local file object key compact value
|
|
file="$1"
|
|
object="$2"
|
|
key="$3"
|
|
compact="$(tr -d '\r\n' <"$file" 2>/dev/null || true)"
|
|
[ -n "$compact" ] || return 0
|
|
value="$(printf '%s' "$compact" | sed -n "s/.*\"$object\"[[:space:]]*:[[:space:]]*{[^}]*\"$key\"[[:space:]]*:[[:space:]]*\"\\([^\"]*\\)\".*/\\1/p" | head -n 1)"
|
|
json_unescape_basic "$value"
|
|
}
|
|
|
|
uci_set_if_changed() {
|
|
local key next current
|
|
key="$1"
|
|
next="$2"
|
|
[ -n "$next" ] || return 1
|
|
current="$(uci_get "$key" '')"
|
|
[ "$current" = "$next" ] && return 1
|
|
uci -q set "$CONFIG.$SECTION.$key=$next" >/dev/null 2>&1 || return 1
|
|
return 0
|
|
}
|
|
|
|
# Existing installations also default to manual: only an explicit opt-in may
|
|
# let a heartbeat replace the administrator's tunnel endpoint.
|
|
vps_host_mode() {
|
|
case "$(uci_get vps_host_mode manual)" in
|
|
auto) printf auto ;;
|
|
*) printf manual ;;
|
|
esac
|
|
}
|
|
|
|
WAN_HELPER="${OWRT_REMOTE_WAN_HELPER:-/usr/lib/owrt-remote/wan.sh}"
|
|
if [ -r "$WAN_HELPER" ]; then
|
|
. "$WAN_HELPER"
|
|
fi
|
|
|
|
host_model() {
|
|
if [ -r /tmp/sysinfo/model ]; then
|
|
cat /tmp/sysinfo/model
|
|
return
|
|
fi
|
|
if [ -r /proc/device-tree/model ]; then
|
|
tr -d '\000' </proc/device-tree/model
|
|
return
|
|
fi
|
|
printf 'OpenWrt router'
|
|
}
|
|
|
|
board_name() {
|
|
if [ -r /tmp/sysinfo/board_name ]; then
|
|
cat /tmp/sysinfo/board_name
|
|
return
|
|
fi
|
|
printf 'unknown'
|
|
}
|
|
|
|
release_text() {
|
|
if [ -r /etc/openwrt_release ]; then
|
|
(
|
|
. /etc/openwrt_release 2>/dev/null
|
|
printf '%s %s' "${DISTRIB_ID:-OpenWrt}" "${DISTRIB_RELEASE:-unknown}"
|
|
)
|
|
return
|
|
fi
|
|
printf 'OpenWrt unknown'
|
|
}
|
|
|
|
uptime_seconds() {
|
|
if [ -r /proc/uptime ]; then
|
|
cut -d. -f1 /proc/uptime
|
|
return
|
|
fi
|
|
printf '0'
|
|
}
|
|
|
|
load_text() {
|
|
if [ -r /proc/loadavg ]; then
|
|
awk '{print $1" "$2" "$3}' /proc/loadavg
|
|
return
|
|
fi
|
|
printf '0 0 0'
|
|
}
|
|
|
|
memory_text() {
|
|
if [ -r /proc/meminfo ]; then
|
|
awk '
|
|
/^MemTotal:/ { total=$2 }
|
|
/^MemAvailable:/ { avail=$2 }
|
|
/^MemFree:/ && avail=="" { avail=$2 }
|
|
END {
|
|
if (total == "") total = 0
|
|
if (avail == "") avail = 0
|
|
printf "%s/%s kB", avail, total
|
|
}
|
|
' /proc/meminfo
|
|
return
|
|
fi
|
|
printf '0/0 kB'
|
|
}
|
|
|
|
flash_text() {
|
|
local mount text
|
|
text="$(
|
|
df -kP 2>/dev/null | awk '
|
|
function mb(k) {
|
|
if (k == "" || k == 0) return "0 MB"
|
|
return sprintf("%.1f MB", k / 1024)
|
|
}
|
|
NR == 1 { next }
|
|
{
|
|
mount = $NF
|
|
total = $(NF-4)
|
|
avail = $(NF-2)
|
|
pct = $(NF-1)
|
|
gsub(/%/, "", pct)
|
|
if (total !~ /^[0-9]+$/ || avail !~ /^[0-9]+$/ || pct !~ /^[0-9]+$/) next
|
|
|
|
score = 0
|
|
if (mount == "/overlay" || mount == "/rom/overlay") score = 400
|
|
else if (mount == "/") score = 300
|
|
else if ($1 == "overlayfs:/overlay") score = 250
|
|
else if (mount ~ /^\/overlay(\/|$)/) score = 200
|
|
if (score <= best_score) next
|
|
|
|
best_score = score
|
|
best_total = total
|
|
best_avail = avail
|
|
best_pct = pct
|
|
}
|
|
END {
|
|
if (best_score > 0) {
|
|
printf "%s free / %s (%s%% used)", mb(best_avail), mb(best_total), best_pct
|
|
}
|
|
}
|
|
'
|
|
)"
|
|
if [ -n "$text" ]; then
|
|
printf '%s' "$text"
|
|
return
|
|
fi
|
|
for mount in /overlay /rom/overlay /; do
|
|
text="$(
|
|
df -kP "$mount" 2>/dev/null | awk '
|
|
function mb(k) {
|
|
if (k == "" || k == 0) return "0 MB"
|
|
return sprintf("%.1f MB", k / 1024)
|
|
}
|
|
NR == 1 { next }
|
|
NF >= 5 {
|
|
total = $(NF-4)
|
|
avail = $(NF-2)
|
|
pct = $(NF-1)
|
|
gsub(/%/, "", pct)
|
|
if (total ~ /^[0-9]+$/ && avail ~ /^[0-9]+$/ && pct ~ /^[0-9]+$/) {
|
|
printf "%s free / %s (%s%% used)", mb(avail), mb(total), pct
|
|
exit
|
|
}
|
|
}
|
|
'
|
|
)"
|
|
if [ -n "$text" ]; then
|
|
printf '%s' "$text"
|
|
return
|
|
fi
|
|
done
|
|
printf 'unknown'
|
|
}
|
|
|
|
temperature_text() {
|
|
local file raw max
|
|
max=""
|
|
for file in /sys/class/thermal/thermal_zone*/temp /sys/devices/virtual/thermal/thermal_zone*/temp /sys/class/hwmon/hwmon*/temp*_input; do
|
|
[ -r "$file" ] || continue
|
|
raw="$(cat "$file" 2>/dev/null | tr -cd '0-9-')"
|
|
[ -n "$raw" ] || continue
|
|
case "$raw" in
|
|
-*|'') continue ;;
|
|
esac
|
|
[ -z "$max" ] && max="$raw"
|
|
[ "$raw" -gt "$max" ] && max="$raw"
|
|
done
|
|
if [ -n "$max" ]; then
|
|
awk -v t="$max" 'BEGIN { if (t > 1000) printf "%.1f C", t / 1000; else printf "%s C", t }'
|
|
return
|
|
fi
|
|
printf 'unknown'
|
|
}
|
|
|
|
ps_all() {
|
|
ps w 2>/dev/null || ps 2>/dev/null || true
|
|
}
|
|
|
|
xray_pids() {
|
|
local config cmdline cmd pid
|
|
config="$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
|
|
[ -n "$config" ] || return 0
|
|
for cmdline in /proc/[0-9]*/cmdline; do
|
|
[ -r "$cmdline" ] || continue
|
|
cmd="$(tr '\000' ' ' <"$cmdline" 2>/dev/null || true)"
|
|
case "$cmd" in
|
|
*xray*"$config"*|*xray-core*"$config"*)
|
|
pid="${cmdline%/cmdline}"
|
|
pid="${pid##*/}"
|
|
printf '%s\n' "$pid"
|
|
;;
|
|
esac
|
|
done
|
|
}
|
|
|
|
xray_running() {
|
|
[ -n "$(xray_pids)" ]
|
|
}
|
|
|
|
stop_xray() {
|
|
local pids pid alive
|
|
pids="$(xray_pids)"
|
|
if [ -z "$pids" ]; then
|
|
printf '%s\n' "OK: Xray уже остановлен"
|
|
return 0
|
|
fi
|
|
for pid in $pids; do
|
|
kill "$pid" >/dev/null 2>&1 || true
|
|
done
|
|
sleep 1
|
|
alive=""
|
|
for pid in $pids; do
|
|
if kill -0 "$pid" >/dev/null 2>&1; then
|
|
kill -9 "$pid" >/dev/null 2>&1 || true
|
|
alive="$alive $pid"
|
|
fi
|
|
done
|
|
if [ -n "$alive" ]; then
|
|
printf 'OK: Xray остановлен принудительно:%s\n' "$alive"
|
|
else
|
|
printf '%s\n' "OK: Xray остановлен"
|
|
fi
|
|
}
|
|
|
|
ssh_running() {
|
|
ps_all | grep '[d]ropbear' >/dev/null 2>&1
|
|
}
|
|
|
|
active_ssh_session() {
|
|
local port hex file
|
|
port="$(safe_num "$(uci_get ssh_port 22)" 22)"
|
|
hex="$(printf '%04X' "$port" 2>/dev/null || printf '0016')"
|
|
for file in /proc/net/tcp /proc/net/tcp6; do
|
|
[ -r "$file" ] || continue
|
|
awk -v port="$hex" '
|
|
NR > 1 {
|
|
split($2, local_addr, ":")
|
|
if (local_addr[2] == port && $4 == "01") {
|
|
found = 1
|
|
}
|
|
}
|
|
END { exit found ? 0 : 1 }
|
|
' "$file" 2>/dev/null && return 0
|
|
done
|
|
return 1
|
|
}
|
|
|
|
xray_bin_path() {
|
|
local configured candidate
|
|
configured="$(uci_get xray_bin /usr/bin/xray)"
|
|
if [ -x "$configured" ]; then
|
|
printf '%s' "$configured"
|
|
return
|
|
fi
|
|
for candidate in /usr/bin/xray /usr/bin/xray-core /usr/local/bin/xray /opt/bin/xray /tmp/owrt-xray/xray /tmp/owrt-xray/xray_softfloat /tmp/xray /tmp/xray_softfloat; do
|
|
if [ -x "$candidate" ]; then
|
|
printf '%s' "$candidate"
|
|
return
|
|
fi
|
|
done
|
|
candidate="$(command -v xray 2>/dev/null || command -v xray-core 2>/dev/null || true)"
|
|
if [ -n "$candidate" ] && [ -x "$candidate" ]; then
|
|
printf '%s' "$candidate"
|
|
return
|
|
fi
|
|
printf '%s' "$configured"
|
|
}
|
|
|
|
fetch_file() {
|
|
local url dst
|
|
url="$1"
|
|
dst="$2"
|
|
if command -v wget >/dev/null 2>&1; then
|
|
wget -q -O "$dst" "$url"
|
|
return
|
|
fi
|
|
if command -v curl >/dev/null 2>&1; then
|
|
curl -fsSL "$url" -o "$dst"
|
|
return
|
|
fi
|
|
die "для скачивания нужен wget или curl"
|
|
}
|
|
|
|
xray_arch() {
|
|
local arch
|
|
arch="$(uname -m 2>/dev/null || true)"
|
|
|
|
case "$arch" in
|
|
mips|mips64|mips64el|mips64le|mipsel|mipsle|'') ;;
|
|
*)
|
|
printf '%s\n' "$arch"
|
|
return
|
|
;;
|
|
esac
|
|
|
|
if command -v opkg >/dev/null 2>&1; then
|
|
arch="$(
|
|
opkg print-architecture 2>/dev/null | awk '
|
|
$1 == "arch" && $2 != "all" && $2 != "noarch" {
|
|
priority = $3 + 0
|
|
if (priority >= best_priority) {
|
|
best = $2
|
|
best_priority = priority
|
|
}
|
|
}
|
|
END {
|
|
if (best != "") {
|
|
print best
|
|
}
|
|
}
|
|
'
|
|
)"
|
|
[ -n "$arch" ] && {
|
|
printf '%s\n' "$arch"
|
|
return
|
|
}
|
|
fi
|
|
|
|
if command -v apk >/dev/null 2>&1; then
|
|
arch="$(apk --print-arch 2>/dev/null || true)"
|
|
[ -n "$arch" ] && {
|
|
printf '%s\n' "$arch"
|
|
return
|
|
}
|
|
fi
|
|
|
|
printf '%s\n' "$arch"
|
|
}
|
|
|
|
xray_release_asset() {
|
|
case "$(xray_arch)" in
|
|
aarch64|arm64) printf '%s\n' "Xray-linux-arm64-v8a.zip" ;;
|
|
armv7l|armv7*) printf '%s\n' "Xray-linux-arm32-v7a.zip" ;;
|
|
armv6l|armv6*) printf '%s\n' "Xray-linux-arm32-v6.zip" ;;
|
|
armv5l|armv5*) printf '%s\n' "Xray-linux-arm32-v5.zip" ;;
|
|
x86_64|amd64) printf '%s\n' "Xray-linux-64.zip" ;;
|
|
i386|i686) printf '%s\n' "Xray-linux-32.zip" ;;
|
|
mips64el|mips64le|mips64el_*|mips64le_*) printf '%s\n' "Xray-linux-mips64le.zip" ;;
|
|
mips64|mips64_*) printf '%s\n' "Xray-linux-mips64.zip" ;;
|
|
mipsel*|mipsle*) printf '%s\n' "Xray-linux-mips32le.zip" ;;
|
|
mips*) printf '%s\n' "Xray-linux-mips32.zip" ;;
|
|
*) return 1 ;;
|
|
esac
|
|
}
|
|
|
|
install_package() {
|
|
local pkg
|
|
pkg="$1"
|
|
if command -v opkg >/dev/null 2>&1; then
|
|
opkg update || die "не смог обновить opkg для установки $pkg"
|
|
opkg install "$pkg" || die "не смог поставить $pkg через opkg"
|
|
return
|
|
fi
|
|
if command -v apk >/dev/null 2>&1; then
|
|
apk -U add "$pkg" ca-certificates || die "не смог поставить $pkg через apk"
|
|
return
|
|
fi
|
|
die "не найден пакетный менеджер opkg или apk для установки $pkg"
|
|
}
|
|
|
|
install_xray_tmp() {
|
|
local dir zip asset url version
|
|
dir="/tmp/owrt-xray"
|
|
zip="$dir/xray.zip"
|
|
asset="$(xray_release_asset)" || die "не знаю готовый Xray asset для $(uname -m 2>/dev/null)"
|
|
url="$XRAY_RELEASE_BASE_URL/$asset"
|
|
|
|
mkdir -p /var/lock /var/run "$dir"
|
|
if ! command -v unzip >/dev/null 2>&1; then
|
|
install_package unzip
|
|
fi
|
|
|
|
printf 'Скачиваю Xray: %s\n' "$asset"
|
|
fetch_file "$url" "$zip"
|
|
( cd "$dir" && unzip -o "$zip" xray >/dev/null ) || die "не смог распаковать Xray"
|
|
chmod +x "$dir/xray"
|
|
version="$("$dir/xray" version 2>&1)" || die "скачанный Xray не запускается"
|
|
version="$(printf '%s\n' "$version" | sed -n '1p')"
|
|
|
|
uci set "$CONFIG.$SECTION.xray_bin=$dir/xray"
|
|
uci commit "$CONFIG"
|
|
printf 'OK: Xray поставлен в %s\n' "$dir/xray"
|
|
printf 'OK: %s\n' "$version"
|
|
printf 'OK: xray_bin сохранен в /etc/config/owrtremote\n'
|
|
}
|
|
|
|
ensure_xray_available() {
|
|
local configured candidate found
|
|
configured="$(uci_get xray_bin /usr/bin/xray)"
|
|
[ -x "$configured" ] && return 0
|
|
|
|
for candidate in /usr/bin/xray /usr/bin/xray-core /usr/local/bin/xray /opt/bin/xray /tmp/owrt-xray/xray /tmp/xray; do
|
|
if [ -x "$candidate" ]; then
|
|
found="$candidate"
|
|
break
|
|
fi
|
|
done
|
|
|
|
if [ -z "$found" ]; then
|
|
found="$(command -v xray 2>/dev/null || command -v xray-core 2>/dev/null || true)"
|
|
fi
|
|
|
|
if [ -n "$found" ] && [ -x "$found" ]; then
|
|
[ "$found" = "$configured" ] || {
|
|
uci set "$CONFIG.$SECTION.xray_bin=$found"
|
|
uci commit "$CONFIG"
|
|
log "Xray найден: $found"
|
|
}
|
|
return 0
|
|
fi
|
|
|
|
log "Xray не найден ($configured), ставлю временный Xray в /tmp..."
|
|
install_xray_tmp
|
|
}
|
|
|
|
service_enabled() {
|
|
/etc/init.d/owrt-remote enabled >/dev/null 2>&1
|
|
}
|
|
|
|
render_client_config() {
|
|
local out stdout router_id vps_host vps_port uuid ssh_uuid encryption flow reverse_tag ssh_reverse_tag admin_host admin_port ssh_host ssh_port xray_config xray_config_dir
|
|
stdout="0"
|
|
if [ "${1:-}" = "--stdout" ]; then
|
|
stdout="1"
|
|
fi
|
|
|
|
router_id="$(safe_id "$(uci_get router_id main)")"
|
|
vps_host="$(uci_get vps_host '')"
|
|
local wan_sockopt wan_xray_device
|
|
wan_sockopt=''
|
|
if truthy "$(uci_get wan_direct 0)"; then
|
|
command -v wan_prepare >/dev/null 2>&1 || die "WAN helper missing: $WAN_HELPER"
|
|
wan_prepare || die "не удалось подготовить прямое соединение через WAN"
|
|
vps_host="$(wan_resolve_host "$vps_host")" || die "VPS host не разрешается через WAN DNS"
|
|
wan_xray_device="$(wan_device)" || die "выбранный WAN интерфейс отключился"
|
|
wan_sockopt=", \"sockopt\": {\"mark\": $((PODKOP_BYPASS_MARK)), \"interface\": \"$(json_escape "$wan_xray_device")\"}"
|
|
fi
|
|
vps_port="$(safe_num "$(uci_get vps_port 8443)" 8443)"
|
|
uuid="$(uci_get vless_uuid '')"
|
|
ssh_uuid="$(uci_get ssh_vless_uuid '')"
|
|
encryption="$(uci_get vless_encryption none)"
|
|
flow="$(uci_get vless_flow '')"
|
|
reverse_tag="$(safe_id "$(uci_get reverse_tag reverse-in)")"
|
|
ssh_reverse_tag="$(safe_id "$(uci_get ssh_reverse_tag "${reverse_tag}-ssh")")"
|
|
admin_host="$(uci_get admin_host 127.0.0.1)"
|
|
admin_port="$(safe_num "$(uci_get admin_port 80)" 80)"
|
|
ssh_host="$(uci_get ssh_host 127.0.0.1)"
|
|
ssh_port="$(safe_num "$(uci_get ssh_port 22)" 22)"
|
|
xray_config="$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
|
|
|
|
[ -n "$vps_host" ] || die "vps_host пустой"
|
|
[ -n "$uuid" ] || die "vless_uuid пустой"
|
|
[ -n "$ssh_uuid" ] || ssh_uuid="$uuid"
|
|
|
|
if [ "$stdout" = "1" ]; then
|
|
out="${TMPDIR:-/tmp}/owrt-remote-client.$$"
|
|
else
|
|
xray_config_dir="$(dirname "$xray_config")"
|
|
mkdir -p "$xray_config_dir"
|
|
out="$xray_config_dir/.owrt-remote-client.$$"
|
|
fi
|
|
cat >"$out" <<EOF
|
|
{
|
|
"log": {
|
|
"access": "none",
|
|
"error": "",
|
|
"loglevel": "warning"
|
|
},
|
|
"inbounds": [],
|
|
"outbounds": [
|
|
{
|
|
"tag": "router-admin",
|
|
"protocol": "freedom",
|
|
"settings": {
|
|
"redirect": "$(json_escape "$admin_host"):$admin_port"
|
|
}
|
|
},
|
|
{
|
|
"tag": "router-ssh",
|
|
"protocol": "freedom",
|
|
"settings": {
|
|
"redirect": "$(json_escape "$ssh_host"):$ssh_port"
|
|
}
|
|
},
|
|
{
|
|
"tag": "vps-interconn",
|
|
"protocol": "vless",
|
|
"settings": {
|
|
"address": "$(json_escape "$vps_host")",
|
|
"port": $vps_port,
|
|
"id": "$(json_escape "$uuid")",
|
|
"encryption": "$(json_escape "$encryption")",
|
|
"flow": "$(json_escape "$flow")",
|
|
"reverse": {
|
|
"tag": "$(json_escape "$reverse_tag")"
|
|
}
|
|
},
|
|
"streamSettings": {
|
|
"network": "tcp",
|
|
"security": "none"$wan_sockopt
|
|
}
|
|
},
|
|
{
|
|
"tag": "vps-ssh-interconn",
|
|
"protocol": "vless",
|
|
"settings": {
|
|
"address": "$(json_escape "$vps_host")",
|
|
"port": $vps_port,
|
|
"id": "$(json_escape "$ssh_uuid")",
|
|
"encryption": "$(json_escape "$encryption")",
|
|
"flow": "$(json_escape "$flow")",
|
|
"reverse": {
|
|
"tag": "$(json_escape "$ssh_reverse_tag")"
|
|
}
|
|
},
|
|
"streamSettings": {
|
|
"network": "tcp",
|
|
"security": "none"$wan_sockopt
|
|
}
|
|
}
|
|
],
|
|
"routing": {
|
|
"rules": [
|
|
{
|
|
"type": "field",
|
|
"inboundTag": [
|
|
"$(json_escape "$reverse_tag")"
|
|
],
|
|
"outboundTag": "router-admin"
|
|
},
|
|
{
|
|
"type": "field",
|
|
"inboundTag": [
|
|
"$(json_escape "$ssh_reverse_tag")"
|
|
],
|
|
"outboundTag": "router-ssh"
|
|
}
|
|
]
|
|
},
|
|
"remarks": "OpenWrt Remote client for $(json_escape "$router_id")"
|
|
}
|
|
EOF
|
|
|
|
if [ "$stdout" = "1" ]; then
|
|
cat "$out"
|
|
rm -f "$out"
|
|
return
|
|
fi
|
|
|
|
mv -f "$out" "$xray_config"
|
|
chmod 0600 "$xray_config"
|
|
printf '%s\n' "$xray_config"
|
|
}
|
|
|
|
run_xray() {
|
|
local enabled xray_bin xray_config
|
|
enabled="$(uci_get enabled 0)"
|
|
truthy "$enabled" || die "сервис выключен: включи option enabled '1'"
|
|
|
|
ensure_xray_available
|
|
xray_bin="$(xray_bin_path)"
|
|
xray_config="$(render_client_config)" || die "не удалось создать конфигурацию Xray"
|
|
[ -n "$xray_config" ] && [ -s "$xray_config" ] || die "конфигурация Xray отсутствует или пуста"
|
|
[ -x "$xray_bin" ] || die "xray не найден или не исполняемый: $xray_bin"
|
|
|
|
if "$xray_bin" help 2>/dev/null | grep -q 'run'; then
|
|
exec "$xray_bin" run -config "$xray_config"
|
|
fi
|
|
exec "$xray_bin" -config "$xray_config"
|
|
}
|
|
|
|
heartbeat_json() {
|
|
local router_id router_name role public_url hub_url xray_state service_state ssh_state event heartbeat_interval
|
|
event="${1:-}"
|
|
router_id="$(safe_id "$(uci_get router_id main)")"
|
|
router_name="$(uci_get router_name "$router_id")"
|
|
role="$(uci_get role node)"
|
|
public_url="$(uci_get public_url '')"
|
|
hub_url="$(uci_get hub_url '')"
|
|
heartbeat_interval="$(safe_num "$(uci_get heartbeat_interval 30)" 30)"
|
|
[ "$heartbeat_interval" -lt 10 ] && heartbeat_interval=10
|
|
|
|
if xray_running; then
|
|
xray_state="running"
|
|
else
|
|
xray_state="stopped"
|
|
fi
|
|
if service_enabled; then
|
|
service_state="enabled"
|
|
else
|
|
service_state="disabled"
|
|
fi
|
|
if ssh_running; then
|
|
ssh_state="running"
|
|
else
|
|
ssh_state="stopped"
|
|
fi
|
|
|
|
cat <<EOF
|
|
{
|
|
"id": $(json_string "$router_id"),
|
|
"name": $(json_string "$router_name"),
|
|
"role": $(json_string "$role"),
|
|
"model": $(json_string "$(host_model)"),
|
|
"board": $(json_string "$(board_name)"),
|
|
"release": $(json_string "$(release_text)"),
|
|
"hostname": $(json_string "$(hostname 2>/dev/null || printf openwrt)"),
|
|
"public_url": $(json_string "$public_url"),
|
|
"admin_host": $(json_string "$(uci_get admin_host 127.0.0.1)"),
|
|
"admin_port": $(safe_num "$(uci_get admin_port 80)" 80),
|
|
"ssh_host": $(json_string "$(uci_get ssh_host 127.0.0.1)"),
|
|
"ssh_port": $(safe_num "$(uci_get ssh_port 22)" 22),
|
|
"hub_url": $(json_string "$hub_url"),
|
|
"vps_host": $(json_string "$(uci_get vps_host '')"),
|
|
"vps_host_mode": $(json_string "$(vps_host_mode)"),
|
|
"wan_direct": $(json_string "$(uci_get wan_direct 0)"),
|
|
"heartbeat_interval": $heartbeat_interval,
|
|
"uptime": $(safe_num "$(uptime_seconds)" 0),
|
|
"load": $(json_string "$(load_text)"),
|
|
"memory": $(json_string "$(memory_text)"),
|
|
"flash": $(json_string "$(flash_text)"),
|
|
"temperature": $(json_string "$(temperature_text)"),
|
|
"xray": $(json_string "$xray_state"),
|
|
"ssh": $(json_string "$ssh_state"),
|
|
"event": $(json_string "$event"),
|
|
"service": $(json_string "$service_state")
|
|
}
|
|
EOF
|
|
}
|
|
|
|
post_json() {
|
|
local url token file
|
|
url="$1"
|
|
token="$2"
|
|
file="$3"
|
|
if truthy "$(uci_get wan_direct 0)"; then
|
|
wan_post_json "$url" "$token" "$file"
|
|
return
|
|
fi
|
|
|
|
if command -v curl >/dev/null 2>&1; then
|
|
curl -fsSL --location --max-redirs 3 --post301 --post302 --post303 \
|
|
--connect-timeout 4 --max-time 10 --noproxy '*' \
|
|
-H "Authorization: Bearer $token" \
|
|
-H "Content-Type: application/json" \
|
|
--data-binary "@$file" "$url"
|
|
return
|
|
fi
|
|
if command -v wget >/dev/null 2>&1; then
|
|
http_proxy= https_proxy= HTTP_PROXY= HTTPS_PROXY= ALL_PROXY= all_proxy= wget -q -T 10 -O - \
|
|
--header="Authorization: Bearer $token" \
|
|
--header="Content-Type: application/json" \
|
|
--post-file="$file" "$url"
|
|
return
|
|
fi
|
|
if command -v uclient-fetch >/dev/null 2>&1; then
|
|
http_proxy= https_proxy= HTTP_PROXY= HTTPS_PROXY= ALL_PROXY= all_proxy= uclient-fetch -q -T 10 -O - \
|
|
--header="Authorization: Bearer $token" \
|
|
--header="Content-Type: application/json" \
|
|
--post-file="$file" "$url"
|
|
return
|
|
fi
|
|
die "для heartbeat нужен uclient-fetch, wget или curl"
|
|
}
|
|
|
|
global_logs_state() {
|
|
local enabled xray
|
|
enabled=false; xray=stopped
|
|
truthy "$(uci_get enabled 0)" && enabled=true
|
|
xray_running && xray=running
|
|
printf '{"enabled":%s,"xray":"%s"}' "$enabled" "$xray"
|
|
}
|
|
|
|
sync_global_logs() (
|
|
local helper router_id batch file response endpoint base token journal offset clear_token rc sync_lock owner attempt
|
|
helper="${OWRT_REMOTE_LOG_HELPER:-/usr/lib/owrt-remote/logs.sh}"
|
|
[ -r "$helper" ] || return 0
|
|
token="$(uci_get hub_token '')"; [ -n "$token" ] || return 0
|
|
# The journal is independent of Remote's enabled flag and Xray lifecycle.
|
|
sh "$helper" check || return 1
|
|
sync_lock="${OWRT_REMOTE_LOG_DIR:-/tmp/owrt-remote-logs}/sync-lock"
|
|
if ! mkdir "$sync_lock" 2>/dev/null; then
|
|
# Give a sender time to write its PID, then recover an abandoned lock.
|
|
for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
|
owner="$(cat "$sync_lock/pid" 2>/dev/null)"
|
|
case "$owner" in ''|*[!0-9]*) sleep 0.1 ;; *) break ;; esac
|
|
done
|
|
owner="$(cat "$sync_lock/pid" 2>/dev/null)"
|
|
case "$owner" in ''|*[!0-9]*) ;; *) kill -0 "$owner" 2>/dev/null && return 0 ;; esac
|
|
rm -f "$sync_lock/pid"; rmdir "$sync_lock" 2>/dev/null || return 0
|
|
mkdir "$sync_lock" 2>/dev/null || return 0
|
|
fi
|
|
printf '%s\n' "$$" >"$sync_lock/pid"
|
|
file=''; response=''
|
|
trap 'rm -f "$file" "$response" "$sync_lock/pid"; rmdir "$sync_lock" 2>/dev/null || true' EXIT
|
|
trap 'exit 1' INT TERM
|
|
if truthy "$(uci_get wan_direct 0)" && [ ! -s "$WAN_STATE/active-interface" ]; then wan_prepare || return 1; fi
|
|
batch="$(sh "$helper" export)" || return 1
|
|
router_id="$(safe_id "$(uci_get router_id main)")"
|
|
# export verifies that this directory is on tmpfs; payloads also stay in RAM.
|
|
umask 077
|
|
file="${OWRT_REMOTE_LOG_DIR:-/tmp/owrt-remote-logs}/sync.$$"; response="$file.response"
|
|
printf '{"id":%s,"batch":%s,"state":%s}\n' "$(json_string "$router_id")" "$batch" "$(global_logs_state)" >"$file"
|
|
for endpoint in $(heartbeat_candidate_endpoints); do
|
|
base="$(heartbeat_base_from_endpoint "$endpoint")"
|
|
if post_json "$base/api/router-logs" "$token" "$file" >"$response" 2>/dev/null &&
|
|
grep -Eq '"ok"[[:space:]]*:[[:space:]]*true' "$response"; then
|
|
journal="$(jsonfilter -i "$response" -e '@.journal_id' 2>/dev/null)"
|
|
offset="$(jsonfilter -i "$response" -e '@.offset' 2>/dev/null)"
|
|
clear_token="$(jsonfilter -i "$response" -e '@.clear_request' 2>/dev/null)"
|
|
sh "$helper" ack "$journal" "$offset" "$clear_token"
|
|
rc=$?
|
|
rm -f "$file" "$response"
|
|
rm -f "$sync_lock/pid"; rmdir "$sync_lock" 2>/dev/null || true
|
|
trap - EXIT INT TERM
|
|
return "$rc"
|
|
fi
|
|
done
|
|
rm -f "$file" "$response"
|
|
rm -f "$sync_lock/pid"; rmdir "$sync_lock" 2>/dev/null || true
|
|
trap - EXIT INT TERM
|
|
return 1
|
|
)
|
|
|
|
heartbeat_base_from_endpoint() {
|
|
printf '%s' "${1%/api/heartbeat}"
|
|
}
|
|
|
|
heartbeat_emit_endpoint() {
|
|
local base marker
|
|
base="$(normalize_url_base "$1")"
|
|
[ -n "$base" ] || return 0
|
|
marker="|$base|"
|
|
case "${HEARTBEAT_ENDPOINT_SEEN:-}" in
|
|
*"$marker"*) return 0 ;;
|
|
esac
|
|
HEARTBEAT_ENDPOINT_SEEN="${HEARTBEAT_ENDPOINT_SEEN:-}$marker"
|
|
printf '%s/api/heartbeat\n' "$base"
|
|
}
|
|
|
|
heartbeat_candidate_endpoints() {
|
|
local hub_url public_url vps_host
|
|
HEARTBEAT_ENDPOINT_SEEN='|'
|
|
hub_url="$(uci_get hub_url '')"
|
|
public_url="$(uci_get public_url '')"
|
|
vps_host="$(uci_get vps_host '')"
|
|
heartbeat_emit_endpoint "$hub_url"
|
|
heartbeat_emit_endpoint "$public_url"
|
|
case "$vps_host" in
|
|
'')
|
|
;;
|
|
http://*|https://*)
|
|
heartbeat_emit_endpoint "$vps_host"
|
|
;;
|
|
*)
|
|
heartbeat_emit_endpoint "https://$vps_host"
|
|
heartbeat_emit_endpoint "http://$vps_host"
|
|
heartbeat_emit_endpoint "http://$vps_host:8088"
|
|
;;
|
|
esac
|
|
}
|
|
|
|
heartbeat_set_url_if_changed() {
|
|
local key next current ignored_file ignored
|
|
key="$1"
|
|
next="$2"
|
|
case "$next" in http://?*|https://?*) ;; *) return 1 ;; esac
|
|
current="$(uci_get "$key" '')"
|
|
case "$current|$next" in
|
|
https://*'|'http://*)
|
|
ignored_file="${TMPDIR:-/tmp}/owrt-remote-$key-ignored"
|
|
ignored="$current|$next"
|
|
if [ "$(cat "$ignored_file" 2>/dev/null)" != "$ignored" ]; then
|
|
log "heartbeat kept $key: current=$current proposed=$next reason=https-downgrade"
|
|
printf '%s' "$ignored" >"$ignored_file"
|
|
fi
|
|
return 1
|
|
;;
|
|
esac
|
|
uci_set_if_changed "$key" "$next"
|
|
}
|
|
|
|
heartbeat_apply_hub_update() {
|
|
local response_file fallback_base next_hub_url next_public_url next_vps_host changed old_vps_host mode ignored_file ignored
|
|
response_file="$1"
|
|
fallback_base="$2"
|
|
next_hub_url="$(json_extract_object_string "$response_file" hub_update hub_url)"
|
|
next_public_url="$(json_extract_object_string "$response_file" hub_update public_url)"
|
|
next_vps_host="$(json_extract_object_string "$response_file" hub_update vps_host)"
|
|
old_vps_host="$(uci_get vps_host '')"
|
|
mode="$(vps_host_mode)"
|
|
# A fallback is a temporary transport, not a new configured Hub URL.
|
|
if [ -z "$next_hub_url" ] && [ -z "$(uci_get hub_url '')" ]; then
|
|
next_hub_url="$fallback_base"
|
|
fi
|
|
changed=0
|
|
if heartbeat_set_url_if_changed hub_url "$next_hub_url"; then
|
|
changed=1
|
|
fi
|
|
if heartbeat_set_url_if_changed public_url "$next_public_url"; then
|
|
changed=1
|
|
fi
|
|
if [ "$mode" = auto ]; then
|
|
if uci_set_if_changed vps_host "$next_vps_host"; then
|
|
changed=1
|
|
fi
|
|
elif [ -n "$next_vps_host" ] && [ "$old_vps_host" != "$next_vps_host" ]; then
|
|
ignored_file="${TMPDIR:-/tmp}/owrt-remote-vps-host-ignored"
|
|
ignored="$old_vps_host|$next_vps_host"
|
|
if [ "$(cat "$ignored_file" 2>/dev/null)" != "$ignored" ]; then
|
|
log "heartbeat kept vps_host: current=$old_vps_host proposed=$next_vps_host reason=manual"
|
|
printf '%s' "$ignored" >"$ignored_file"
|
|
fi
|
|
fi
|
|
[ "$changed" = "1" ] || return 0
|
|
uci commit "$CONFIG" >/dev/null 2>&1 || return 1
|
|
log "heartbeat updated hub settings: hub_url=$(uci_get hub_url '') public_url=$(uci_get public_url '') vps_host=$(uci_get vps_host '')"
|
|
if [ "$mode" = auto ] && [ -n "$next_vps_host" ] && [ "$old_vps_host" != "$next_vps_host" ]; then
|
|
log "heartbeat updated vps_host: old=$old_vps_host new=$next_vps_host reason=hub_update mode=auto"
|
|
# The running Xray keeps its old address until it is restarted.
|
|
( sleep 2; /etc/init.d/owrt-remote restart >/dev/null 2>&1 ) </dev/null >/dev/null 2>&1 &
|
|
fi
|
|
}
|
|
|
|
send_heartbeat() {
|
|
local hub_url token endpoint tmp response event used fallback_base errors rc
|
|
event="${1:-}"
|
|
hub_url="$(uci_get hub_url '')"
|
|
token="$(uci_get hub_token '')"
|
|
[ -n "$hub_url" ] || die "hub_url пустой"
|
|
[ -n "$token" ] || die "hub_token пустой"
|
|
if truthy "$(uci_get wan_direct 0)"; then
|
|
command -v wan_prepare >/dev/null 2>&1 || die "WAN helper missing: $WAN_HELPER"
|
|
wan_prepare || { log 'Heartbeat: не удалось подготовить прямой WAN'; return 1; }
|
|
wan_reconcile_xray
|
|
fi
|
|
|
|
endpoint="${hub_url%/}/api/heartbeat"
|
|
tmp="${TMPDIR:-/tmp}/owrt-remote-heartbeat.$$"
|
|
response="${TMPDIR:-/tmp}/owrt-remote-heartbeat.response.$$"
|
|
errors="$response.error"
|
|
heartbeat_json "$event" >"$tmp"
|
|
used=0
|
|
for endpoint in $(heartbeat_candidate_endpoints); do
|
|
used=1
|
|
rc=0
|
|
post_json "$endpoint" "$token" "$tmp" >"$response" 2>"$errors" || rc=$?
|
|
if [ "$rc" = 0 ] && grep -Eq '"ok"[[:space:]]*:[[:space:]]*true' "$response"; then
|
|
fallback_base="$(heartbeat_base_from_endpoint "$endpoint")"
|
|
if ! heartbeat_apply_hub_update "$response" "$fallback_base"; then
|
|
log 'Heartbeat: Hub ответил, но обновление настроек не применилось'
|
|
rm -f "$tmp" "$response" "$errors"
|
|
return 1
|
|
fi
|
|
cat "$response"
|
|
log "Heartbeat: OK; Hub=$fallback_base; WAN_direct=$(uci_get wan_direct 0); WAN_active=$(cat "$WAN_STATE/active-interface" 2>/dev/null)"
|
|
rm -f "$tmp" "$response" "$errors"
|
|
return 0
|
|
fi
|
|
log "Heartbeat: ошибка; endpoint=$endpoint; rc=$rc; $(head -c 1024 "$errors"); ответ=$(head -c 1024 "$response")"
|
|
done
|
|
rm -f "$tmp" "$response" "$errors"
|
|
[ "$used" = "1" ] || die "hub_url/public_url/vps_host пустые"
|
|
return 1
|
|
}
|
|
|
|
wan_reconcile_xray() {
|
|
local config bound device
|
|
config="$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
|
|
[ -r "$config" ] || return 0
|
|
bound="$(jsonfilter -i "$config" -e '@.outbounds[@.tag="vps-interconn"].streamSettings.sockopt.interface' 2>/dev/null)"
|
|
device="$(wan_device)" || return 1
|
|
[ "$bound" != "$device" ] || return 0
|
|
xray_running || return 0
|
|
wan_reconnect_xray "$bound" "$device"
|
|
}
|
|
|
|
wan_reconnect_xray() {
|
|
local restart_lock owner
|
|
restart_lock="${TMPDIR:-/tmp}/owrt-remote-wan-restart"
|
|
# A concurrent heartbeat must not enqueue another restart of the same tunnel.
|
|
if ! mkdir "$restart_lock" 2>/dev/null; then
|
|
owner="$(cat "$restart_lock/pid" 2>/dev/null)"
|
|
case "$owner" in ''|*[!0-9]*) return 0 ;; esac
|
|
kill -0 "$owner" 2>/dev/null && return 0
|
|
rm -f "$restart_lock/pid"
|
|
rmdir "$restart_lock" 2>/dev/null || return 0
|
|
mkdir "$restart_lock" 2>/dev/null || return 0
|
|
fi
|
|
log "Reconnecting reverse tunnel after WAN change: $1 -> $2"
|
|
(
|
|
trap 'rm -f "$restart_lock/pid"; rmdir "$restart_lock" 2>/dev/null || true' EXIT
|
|
trap 'exit 1' INT TERM
|
|
sleep 1
|
|
/etc/init.d/owrt-remote restart >/dev/null 2>&1 || log 'WAN failover tunnel restart failed'
|
|
) </dev/null >/dev/null 2>&1 &
|
|
printf '%s' "$!" >"$restart_lock/pid"
|
|
}
|
|
|
|
heartbeat_mark_ok() {
|
|
rm -f "${TMPDIR:-/tmp}/owrt-remote-heartbeat.fail"
|
|
}
|
|
|
|
heartbeat_self_heal() {
|
|
local fail_file restart_file fails now last_restart threshold cooldown
|
|
fail_file="${TMPDIR:-/tmp}/owrt-remote-heartbeat.fail"
|
|
restart_file="${TMPDIR:-/tmp}/owrt-remote-heartbeat.restart"
|
|
threshold=3
|
|
cooldown=300
|
|
now="$(date +%s 2>/dev/null || echo 0)"
|
|
fails=0
|
|
last_restart=0
|
|
|
|
[ -f "$fail_file" ] && fails="$(cat "$fail_file" 2>/dev/null || echo 0)"
|
|
fails="$(safe_num "$fails" 0)"
|
|
fails=$((fails + 1))
|
|
printf '%s\n' "$fails" >"$fail_file"
|
|
|
|
[ "$fails" -lt "$threshold" ] && return 0
|
|
if active_ssh_session; then
|
|
log "heartbeat failed ${threshold} times, restart postponed because SSH session is active"
|
|
return 0
|
|
fi
|
|
[ -f "$restart_file" ] && last_restart="$(cat "$restart_file" 2>/dev/null || echo 0)"
|
|
last_restart="$(safe_num "$last_restart" 0)"
|
|
[ $((now - last_restart)) -lt "$cooldown" ] && return 0
|
|
|
|
printf '%s\n' "$now" >"$restart_file"
|
|
rm -f "$fail_file"
|
|
log "heartbeat failed ${threshold} times in a row, restarting owrt-remote"
|
|
(
|
|
sleep 1
|
|
/etc/init.d/owrt-remote restart >/dev/null 2>&1
|
|
) &
|
|
}
|
|
|
|
heartbeat_loop() {
|
|
local interval
|
|
interval="$(safe_num "$(uci_get heartbeat_interval 30)" 30)"
|
|
[ "$interval" -lt 10 ] && interval=10
|
|
log "Heartbeat: цикл запущен; интервал=${interval}s"
|
|
while :; do
|
|
if send_heartbeat >/dev/null 2>&1; then
|
|
heartbeat_mark_ok
|
|
else
|
|
heartbeat_self_heal
|
|
fi
|
|
sleep "$interval"
|
|
done
|
|
}
|
|
|
|
status() {
|
|
printf 'router_id: %s\n' "$(uci_get router_id main)"
|
|
printf 'router_name: %s\n' "$(uci_get router_name '')"
|
|
printf 'enabled: %s\n' "$(uci_get enabled 0)"
|
|
printf 'hub_url: %s\n' "$(uci_get hub_url '')"
|
|
printf 'vps_host: %s\n' "$(uci_get vps_host '')"
|
|
printf 'vps_host_mode: %s\n' "$(vps_host_mode)"
|
|
printf 'wan_direct: %s\n' "$(uci_get wan_direct 0)"
|
|
printf 'wan_interfaces: %s\n' "$(uci_get wan_interface wan)"
|
|
printf 'wan_active_interface: %s\n' "$(cat "$WAN_STATE/active-interface" 2>/dev/null)"
|
|
printf 'vps_port: %s\n' "$(uci_get vps_port 8443)"
|
|
printf 'xray_bin: %s\n' "$(xray_bin_path)"
|
|
printf 'xray_config: %s\n' "$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
|
|
if xray_running; then
|
|
printf 'xray_state: running\n'
|
|
else
|
|
printf 'xray_state: stopped\n'
|
|
fi
|
|
if service_enabled; then
|
|
printf 'service: enabled\n'
|
|
else
|
|
printf 'service: disabled\n'
|
|
fi
|
|
}
|
|
|
|
doctor() {
|
|
local ok xray_bin
|
|
ok=1
|
|
ensure_xray_available
|
|
xray_bin="$(xray_bin_path)"
|
|
|
|
[ -x "$xray_bin" ] || {
|
|
log "нет Xray: $xray_bin"
|
|
ok=0
|
|
}
|
|
[ -n "$(uci_get hub_url '')" ] || {
|
|
log "hub_url пустой"
|
|
ok=0
|
|
}
|
|
[ -n "$(uci_get hub_token '')" ] || {
|
|
log "hub_token пустой"
|
|
ok=0
|
|
}
|
|
[ -n "$(uci_get vps_host '')" ] || {
|
|
log "vps_host пустой"
|
|
ok=0
|
|
}
|
|
[ -n "$(uci_get vless_uuid '')" ] || {
|
|
log "vless_uuid пустой"
|
|
ok=0
|
|
}
|
|
|
|
if [ "$ok" = "1" ]; then
|
|
printf '%s\n' "OK: конфиг выглядит готовым"
|
|
else
|
|
exit 1
|
|
fi
|
|
}
|
|
|
|
# Override Xray bootstrap with boot-safe retry logic.
|
|
fetch_file() {
|
|
local url dst
|
|
url="$1"
|
|
dst="$2"
|
|
rm -f "$dst"
|
|
if command -v curl >/dev/null 2>&1 && curl -fsSL "$url" -o "$dst"; then
|
|
return 0
|
|
fi
|
|
if command -v uclient-fetch >/dev/null 2>&1 && uclient-fetch -q -O "$dst" "$url"; then
|
|
return 0
|
|
fi
|
|
if command -v wget >/dev/null 2>&1 && wget -q -O "$dst" "$url"; then
|
|
return 0
|
|
fi
|
|
rm -f "$dst"
|
|
return 1
|
|
}
|
|
|
|
install_package() {
|
|
local pkg
|
|
pkg="$1"
|
|
if command -v opkg >/dev/null 2>&1; then
|
|
opkg update >/dev/null 2>&1 || return 1
|
|
opkg install "$pkg" >/dev/null 2>&1 || return 1
|
|
return 0
|
|
fi
|
|
if command -v apk >/dev/null 2>&1; then
|
|
apk -U add "$pkg" >/dev/null 2>&1 || return 1
|
|
return 0
|
|
fi
|
|
return 1
|
|
}
|
|
|
|
has_ca_certificates() {
|
|
[ -s /etc/ssl/cert.pem ] && return 0
|
|
[ -s /etc/ssl/certs/ca-certificates.crt ] && return 0
|
|
[ -d /etc/ssl/certs ] && ls /etc/ssl/certs/* >/dev/null 2>&1 && return 0
|
|
return 1
|
|
}
|
|
|
|
ensure_ca_certificates() {
|
|
has_ca_certificates && return 0
|
|
if command -v apk >/dev/null 2>&1; then
|
|
install_package ca-certificates >/dev/null 2>&1 || true
|
|
fi
|
|
if command -v opkg >/dev/null 2>&1; then
|
|
install_package ca-bundle >/dev/null 2>&1 || install_package ca-certificates >/dev/null 2>&1 || true
|
|
fi
|
|
has_ca_certificates
|
|
}
|
|
|
|
ensure_fetch_tool() {
|
|
command -v curl >/dev/null 2>&1 && return 0
|
|
command -v uclient-fetch >/dev/null 2>&1 && return 0
|
|
command -v wget >/dev/null 2>&1 && return 0
|
|
if command -v apk >/dev/null 2>&1; then
|
|
install_package curl >/dev/null 2>&1 || install_package wget >/dev/null 2>&1 || true
|
|
fi
|
|
if command -v opkg >/dev/null 2>&1; then
|
|
install_package curl >/dev/null 2>&1 || install_package wget-ssl >/dev/null 2>&1 || install_package wget >/dev/null 2>&1 || true
|
|
fi
|
|
command -v curl >/dev/null 2>&1 && return 0
|
|
command -v uclient-fetch >/dev/null 2>&1 && return 0
|
|
command -v wget >/dev/null 2>&1 && return 0
|
|
return 1
|
|
}
|
|
|
|
install_xray_tmp() {
|
|
local dir zip asset url version entry candidates
|
|
dir="/tmp/owrt-xray"
|
|
zip="$dir/xray.zip"
|
|
asset="$(xray_release_asset)" || {
|
|
log "unknown Xray asset for $(uname -m 2>/dev/null)"
|
|
return 1
|
|
}
|
|
url="$XRAY_RELEASE_BASE_URL/$asset"
|
|
|
|
mkdir -p /var/lock /var/run "$dir"
|
|
if ! command -v unzip >/dev/null 2>&1; then
|
|
install_package unzip || {
|
|
log "cannot install unzip"
|
|
return 1
|
|
}
|
|
fi
|
|
ensure_ca_certificates || log "CA certificates not found, trying download anyway"
|
|
ensure_fetch_tool || {
|
|
log "need curl, uclient-fetch or wget to download Xray"
|
|
return 1
|
|
}
|
|
|
|
printf 'Skachivayu Xray: %s\n' "$asset"
|
|
rm -f "$zip" "$dir/xray" "$dir/xray_softfloat"
|
|
fetch_file "$url" "$zip" || {
|
|
log "cannot download Xray: $url"
|
|
return 1
|
|
}
|
|
[ -s "$zip" ] || {
|
|
log "downloaded Xray archive is empty: $zip"
|
|
rm -f "$zip"
|
|
return 1
|
|
}
|
|
|
|
candidates="xray"
|
|
case "$(xray_arch)" in
|
|
mips*)
|
|
candidates="xray_softfloat xray"
|
|
;;
|
|
esac
|
|
|
|
for entry in $candidates; do
|
|
( cd "$dir" && unzip -o "$zip" "$entry" >/dev/null ) || continue
|
|
[ -s "$dir/$entry" ] || continue
|
|
chmod +x "$dir/$entry"
|
|
version="$("$dir/$entry" version 2>&1)" || {
|
|
rm -f "$dir/$entry"
|
|
continue
|
|
}
|
|
version="$(printf '%s\n' "$version" | sed -n '1p')"
|
|
|
|
uci set "$CONFIG.$SECTION.xray_bin=$dir/$entry"
|
|
uci commit "$CONFIG"
|
|
printf 'OK: Xray installed in %s\n' "$dir/$entry"
|
|
printf 'OK: %s\n' "$version"
|
|
printf 'OK: xray_bin saved in /etc/config/owrtremote\n'
|
|
return 0
|
|
done
|
|
|
|
log "downloaded Xray does not start"
|
|
rm -f "$dir/xray" "$dir/xray_softfloat"
|
|
return 1
|
|
}
|
|
|
|
ensure_xray_available() {
|
|
local configured candidate found
|
|
configured="$(uci_get xray_bin /usr/bin/xray)"
|
|
[ -x "$configured" ] && return 0
|
|
|
|
for candidate in /usr/bin/xray /usr/bin/xray-core /usr/local/bin/xray /opt/bin/xray /tmp/owrt-xray/xray /tmp/owrt-xray/xray_softfloat /tmp/xray /tmp/xray_softfloat; do
|
|
if [ -x "$candidate" ]; then
|
|
found="$candidate"
|
|
break
|
|
fi
|
|
done
|
|
|
|
if [ -z "$found" ]; then
|
|
found="$(command -v xray 2>/dev/null || command -v xray-core 2>/dev/null || true)"
|
|
fi
|
|
|
|
if [ -n "$found" ] && [ -x "$found" ]; then
|
|
[ "$found" = "$configured" ] || {
|
|
uci set "$CONFIG.$SECTION.xray_bin=$found"
|
|
uci commit "$CONFIG"
|
|
log "Xray found: $found"
|
|
}
|
|
return 0
|
|
fi
|
|
|
|
log "Xray missing ($configured), reinstalling temporary Xray in /tmp..."
|
|
install_xray_tmp
|
|
}
|
|
|
|
ensure_xray_available_with_retry() {
|
|
local attempts delay try_num
|
|
attempts="${1:-18}"
|
|
delay="${2:-10}"
|
|
try_num=1
|
|
while [ "$try_num" -le "$attempts" ]; do
|
|
if ensure_xray_available; then
|
|
return 0
|
|
fi
|
|
[ "$try_num" -ge "$attempts" ] && break
|
|
log "Xray is not ready yet, retry in ${delay}s (${try_num}/${attempts})"
|
|
sleep "$delay"
|
|
try_num=$((try_num + 1))
|
|
done
|
|
return 1
|
|
}
|
|
|
|
run_xray() {
|
|
local enabled xray_bin xray_config
|
|
enabled="$(uci_get enabled 0)"
|
|
truthy "$enabled" || die "service disabled: set option enabled '1'"
|
|
|
|
ensure_xray_available_with_retry || die "cannot prepare Xray for tunnel"
|
|
xray_bin="$(xray_bin_path)"
|
|
xray_config="$(render_client_config)" || die "cannot create Xray configuration"
|
|
[ -n "$xray_config" ] && [ -s "$xray_config" ] || die "Xray configuration is missing or empty"
|
|
[ -x "$xray_bin" ] || die "xray not found or not executable: $xray_bin"
|
|
log "Xray: запуск туннеля; config=$xray_config; VPS=$(uci_get vps_host ''):$(uci_get vps_port 8443); WAN_direct=$(uci_get wan_direct 0); WAN_selected=$(uci_get wan_interface wan)"
|
|
|
|
if "$xray_bin" help 2>/dev/null | grep -q 'run'; then
|
|
exec "$xray_bin" run -config "$xray_config"
|
|
fi
|
|
exec "$xray_bin" -config "$xray_config"
|
|
}
|
|
|
|
cmd="${1:-help}"
|
|
shift || true
|
|
|
|
case "$cmd" in
|
|
help|-h|--help)
|
|
usage
|
|
;;
|
|
status)
|
|
status
|
|
;;
|
|
doctor)
|
|
doctor
|
|
;;
|
|
wan-prepare)
|
|
wan_prepare
|
|
;;
|
|
wan-preflight)
|
|
wan_preflight
|
|
;;
|
|
wan-cleanup)
|
|
wan_cleanup
|
|
;;
|
|
network-diagnostics)
|
|
wan_diagnostics
|
|
;;
|
|
install-xray-tmp)
|
|
install_xray_tmp
|
|
;;
|
|
stop-xray)
|
|
stop_xray
|
|
;;
|
|
render-client)
|
|
render_client_config "$@"
|
|
;;
|
|
run)
|
|
run_xray
|
|
;;
|
|
heartbeat)
|
|
send_heartbeat "$@"
|
|
;;
|
|
heartbeat-loop)
|
|
heartbeat_loop
|
|
;;
|
|
logs-sync)
|
|
sync_global_logs
|
|
;;
|
|
*)
|
|
usage >&2
|
|
exit 2
|
|
;;
|
|
esac
|