#!/bin/sh
KEY_FILE="${KEY_FILE:-/etc/owrt-remote/web.key}"
AGENT="${AGENT:-/usr/sbin/owrt-remote}"
LOG_HELPER="${OWRT_REMOTE_LOG_HELPER:-/usr/lib/owrt-remote/logs.sh}"
OWRT_REMOTE_UI_VERSION="2026-07-02-mobile-terminal-batch-v25"
PARAMS_FILE="${TMPDIR:-/tmp}/owrt-remote-cgi.$$"
RESULT_TITLE=""
RESULT_BODY=""
RESULT_KIND="info"
SHOW_XRAY_SETTINGS="0"
XRAY_SETTINGS_DRAFT=""
cleanup() {
rm -f "$PARAMS_FILE"
}
trap cleanup EXIT INT TERM
html_escape() {
sed 's/&/\&/g; s/\</g; s/>/\>/g; s/"/\"/g'
}
h() {
printf '%s' "$1" | html_escape
}
url_decode() {
local data
data="$(printf '%s' "$1" | sed 's/+/ /g; s/%/\\x/g')"
printf '%b' "$data"
}
parse_params() {
local data old_ifs pair key value
data="$1"
old_ifs="$IFS"
IFS='&'
for pair in $data; do
key="${pair%%=*}"
value="${pair#*=}"
[ "$pair" = "$key" ] && value=""
key="$(url_decode "$key" | tr -d '\r\n\t')"
[ -n "$key" ] && printf '%s\t%s\n' "$key" "$value" >>"$PARAMS_FILE"
done
IFS="$old_ifs"
}
param() {
local raw
raw="$(awk -F ' ' -v k="$1" '$1 == k { print $2; exit }' "$PARAMS_FILE")"
url_decode "$raw"
}
param_values() {
local raw
awk -F '\t' -v k="$1" '$1 == k { print $2 }' "$PARAMS_FILE" | while IFS= read -r raw; do
url_decode "$raw"
printf '\n'
done
}
has_param() {
awk -F ' ' -v k="$1" '$1 == k { found = 1 } END { exit(found ? 0 : 1) }' "$PARAMS_FILE"
}
read_request() {
local post_data
: >"$PARAMS_FILE"
parse_params "${QUERY_STRING:-}"
case "${CONTENT_TYPE:-}" in
multipart/form-data*) return ;;
esac
if [ "${REQUEST_METHOD:-GET}" = "POST" ] && [ -n "${CONTENT_LENGTH:-}" ]; then
post_data="$(dd bs=1 count="$CONTENT_LENGTH" 2>/dev/null)"
parse_params "$post_data"
fi
}
http_html() {
printf 'Content-Type: text/html; charset=utf-8\r\n'
printf 'Cache-Control: no-store, no-cache, must-revalidate, max-age=0\r\n'
printf 'Pragma: no-cache\r\n'
printf 'Expires: 0\r\n\r\n'
}
http_json() {
printf 'Content-Type: application/json; charset=utf-8\r\n'
printf 'Cache-Control: no-store\r\n\r\n'
}
web_key() {
cat "$KEY_FILE" 2>/dev/null
}
authorized() {
local expected supplied
expected="$(web_key)"
supplied="$(param key)"
[ -n "$expected" ] && [ "$supplied" = "$expected" ]
}
uci_get() {
local key default value
key="$1"
default="$2"
value="$(uci -q get "owrtremote.main.$key" 2>/dev/null || true)"
[ -n "$value" ] && {
printf '%s' "$value"
return
}
printf '%s' "$default"
}
uci_set() {
local key value
key="$1"
value="$2"
uci -q get owrtremote.main >/dev/null 2>&1 || uci set owrtremote.main=remote
uci set "owrtremote.main.$key=$value"
}
service_enabled() {
/etc/init.d/owrt-remote enabled >/dev/null 2>&1
}
xray_running() {
"$AGENT" status 2>/dev/null | grep -q '^xray_state: running'
}
set_result() {
RESULT_TITLE="$1"
RESULT_BODY="$2"
RESULT_KIND="${3:-info}"
if [ -r "$LOG_HELPER" ]; then
printf '%s\n' "$RESULT_BODY" | sh "$LOG_HELPER" event "Панель: $RESULT_TITLE; результат=$RESULT_KIND" "$RESULT_KIND" >/dev/null 2>&1 || true
fi
}
logs_response() {
local mode
mode="$1"
if [ ! -r "$LOG_HELPER" ]; then
printf 'Status: 503 Service Unavailable\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\n\r\n'
printf 'Сборщик логов не установлен. Установи локальный фикс целиком.\n'
return
fi
if ! sh "$LOG_HELPER" check >/dev/null 2>&1; then
printf 'Status: 503 Service Unavailable\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\n\r\n'
printf 'Журнал недоступен: для логов требуется ОЗУ (tmpfs). Запись на Flash запрещена.\n'
return
fi
if [ "$mode" = clear ]; then
if [ "${REQUEST_METHOD:-GET}" != POST ]; then
printf 'Status: 405 Method Not Allowed\r\nAllow: POST\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n'
return
fi
if sh "$LOG_HELPER" clear; then
printf 'Content-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\n\r\n'
printf 'Логи Remote очищены.\n'
else
printf 'Status: 503 Service Unavailable\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n'
printf 'Не удалось очистить логи. Повтори через несколько секунд.\n'
fi
return
fi
printf 'Content-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n'
if [ "$mode" = download ]; then
printf 'Content-Disposition: attachment; filename="owrt-remote-global-%s.log"\r\n' "$(date '+%Y%m%d-%H%M%S')"
fi
printf '\r\n'
sh "$LOG_HELPER" read "$mode"
}
save_config() {
local enabled field wan_interfaces
wan_interfaces="$(param_values wan_interface | awk 'NF { if (NF != 1 || $0 !~ /^[a-zA-Z0-9_.:-]+$/) exit 1; if (!seen[$0]++) { printf "%s%s", sep, $0; sep=" " } }')" || {
set_result "Настройки не сохранены" "Некорректное имя WAN интерфейса." "bad"
return 1
}
if [ -z "$wan_interfaces" ]; then
if has_param wan_interface_picker && has_param wan_direct; then
set_result "Настройки не сохранены" "Для прямого соединения с Hub отметь хотя бы один WAN интерфейс." "warn"
return 1
fi
wan_interfaces=wan
fi
if has_param enabled; then
enabled="1"
else
enabled="0"
fi
uci_set enabled "$enabled"
for field in router_id router_name role hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_port vless_uuid vless_encryption vless_flow reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port public_url; do
uci_set "$field" "$(param "$field")"
done
if has_param vps_host_auto; then uci_set vps_host_mode auto; else uci_set vps_host_mode manual; fi
if has_param wan_direct; then uci_set wan_direct 1; else uci_set wan_direct 0; fi
uci_set wan_interface "$wan_interfaces"
uci_set wan_dns "$(param wan_dns)"
uci commit owrtremote
if [ -r "$LOG_HELPER" ]; then
printf '' | sh "$LOG_HELPER" event "Панель: сохранены настройки; enabled=$enabled; Hub=$(uci_get hub_url ''); VPS=$(uci_get vps_host ''):$(uci_get vps_port 8443); WAN_direct=$(uci_get wan_direct 0); WAN_selected=$wan_interfaces" >/dev/null 2>&1 || true
fi
set_result "Настройки сохранены" "Если менял Xray или VPS-поля, перезапусти сервис." "ok"
}
clear_config() {
local field
for field in role public_url hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_host_mode wan_direct wan_interface wan_dns vps_port vless_uuid vless_encryption vless_flow reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port; do
uci -q delete "owrtremote.main.$field"
done
uci commit owrtremote
set_result "Конфигурация очищена" "Поля VPS, Xray, LuCI и SSH очищены. Router ID и название оставлены." "warn"
}
normalize_xray_settings() {
# Only repair mobile typography around a complete UCI assignment. Values
# already enclosed in shell quotes (including names/tokens) stay unchanged.
LC_ALL=C awk '
function shell_quote(value, result, i, char) {
result = "\047"
for (i = 1; i <= length(value); i++) {
char = substr(value, i, 1)
result = result (char == "\047" ? "\047\042\047\042\047" : char)
}
return result "\047"
}
function scan_quotes(line, i, char) {
for (i = 1; i <= length(line); i++) {
char = substr(line, i, 1)
if (quote != "\047" && char == "\\") { i++; continue }
if (!quote && char == "#" && (i == 1 || substr(line, i - 1, 1) ~ /[ \t;]/)) break
if (char == quote) quote = ""
else if (!quote && (char == "\047" || char == "\042")) quote = char
}
}
NR == 1 { sub(/^\357\273\277/, "") }
{
line = $0
# Arbitrary shell input may contain a heredoc or multiline string.
# Preserve it verbatim instead of interpreting payload as commands.
if (index(line, "<<")) literal = 1
position = index(line, "=")
prefix = substr(line, 1, position)
gsub(/\302\240|\342\200\257/, " ", prefix)
if (!quote && !literal && !continued && position && prefix ~ /^[ \t]*uci[ \t]+(-q[ \t]+)?set[ \t]+owrtremote\.main(\.[a-zA-Z0-9_]+)?=$/) {
value = substr(line, position + 1)
sub(/[ \t]+$/, "", value)
if (value ~ /^\342\200\230.*\342\200\231$/ || value ~ /^\342\200\234.*\342\200\235$/) {
line = prefix shell_quote(substr(value, 4, length(value) - 6))
} else {
line = prefix substr(line, position + 1)
}
}
print line
scan_quotes(line)
continued = (line ~ /\\$/)
}
'
}
apply_xray_settings() {
local script script_file output trace stage rc
# HTML textarea POSTs use CRLF, even when the copied Hub commands use LF.
# BusyBox ash treats the trailing CR as part of keywords such as then/fi.
XRAY_SETTINGS_DRAFT="$(param xray_settings_script | tr -d '\r')"
script="$(printf '%s\n' "$XRAY_SETTINGS_DRAFT" | normalize_xray_settings)"
output="${TMPDIR:-/tmp}/owrt-remote-apply.$$"
script_file="${TMPDIR:-/tmp}/owrt-remote-apply-script.$$"
trace="${TMPDIR:-/tmp}/owrt-remote-apply-trace.$$"
rc=0
SHOW_XRAY_SETTINGS="1"
# BusyBox tr in OpenWrt does not enable [:space:] by default.
if [ -z "$(printf '%s' "$script" | tr -d ' \t\r\n\v\f')" ]; then
set_result "Xray настройки" "Вставь команды из OpenWrt config на VPS и нажми Применить." "warn"
return
fi
{
printf '%s\n' "#!/bin/sh"
printf '%s\n' "$script"
} >"$script_file"
chmod 600 "$script_file" 2>/dev/null || true
# Check the complete script before any UCI command can change the router.
if sh -n "$script_file" >"$output" 2>&1; then
:
else
rc=$?
set_result "Ошибка применения Xray настроек" "Синтаксическая ошибка в командах. Настройки не изменены.
$(cat "$output")
rc=$rc" "bad"
rm -f "$script_file" "$output"
return
fi
: >"$trace"
chmod 600 "$trace" 2>/dev/null || true
export OWRT_REMOTE_APPLY_TRACE="$trace"
if sh -e "$script_file" >"$output" 2>&1; then
XRAY_SETTINGS_DRAFT=""
set_result "Xray настройки применены" "$(cat "$output")" "ok"
else
rc=$?
stage="$(tail -n 1 "$trace" 2>/dev/null)"
case "$stage" in
heartbeat)
set_result "Ошибка отправки Heartbeat после применения настроек" "$(cat "$output")
rc=$rc
Сбой произошёл на отправке Heartbeat, а не при проверке JSON Xray. Ранее выполненные команды уже применены. Проверь указанный выше ответ HTTP-клиента и адрес Hub.
Вставленные команды сохранены в поле ниже." "bad"
;;
render-client)
set_result "Ошибка проверки конфигурации Xray" "$(cat "$output")
rc=$rc
Новый JSON не установлен; перезапуск из этого блока не выполнен. Рабочий файл конфигурации сохранён. Уже записанные команды UCI не отменяются автоматически.
Вставленные команды сохранены в поле ниже." "bad"
;;
*)
set_result "Ошибка применения Xray настроек" "$(cat "$output")
rc=$rc
Команда завершилась с ошибкой. Причина — в выводе выше; этот код сам по себе не означает ошибку форматирования. Вставленные команды сохранены в поле ниже." "bad"
;;
esac
fi
rm -f "$script_file" "$output" "$trace"
}
run_action() {
local action output rc
action="$1"
output="${TMPDIR:-/tmp}/owrt-remote-action.$$"
rc=0
case "$action" in
start)
: >"$output"
uci_set enabled 1
uci commit owrtremote >>"$output" 2>&1 || rc=$?
/etc/init.d/owrt-remote enable >>"$output" 2>&1 || rc=$?
/etc/init.d/owrt-remote restart >>"$output" 2>&1 || rc=$?
set_result "Сервис запущен" "$(cat "$output")" "ok"
;;
stop)
: >"$output"
uci_set enabled 0
uci commit owrtremote >>"$output" 2>&1 || rc=$?
/etc/init.d/owrt-remote stop >>"$output" 2>&1 || rc=$?
"$AGENT" stop-xray >>"$output" 2>&1 || rc=$?
/etc/init.d/owrt-remote disable >>"$output" 2>&1 || rc=$?
"$AGENT" heartbeat >>"$output" 2>&1 || true
set_result "Сервис остановлен" "$(cat "$output")" "warn"
;;
restart)
: >"$output"
uci_set enabled 1
uci commit owrtremote >>"$output" 2>&1 || rc=$?
/etc/init.d/owrt-remote enable >>"$output" 2>&1 || rc=$?
/etc/init.d/owrt-remote restart >>"$output" 2>&1 || rc=$?
set_result "Сервис перезапущен" "$(cat "$output")" "ok"
;;
heartbeat)
"$AGENT" heartbeat >"$output" 2>&1 || rc=$?
if [ "$rc" = "0" ] && grep -q '"ok"[[:space:]]*:[[:space:]]*true' "$output"; then
set_result "Heartbeat" "OK: роутер отправил heartbeat на VPS, карточка обновлена." "ok"
else
set_result "Heartbeat" "$(cat "$output")" "ok"
fi
;;
doctor)
"$AGENT" doctor >"$output" 2>&1 || rc=$?
set_result "Проверка" "$(cat "$output")" "ok"
;;
install_xray_tmp)
if "$AGENT" install-xray-tmp >"$output" 2>&1; then
"$AGENT" render-client >>"$output" 2>&1 || rc=$?
/etc/init.d/owrt-remote restart >>"$output" 2>&1 || rc=$?
else
rc=$?
fi
set_result "Xray установлен в /tmp" "$(cat "$output")" "ok"
;;
esac
if [ "$rc" != "0" ]; then
set_result "$RESULT_TITLE" "$(cat "$output")" "bad"
fi
# Deliver the completed stop result without keeping a mobile HTTP request open.
if [ "$action" = stop ]; then
( "$AGENT" logs-sync ) /dev/null 2>&1 &
fi
rm -f "$output"
}
field() {
local name label value type help
name="$1"
label="$2"
type="${3:-text}"
help="${4:-}"
value="$(uci_get "$name" '')"
printf ''
}
wan_interface_field() {
local current interfaces iface selected count
current="$(uci_get wan_interface wan)"
# netifd uses logical interface names, not physical devices such as eth0.
# Include configured interfaces even while their modem/link is down.
interfaces="$(
{
uci -q show network 2>/dev/null | sed -n 's/^network\.\([^.=]*\)=interface$/\1/p'
ubus call network.interface dump 2>/dev/null | jsonfilter -e '@.interface[*].interface' 2>/dev/null
} | LC_ALL=C sort -u | while IFS= read -r iface; do
case "$iface" in ''|*[!a-zA-Z0-9_.:-]*) continue ;; esac
printf '%s\n' "$iface"
done
)"
count="$(printf '%s\n' "$current" | awk '{ print NF }')"
printf '
WAN интерфейс'
printf 'Отметь один или несколько интерфейсов с выходом в Интернет. Remote использует один доступный из выбранных; остальные служат резервом. После выбора нажми «Сохранить и запустить».'
printf ''
printf 'Выбрать интерфейсы (%s)
' "$count"
# Keep saved choices even while netifd/UCI cannot list those interfaces.
{
printf '%s\n' "$current" | tr ' ' '\n'
printf '%s\n' "$interfaces"
} | awk 'NF && !seen[$0]++' | while IFS= read -r iface; do
[ -n "$iface" ] || continue
selected=''
case " $current " in *" $iface "*) selected=' checked' ;; esac
printf '' "$(h "$iface")" "$selected" "$(h "$iface")"
done
printf '
%s
' "$(h "$current")"
}
metric() {
local label value tone
label="$1"
value="$2"
tone="${3:-}"
printf '
%s%s
' "$(h "$tone")" "$(h "$label")" "$(h "$value")"
}
metric_link() {
local label value href
label="$1"
value="$2"
href="$3"
printf '
Действия панели, изменения связи с Hub и WAN, предупреждения и ошибки Xray. Одинаковые события не дублируются. Журнал хранится только в ОЗУ, очищается после перезагрузки и каждые 24 часа. Максимум около 2 МБ. Ключи и пароли скрываются.