#!/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' } 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 'Журнал временно недоступен: не удалось подготовить хранилище или получить блокировку. Настройки роутера не изменены.\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 if "$AGENT" render-client >>"$output" 2>&1; then if /etc/init.d/owrt-remote restart >>"$output" 2>&1; then set_result "Xray установлен, конфигурация проверена" "$(cat "$output")" "ok" else rc=$? set_result "Ошибка перезапуска Xray" "$(cat "$output")" "bad" fi else rc=$? printf '\nrc=%s\nРабочий JSON сохранён. Перезапуск сервиса не выполнен.\n' "$rc" >>"$output" set_result "Xray скачан, но конфигурация не прошла проверку" "$(cat "$output")" "bad" fi else rc=$? set_result "Ошибка установки Xray" "$(cat "$output")" "bad" fi ;; esac if [ "$rc" != "0" ] && [ "$RESULT_KIND" != bad ]; 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 '
%s
%sПерейти
' "$(h "$label")" "$(h "$value")" "$(h "$href")" } render_unauthorized() { http_html cat <<'EOF' OpenWrt Remote

Доступ запрещен

Открой панель из LuCI или по ссылке, которую показал install.sh.

EOF } render_page() { local key router_id router_name hub_url service_state service_tone xray_state xray_tone enabled_checked status_text local vps_host_auto_checked wan_direct_checked vps_host_auto_checked=''; wan_direct_checked='' [ "$(uci_get vps_host_mode manual)" != auto ] || vps_host_auto_checked=checked [ "$(uci_get wan_direct 0)" != 1 ] || wan_direct_checked=checked key="$(param key)" router_id="$(uci_get router_id main)" router_name="$(uci_get router_name "$router_id")" hub_url="$(uci_get hub_url '')" if service_enabled; then service_state="Включен" service_tone="good" else service_state="Выключен" service_tone="warn" fi if xray_running; then xray_state="Запущен" xray_tone="good" else xray_state="Остановлен" xray_tone="bad" fi if [ "$(uci_get enabled 0)" = "1" ]; then enabled_checked="checked" status_text="Агент включен" else enabled_checked="" status_text="Агент выключен" fi http_html cat < OpenWrt Remote Hub v120

OpenWrt Remote Hub v120

Состояние

EOF metric "Сервис procd" "$service_state" "$service_tone" metric "Xray туннель" "$xray_state" "$xray_tone" if [ -n "$hub_url" ]; then metric_link "Hub URL" "$hub_url" "$hub_url" else metric "Hub URL" "не задан" "linkMetric" fi cat <
Скачать Xray config
EOF if [ -n "$RESULT_TITLE" ]; then printf '
%s\n%s
' "$(h "$RESULT_KIND")" "$(h "$RESULT_TITLE")" "$(h "$RESULT_BODY")" fi if [ "$SHOW_XRAY_SETTINGS" = "1" ]; then cat <

Xray настройки

Вставь сюда блок команд из OpenWrt config на VPS. Роутер сам применит UCI, пересоберет Xray config, включит сервис и отправит heartbeat.

EOF fi cat <

Настройки роутера

EOF field router_id "Router ID" text "Уникальное имя этого роутера в VPS-панели. Бери из карточки роутера на VPS: main, office-1, shop-2." field router_name "Название" text "Красивое имя для карточки на VPS. Можно писать по-русски: Главный роутер, Дом, Офис." field role "Роль" text "main ставь для главного роутера. node ставь для дополнительных роутеров, которые просто цепляешь и мониторишь." field public_url "Public URL" text "Обычно оставь пустым. Нужно только если у роутера уже есть своя готовая публичная ссылка." field hub_url "Hub URL" text "Адрес веб-панели на VPS, куда роутер отправляет online/offline. Бери из VPS, например http://VPS_IP:8088." field hub_token "Hub token" password "Секрет AGENT_TOKEN из VPS-хаба. Его показывает команда init/serve на VPS; нужен для heartbeat." field heartbeat_interval "Heartbeat, секунд" number "Как часто роутер сообщает VPS, что он online. Обычно 30 секунд, меньше 10 не ставь." field xray_bin "Xray binary" text "Путь к Xray на роутере. Если ставил пакет xray-core, обычно оставь /usr/bin/xray." field xray_config "Xray config" text "Куда агент сохранит клиентский Xray-конфиг. Обычно оставь /etc/xray/owrt-remote-client.json." field vps_host "VPS host" text "IP или домен VPS, куда Xray роутера подключается reverse-туннелем. Бери IP/домен своего VPS." cat < Автоматически обновлять VPS host Управляет только адресом Xray: выключено — VPS host сохраняется; включено — Hub может изменить его и перезапустить Xray. Hub URL настраивается отдельно. Heartbeat и Xray обходят Podkop. DNS берётся с WAN, настройки LAN не меняются. EOF wan_interface_field field wan_dns "WAN DNS" text "Необязательно: IP DNS-сервера для Remote. Пустое поле — DNS от провайдера на WAN." field vps_port "VPS Xray port" number "Порт Xray на VPS для reverse-туннеля. Должен совпадать с render-xray на VPS, обычно 8443." field vless_uuid "VLESS UUID" text "Уникальный UUID роутера. Бери из карточки роутера на VPS или из команды print-openwrt-config." field vless_encryption "VLESS encryption" text "Для этой схемы оставь none. Меняй только если сам меняешь Xray-конфиг на VPS." field vless_flow "VLESS flow" text "Обычно оставь пустым. Нужно только для специальных режимов Xray." field reverse_tag "Reverse tag" text "Метка reverse-туннеля внутри Xray. Обычно оставь reverse-in, если на VPS не задавал другое." field ssh_vless_uuid "SSH VLESS UUID" text "UUID отдельного SSH reverse-туннеля. Бери из OpenWrt config на VPS для этого роутера." field ssh_reverse_tag "SSH reverse tag" text "Метка reverse-туннеля для SSH. Обычно reverse-in-ssh." field admin_host "Admin host" text "Куда внутри роутера вести админку LuCI. Обычно 127.0.0.1, потому что uhttpd слушает локально." field admin_port "Admin port" number "Порт LuCI/uhttpd внутри роутера. Обычно 80; если LuCI на другом порту, укажи его." field ssh_host "SSH host" text "Куда внутри роутера вести SSH. Обычно 127.0.0.1." field ssh_port "SSH port" number "Порт Dropbear/SSH внутри роутера. Обычно 22." cat <
EOF } read_request if ! authorized; then render_unauthorized exit 0 fi action="$(param action)" case "$action" in logs_download) logs_response download; exit 0 ;; logs_live) logs_response live; exit 0 ;; logs_clear) logs_response clear; exit 0 ;; esac if [ "${REQUEST_METHOD:-GET}" = POST ] && [ -n "$action" ] && [ -r "$LOG_HELPER" ]; then printf '' | sh "$LOG_HELPER" event "Панель: действие=$action; начало" >/dev/null 2>&1 || true elif [ "${REQUEST_METHOD:-GET}" = GET ] && [ -z "$action" ] && [ -r "$LOG_HELPER" ]; then printf '' | sh "$LOG_HELPER" event 'Панель: открыта' >/dev/null 2>&1 || true fi if [ "$action" = "download_config" ]; then http_json "$AGENT" render-client --stdout 2>&1 exit 0 fi if [ "${REQUEST_METHOD:-GET}" = "POST" ]; then case "$action" in save) save_config ;; save_start) if save_config; then run_action start; fi ;; show_xray_settings) SHOW_XRAY_SETTINGS="1" ;; apply_xray_settings) apply_xray_settings ;; clear_config) clear_config ;; start|stop|restart|heartbeat|doctor|install_xray_tmp) run_action "$action" ;; esac fi render_page