Add OpenWrt remote hub
This commit is contained in:
1 parent
48cba62f21
commit
38a92b0b1f
19 files changed
+2080
-2123
No files matched your search
@@ -1,889 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
BACKEND="${BACKEND:-/usr/sbin/owrt-full-backup}"
|
||||
KEY_FILE="${KEY_FILE:-/etc/owrt-full-backup/web.key}"
|
||||
PARAMS_FILE="${TMPDIR:-/tmp}/owrt-full-backup-cgi.$$"
|
||||
RESULT_FILE=""
|
||||
RESULT_TITLE=""
|
||||
RESULT_CODE=""
|
||||
JOB_DIR="${JOB_DIR:-/tmp/owrt-full-backup-jobs}"
|
||||
ACTIVE_JOB=""
|
||||
PROJECT_URL="${PROJECT_URL:-https://github.com/kzolotarev95/luci-app-owrt-full-backup}"
|
||||
RAW_URL="${RAW_URL:-https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-full-backup/main}"
|
||||
|
||||
cleanup() {
|
||||
rm -f "$PARAMS_FILE"
|
||||
if [ -n "$RESULT_FILE" ]; then
|
||||
rm -f "$RESULT_FILE"
|
||||
fi
|
||||
}
|
||||
|
||||
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')"
|
||||
value="$(url_decode "$value" | tr '\r\n\t' ' ')"
|
||||
[ -n "$key" ] && printf '%s\t%s\n' "$key" "$value" >>"$PARAMS_FILE"
|
||||
done
|
||||
IFS="$old_ifs"
|
||||
}
|
||||
|
||||
param() {
|
||||
awk -F ' ' -v k="$1" '$1 == k { print $2; exit }' "$PARAMS_FILE"
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
config_get() {
|
||||
local key default value
|
||||
key="$1"
|
||||
default="$2"
|
||||
if command -v uci >/dev/null 2>&1; then
|
||||
value="$(uci -q get "fullbackup.main.$key" 2>/dev/null || true)"
|
||||
[ -n "$value" ] && {
|
||||
printf '%s' "$value"
|
||||
return
|
||||
}
|
||||
fi
|
||||
printf '%s' "$default"
|
||||
}
|
||||
|
||||
web_key() {
|
||||
cat "$KEY_FILE" 2>/dev/null
|
||||
}
|
||||
|
||||
self_url() {
|
||||
printf '%s' "${SCRIPT_NAME:-/cgi-bin/owrt-full-backup}"
|
||||
}
|
||||
|
||||
authorized() {
|
||||
local expected supplied
|
||||
expected="$(web_key)"
|
||||
supplied="$(param key)"
|
||||
[ -n "$expected" ] && [ "$supplied" = "$expected" ]
|
||||
}
|
||||
|
||||
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_unauthorized() {
|
||||
http_html
|
||||
cat <<'EOF'
|
||||
<!doctype html><html><head><meta charset="utf-8"><title>OpenWrt Full Backup</title></head>
|
||||
<body><h1>Доступ запрещен</h1><p>Открой панель по секретной ссылке, которую показал install.sh.</p></body></html>
|
||||
EOF
|
||||
}
|
||||
|
||||
valid_abs_path() {
|
||||
case "$1" in
|
||||
/*) ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
printf '%s' "$1" | grep -Eq '^/[A-Za-z0-9._/-]+$'
|
||||
}
|
||||
|
||||
valid_job_id() {
|
||||
case "$1" in
|
||||
''|*[!A-Za-z0-9._-]*) return 1 ;;
|
||||
*) return 0 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
shell_quote() {
|
||||
printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
|
||||
}
|
||||
|
||||
job_file() {
|
||||
printf '%s/%s.%s' "$JOB_DIR" "$1" "$2"
|
||||
}
|
||||
|
||||
format_seconds() {
|
||||
local seconds minutes rest
|
||||
seconds="$1"
|
||||
case "$seconds" in ''|*[!0-9]*) seconds=0 ;; esac
|
||||
minutes="$((seconds / 60))"
|
||||
rest="$((seconds % 60))"
|
||||
if [ "$minutes" -gt 0 ]; then
|
||||
printf '%s мин %s сек' "$minutes" "$rest"
|
||||
else
|
||||
printf '%s сек' "$rest"
|
||||
fi
|
||||
}
|
||||
|
||||
localize_log() {
|
||||
sed \
|
||||
-e 's/^Старт: /Начало: /' \
|
||||
-e 's/^Код выхода: 0$/Готово./' \
|
||||
-e 's/Sun/Вс/g' -e 's/Mon/Пн/g' -e 's/Tue/Вт/g' -e 's/Wed/Ср/g' -e 's/Thu/Чт/g' -e 's/Fri/Пт/g' -e 's/Sat/Сб/g' \
|
||||
-e 's/Jan/Янв/g' -e 's/Feb/Фев/g' -e 's/Mar/Мар/g' -e 's/Apr/Апр/g' -e 's/May/Май/g' -e 's/Jun/Июн/g' \
|
||||
-e 's/Jul/Июл/g' -e 's/Aug/Авг/g' -e 's/Sep/Сен/g' -e 's/Oct/Окт/g' -e 's/Nov/Ноя/g' -e 's/Dec/Дек/g'
|
||||
}
|
||||
|
||||
download_file() {
|
||||
local file base
|
||||
file="$(param file)"
|
||||
valid_abs_path "$file" || {
|
||||
http_html
|
||||
printf '<p>Неверный путь к файлу.</p>'
|
||||
exit 0
|
||||
}
|
||||
case "$file" in
|
||||
*.tar.gz|*.tar.gz.sha256) ;;
|
||||
*) http_html; printf '<p>Скачать можно только архивы бэкапа и checksum-файлы.</p>'; exit 0 ;;
|
||||
esac
|
||||
[ -f "$file" ] || {
|
||||
http_html
|
||||
printf '<p>Файл не найден.</p>'
|
||||
exit 0
|
||||
}
|
||||
base="$(basename "$file")"
|
||||
case "$file" in
|
||||
*.sha256) printf 'Content-Type: text/plain\r\n' ;;
|
||||
*) printf 'Content-Type: application/gzip\r\n' ;;
|
||||
esac
|
||||
printf 'Content-Disposition: attachment; filename="%s"\r\n\r\n' "$base"
|
||||
cat "$file"
|
||||
exit 0
|
||||
}
|
||||
|
||||
handle_delete_backup() {
|
||||
local file confirm
|
||||
file="$(param file)"
|
||||
confirm="$(param confirm)"
|
||||
RESULT_TITLE="Удаление бэкапа"
|
||||
RESULT_FILE="${TMPDIR:-/tmp}/owrt-full-backup-result.$$"
|
||||
|
||||
if [ "$confirm" != "DELETE" ]; then
|
||||
RESULT_CODE=2
|
||||
printf 'Для удаления введи DELETE.\n' >"$RESULT_FILE"
|
||||
return
|
||||
fi
|
||||
|
||||
valid_abs_path "$file" || {
|
||||
RESULT_CODE=2
|
||||
printf 'Неверный путь к файлу.\n' >"$RESULT_FILE"
|
||||
return
|
||||
}
|
||||
|
||||
case "$file" in
|
||||
*.tar.gz|*.tar.gz.sha256) ;;
|
||||
*)
|
||||
RESULT_CODE=2
|
||||
printf 'Удалять можно только архивы бэкапа и checksum-файлы.\n' >"$RESULT_FILE"
|
||||
return
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ ! -f "$file" ]; then
|
||||
RESULT_TITLE="Бэкап уже удален"
|
||||
RESULT_CODE=0
|
||||
printf 'Архив уже удален или его нет в папке: %s\n' "$file" >"$RESULT_FILE"
|
||||
return
|
||||
fi
|
||||
|
||||
if rm -f "$file" "$file.sha256" 2>"$RESULT_FILE"; then
|
||||
RESULT_TITLE="Бэкап удален"
|
||||
RESULT_CODE=0
|
||||
printf 'Удалено: %s\n' "$file" >"$RESULT_FILE"
|
||||
else
|
||||
RESULT_CODE=1
|
||||
printf 'Не удалось удалить: %s\n' "$file" >>"$RESULT_FILE"
|
||||
fi
|
||||
}
|
||||
|
||||
handle_upload_backup() {
|
||||
RESULT_TITLE="Загрузка архива"
|
||||
RESULT_FILE="${TMPDIR:-/tmp}/owrt-full-backup-result.$$"
|
||||
|
||||
if ! command -v owrt-full-backup-upload >/dev/null 2>&1; then
|
||||
RESULT_CODE=127
|
||||
printf 'Помощник загрузки не установлен: owrt-full-backup-upload\n' >"$RESULT_FILE"
|
||||
return
|
||||
fi
|
||||
|
||||
owrt-full-backup-upload "$(config_get output_dir /tmp)" >"$RESULT_FILE" 2>&1
|
||||
RESULT_CODE="$?"
|
||||
}
|
||||
|
||||
start_backend_job() {
|
||||
local title id started log status meta script cmd arg
|
||||
title="$1"
|
||||
shift
|
||||
|
||||
if [ ! -x "$BACKEND" ]; then
|
||||
RESULT_TITLE="$title"
|
||||
RESULT_CODE=127
|
||||
RESULT_FILE="${TMPDIR:-/tmp}/owrt-full-backup-result.$$"
|
||||
printf 'Backend не установлен: %s\n' "$BACKEND" >"$RESULT_FILE"
|
||||
return
|
||||
fi
|
||||
|
||||
mkdir -p "$JOB_DIR"
|
||||
id="$(date +%s)-$$"
|
||||
started="$(date +%s)"
|
||||
log="$(job_file "$id" log)"
|
||||
status="$(job_file "$id" status)"
|
||||
meta="$(job_file "$id" meta)"
|
||||
script="$(job_file "$id" sh)"
|
||||
|
||||
ACTIVE_JOB="$id"
|
||||
printf 'running\n' >"$status"
|
||||
{
|
||||
printf 'title=%s\n' "$title"
|
||||
printf 'started=%s\n' "$started"
|
||||
} >"$meta"
|
||||
|
||||
cmd="$(shell_quote "$BACKEND")"
|
||||
for arg in "$@"; do
|
||||
cmd="$cmd $(shell_quote "$arg")"
|
||||
done
|
||||
|
||||
cat >"$script" <<EOF
|
||||
#!/bin/sh
|
||||
echo "Начало: \$(date '+%d.%m.%Y %H:%M:%S')"
|
||||
echo "Создание бэкапа запущено."
|
||||
$cmd
|
||||
code="\$?"
|
||||
echo "\$code" > "$(job_file "$id" code)"
|
||||
date +%s > "$(job_file "$id" finished)"
|
||||
if [ "\$code" = "0" ]; then
|
||||
echo "Готово."
|
||||
echo done > "$status"
|
||||
else
|
||||
echo "Ошибка: код выхода \$code"
|
||||
echo failed > "$status"
|
||||
fi
|
||||
rm -f "$script"
|
||||
EOF
|
||||
chmod 0700 "$script"
|
||||
if command -v start-stop-daemon >/dev/null 2>&1 && start-stop-daemon -S -b -x /bin/sh -- "$script" >"$log" 2>&1; then
|
||||
:
|
||||
elif command -v setsid >/dev/null 2>&1; then
|
||||
setsid sh "$script" >"$log" 2>&1 </dev/null &
|
||||
elif command -v nohup >/dev/null 2>&1; then
|
||||
nohup sh "$script" >"$log" 2>&1 </dev/null &
|
||||
else
|
||||
sh "$script" >"$log" 2>&1 </dev/null &
|
||||
fi
|
||||
}
|
||||
|
||||
run_backend() {
|
||||
RESULT_TITLE="$1"
|
||||
shift
|
||||
RESULT_FILE="${TMPDIR:-/tmp}/owrt-full-backup-result.$$"
|
||||
if [ ! -x "$BACKEND" ]; then
|
||||
RESULT_CODE=127
|
||||
printf 'Backend не установлен: %s\n' "$BACKEND" >"$RESULT_FILE"
|
||||
return
|
||||
fi
|
||||
"$BACKEND" "$@" >"$RESULT_FILE" 2>&1
|
||||
RESULT_CODE="$?"
|
||||
}
|
||||
|
||||
handle_create() {
|
||||
local output_dir name firmware
|
||||
output_dir="$(param output_dir)"
|
||||
name="$(param name)"
|
||||
firmware="$(param firmware_image)"
|
||||
[ -n "$output_dir" ] || output_dir="$(config_get output_dir /tmp)"
|
||||
valid_abs_path "$output_dir" || {
|
||||
RESULT_TITLE="Создание бэкапа"
|
||||
RESULT_CODE=2
|
||||
RESULT_FILE="${TMPDIR:-/tmp}/owrt-full-backup-result.$$"
|
||||
printf 'Неверная папка для архива. Используй абсолютный путь, например /mnt/usb.\n' >"$RESULT_FILE"
|
||||
return
|
||||
}
|
||||
|
||||
set -- create -o "$output_dir"
|
||||
[ -n "$name" ] && set -- "$@" -n "$name"
|
||||
has_param include_overlay || set -- "$@" --no-overlay
|
||||
has_param include_rom && set -- "$@" --include-rom
|
||||
has_param include_raw_mtd && set -- "$@" --include-raw-mtd
|
||||
[ -n "$firmware" ] && set -- "$@" --firmware-image "$firmware"
|
||||
start_backend_job "Создание бэкапа" "$@"
|
||||
}
|
||||
|
||||
handle_inspect() {
|
||||
local archive
|
||||
archive="$(param archive)"
|
||||
valid_abs_path "$archive" || {
|
||||
RESULT_TITLE="Просмотр архива"
|
||||
RESULT_CODE=2
|
||||
RESULT_FILE="${TMPDIR:-/tmp}/owrt-full-backup-result.$$"
|
||||
printf 'Неверный путь к архиву.\n' >"$RESULT_FILE"
|
||||
return
|
||||
}
|
||||
run_backend "Просмотр архива" inspect "$archive"
|
||||
}
|
||||
|
||||
handle_restore() {
|
||||
local archive confirm
|
||||
archive="$(param archive)"
|
||||
confirm="$(param confirm)"
|
||||
if [ "$confirm" != "RESTORE" ]; then
|
||||
RESULT_TITLE="Восстановление"
|
||||
RESULT_CODE=2
|
||||
RESULT_FILE="${TMPDIR:-/tmp}/owrt-full-backup-result.$$"
|
||||
printf 'Для подтверждения введи RESTORE.\n' >"$RESULT_FILE"
|
||||
return
|
||||
fi
|
||||
valid_abs_path "$archive" || {
|
||||
RESULT_TITLE="Восстановление"
|
||||
RESULT_CODE=2
|
||||
RESULT_FILE="${TMPDIR:-/tmp}/owrt-full-backup-result.$$"
|
||||
printf 'Неверный путь к архиву.\n' >"$RESULT_FILE"
|
||||
return
|
||||
}
|
||||
|
||||
set -- restore "$archive" --yes
|
||||
has_param restore_configs || set -- "$@" --no-configs
|
||||
has_param restore_packages || set -- "$@" --no-packages
|
||||
has_param restore_overlay && set -- "$@" --overlay
|
||||
has_param flash_firmware && set -- "$@" --flash-firmware
|
||||
run_backend "Восстановление" "$@"
|
||||
}
|
||||
|
||||
handle_save_defaults() {
|
||||
local output_dir include_overlay include_rom include_raw_mtd keep_days
|
||||
RESULT_TITLE="Сохранение настроек"
|
||||
RESULT_CODE=0
|
||||
RESULT_FILE="${TMPDIR:-/tmp}/owrt-full-backup-result.$$"
|
||||
output_dir="$(param default_output_dir)"
|
||||
keep_days="$(param keep_days)"
|
||||
valid_abs_path "$output_dir" || {
|
||||
RESULT_CODE=2
|
||||
printf 'Неверная папка для архива.\n' >"$RESULT_FILE"
|
||||
return
|
||||
}
|
||||
case "$keep_days" in ''|*[!0-9]*) keep_days=0 ;; esac
|
||||
has_param default_include_overlay && include_overlay=1 || include_overlay=0
|
||||
has_param default_include_rom && include_rom=1 || include_rom=0
|
||||
has_param default_include_raw_mtd && include_raw_mtd=1 || include_raw_mtd=0
|
||||
|
||||
if command -v uci >/dev/null 2>&1; then
|
||||
uci -q batch <<EOF >"$RESULT_FILE" 2>&1
|
||||
set fullbackup.main=backup
|
||||
set fullbackup.main.output_dir='$output_dir'
|
||||
set fullbackup.main.include_overlay='$include_overlay'
|
||||
set fullbackup.main.include_rom='$include_rom'
|
||||
set fullbackup.main.include_raw_mtd='$include_raw_mtd'
|
||||
set fullbackup.main.keep_days='$keep_days'
|
||||
commit fullbackup
|
||||
EOF
|
||||
RESULT_CODE="$?"
|
||||
[ "$RESULT_CODE" = "0" ] && printf 'Настройки сохранены.\n' >>"$RESULT_FILE"
|
||||
else
|
||||
RESULT_CODE=127
|
||||
printf 'Команда uci не найдена.\n' >"$RESULT_FILE"
|
||||
fi
|
||||
}
|
||||
|
||||
handle_action() {
|
||||
local action
|
||||
action="$(param action)"
|
||||
case "$action" in
|
||||
create) handle_create ;;
|
||||
inspect) handle_inspect ;;
|
||||
restore) handle_restore ;;
|
||||
save_defaults) handle_save_defaults ;;
|
||||
delete_backup) handle_delete_backup ;;
|
||||
upload_backup) handle_upload_backup ;;
|
||||
esac
|
||||
}
|
||||
|
||||
system_value() {
|
||||
local value
|
||||
case "$1" in
|
||||
host)
|
||||
if command -v uci >/dev/null 2>&1; then
|
||||
value="$(uci -q get system.@system[0].hostname 2>/dev/null || true)"
|
||||
[ -n "$value" ] && {
|
||||
printf '%s' "$value"
|
||||
return
|
||||
}
|
||||
fi
|
||||
hostname 2>/dev/null || printf 'openwrt'
|
||||
;;
|
||||
release)
|
||||
if [ -r /etc/openwrt_release ]; then
|
||||
. /etc/openwrt_release 2>/dev/null
|
||||
printf '%s %s' "${DISTRIB_ID:-OpenWrt}" "${DISTRIB_RELEASE:-unknown}"
|
||||
else
|
||||
printf 'OpenWrt unknown'
|
||||
fi
|
||||
;;
|
||||
board)
|
||||
if [ -r /tmp/sysinfo/board_name ]; then
|
||||
cat /tmp/sysinfo/board_name
|
||||
else
|
||||
printf 'unknown'
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
storage_widgets() {
|
||||
local fs size used avail pct mount usage label
|
||||
df -h 2>/dev/null | awk 'NR > 1 { print }' | while read -r fs size used avail pct mount; do
|
||||
[ -n "$mount" ] || continue
|
||||
usage="${pct%%%}"
|
||||
case "$usage" in ''|*[!0-9]*) usage=0 ;; esac
|
||||
[ "$usage" -gt 100 ] 2>/dev/null && usage=100
|
||||
case "$mount" in
|
||||
/) label="Корневой раздел /" ;;
|
||||
/rom) label="Раздел прошивки /rom" ;;
|
||||
/tmp) label="Временная память /tmp" ;;
|
||||
/overlay) label="Изменяемый раздел /overlay" ;;
|
||||
/dev) label="Служебный раздел /dev" ;;
|
||||
*) label="Раздел $mount" ;;
|
||||
esac
|
||||
printf '<div class="disk-widget">'
|
||||
printf '<div class="disk-top"><div><strong>%s</strong><span>%s</span></div><b>%s</b></div>' "$(h "$label")" "$(h "$fs")" "$(h "$pct")"
|
||||
printf '<div class="meter"><span style="width:%s%%"></span></div>' "$usage"
|
||||
printf '<div class="disk-meta"><span>Занято: %s</span><span>Свободно: %s</span><span>Всего: %s</span></div>' "$(h "$used")" "$(h "$avail")" "$(h "$size")"
|
||||
printf '</div>'
|
||||
done
|
||||
}
|
||||
|
||||
temperature_widgets() {
|
||||
local path raw whole frac label printed type_path name_path
|
||||
printed=0
|
||||
for path in /sys/class/thermal/thermal_zone*/temp /sys/class/hwmon/hwmon*/temp*_input; do
|
||||
[ -r "$path" ] || continue
|
||||
raw="$(cat "$path" 2>/dev/null | tr -dc '0-9')"
|
||||
[ -n "$raw" ] || continue
|
||||
case "$raw" in *[!0-9]*) continue ;; esac
|
||||
if [ "$raw" -ge 1000 ] 2>/dev/null; then
|
||||
whole="$((raw / 1000))"
|
||||
frac="$(((raw % 1000) / 100))"
|
||||
else
|
||||
whole="$raw"
|
||||
frac=0
|
||||
fi
|
||||
label="Датчик температуры"
|
||||
type_path="${path%/temp}/type"
|
||||
name_path="${path%/temp*_input}/name"
|
||||
if [ -r "$type_path" ]; then
|
||||
label="$(cat "$type_path" 2>/dev/null | sed -n '1p')"
|
||||
elif [ -r "$name_path" ]; then
|
||||
label="$(cat "$name_path" 2>/dev/null | sed -n '1p')"
|
||||
fi
|
||||
printed=1
|
||||
printf '<div class="temp-widget"><div><strong>%s</strong><span>%s</span></div><b>%s.%s °C</b></div>' "$(h "$label")" "$(h "$path")" "$(h "$whole")" "$(h "$frac")"
|
||||
done
|
||||
[ "$printed" = "1" ] || printf '<p class="muted">Датчик температуры не найден.</p>'
|
||||
}
|
||||
|
||||
checkbox_attr() {
|
||||
[ "$1" = "1" ] && printf ' checked'
|
||||
}
|
||||
|
||||
backup_rows() {
|
||||
local dir key file base size mtime
|
||||
dir="$(config_get output_dir /tmp)"
|
||||
key="$(h "$(param key)")"
|
||||
[ -d "$dir" ] || {
|
||||
printf '<tr><td colspan="4">Папка для архивов не существует.</td></tr>'
|
||||
return
|
||||
}
|
||||
for file in "$dir"/*-owrt-full-backup.tar.gz; do
|
||||
[ -f "$file" ] || continue
|
||||
base="$(basename "$file")"
|
||||
size="$(ls -lh "$file" 2>/dev/null | awk '{print $5}')"
|
||||
mtime="$(ls -l "$file" 2>/dev/null | awk '{print $6" "$7" "$8}')"
|
||||
printf '<tr><td><code>%s</code></td><td>%s</td><td>%s</td><td class="actions"><a class="button small" href="%s?key=%s&action=download&file=%s">Скачать</a><form method="post" action="%s" onsubmit="return confirm('"'"'Удалить этот бэкап?'"'"');"><input type="hidden" name="key" value="%s"><input type="hidden" name="action" value="delete_backup"><input type="hidden" name="file" value="%s"><input type="hidden" name="confirm" value="DELETE"><button class="danger small" type="submit">Удалить</button></form></td></tr>' \
|
||||
"$(h "$base")" "$(h "$size")" "$(h "$mtime")" "$(self_url)" "$key" "$(h "$file")" "$(self_url)" "$key" "$(h "$file")"
|
||||
done
|
||||
}
|
||||
|
||||
render_job_panel() {
|
||||
local id status meta log code_file finished_file started finished now elapsed elapsed_text title state_class state_text job_note button_text code estimate_text
|
||||
id="$1"
|
||||
valid_job_id "$id" || return
|
||||
|
||||
status="$(cat "$(job_file "$id" status)" 2>/dev/null || printf 'missing')"
|
||||
meta="$(job_file "$id" meta)"
|
||||
log="$(job_file "$id" log)"
|
||||
code_file="$(job_file "$id" code)"
|
||||
finished_file="$(job_file "$id" finished)"
|
||||
started="$(sed -n 's/^started=//p' "$meta" 2>/dev/null | sed -n '1p')"
|
||||
title="$(sed -n 's/^title=//p' "$meta" 2>/dev/null | sed -n '1p')"
|
||||
code="$(cat "$code_file" 2>/dev/null | sed -n '1p')"
|
||||
finished="$(cat "$finished_file" 2>/dev/null | sed -n '1p')"
|
||||
[ -n "$title" ] || title="Создание бэкапа"
|
||||
case "$started" in ''|*[!0-9]*) started="$(date +%s)" ;; esac
|
||||
now="$(date +%s)"
|
||||
if [ "$status" != "running" ]; then
|
||||
case "$finished" in
|
||||
''|*[!0-9]*) ;;
|
||||
*) [ "$finished" -ge "$started" ] 2>/dev/null && now="$finished" ;;
|
||||
esac
|
||||
fi
|
||||
elapsed="$((now - started))"
|
||||
elapsed_text="$(format_seconds "$elapsed")"
|
||||
estimate_text=""
|
||||
|
||||
case "$status" in
|
||||
running)
|
||||
state_class="running"
|
||||
state_text="Выполняется"
|
||||
estimate_text="Примерно: 1-3 мин"
|
||||
job_note="Страница обновляется каждые 2 секунды. Время примерное: большой overlay, ROM или медленная флешка могут идти дольше."
|
||||
button_text="Обновить лог"
|
||||
;;
|
||||
done)
|
||||
state_class="ok"
|
||||
state_text="Завершено"
|
||||
job_note="Готово. Архив уже появился в списке ниже."
|
||||
button_text="Обновить список"
|
||||
;;
|
||||
failed)
|
||||
state_class="error"
|
||||
state_text="Ошибка"
|
||||
job_note="Создание бэкапа завершилось с ошибкой. Подробности в журнале ниже."
|
||||
button_text="Обновить список"
|
||||
;;
|
||||
*)
|
||||
state_class="error"
|
||||
state_text="Задача не найдена"
|
||||
job_note="Эта задача уже недоступна. Можно обновить страницу и посмотреть список архивов."
|
||||
button_text="Обновить список"
|
||||
;;
|
||||
esac
|
||||
|
||||
printf '<section class="panel span6 job-card %s">' "$state_class"
|
||||
printf '<div class="section-head"><div><h2>%s</h2><p>Статус: %s · Время: <span id="job-timer" data-start="%s">%s</span>' "$(h "$title")" "$(h "$state_text")" "$(h "$started")" "$(h "$elapsed_text")"
|
||||
if [ -n "$estimate_text" ]; then
|
||||
printf ' · <span class="hot-text">%s</span>' "$(h "$estimate_text")"
|
||||
fi
|
||||
if [ -n "$code" ] && [ "$code" != "0" ]; then
|
||||
printf ' · Код ошибки: %s' "$(h "$code")"
|
||||
fi
|
||||
printf '</p></div><a class="button small" href="%s?key=%s">%s</a></div>' "$(self_url)" "$(h "$(param key)")" "$button_text"
|
||||
printf '<p>%s</p><div class="console-title">Журнал выполнения</div>' "$(h "$job_note")"
|
||||
printf '<pre class="console">'
|
||||
if [ -r "$log" ]; then
|
||||
tail -n 120 "$log" | localize_log | html_escape
|
||||
else
|
||||
printf 'Лог пока пуст. Подожди пару секунд.\n' | html_escape
|
||||
fi
|
||||
printf '</pre>'
|
||||
if [ "$status" = "running" ]; then
|
||||
printf '<script>(function(){var el=document.getElementById("job-timer");if(!el)return;var start=parseInt(el.dataset.start,10)||0;function fmt(s){s=Math.max(0,s|0);var m=Math.floor(s/60),r=s%%60;return m>0?m+" мин "+r+" сек":r+" сек";}function tick(){var now=Math.floor(Date.now()/1000);el.textContent=fmt(now-start);}tick();setInterval(tick,1000);}());</script>'
|
||||
fi
|
||||
printf '</section>'
|
||||
}
|
||||
|
||||
page() {
|
||||
local key output_dir include_overlay include_rom include_raw_mtd keep_days job_id job_status refresh_meta result_class result_status
|
||||
key="$(h "$(param key)")"
|
||||
output_dir="$(config_get output_dir /tmp)"
|
||||
include_overlay="$(config_get include_overlay 1)"
|
||||
include_rom="$(config_get include_rom 0)"
|
||||
include_raw_mtd="$(config_get include_raw_mtd 0)"
|
||||
keep_days="$(config_get keep_days 0)"
|
||||
job_id="$ACTIVE_JOB"
|
||||
if [ -z "$job_id" ] && valid_job_id "$(param job)"; then
|
||||
job_id="$(param job)"
|
||||
fi
|
||||
job_status=""
|
||||
refresh_meta=""
|
||||
if [ -n "$job_id" ] && valid_job_id "$job_id"; then
|
||||
job_status="$(cat "$(job_file "$job_id" status)" 2>/dev/null || true)"
|
||||
if [ "$job_status" = "running" ]; then
|
||||
refresh_meta="<meta http-equiv=\"refresh\" content=\"2;url=$(self_url)?key=$key&job=$job_id\">"
|
||||
fi
|
||||
fi
|
||||
|
||||
http_html
|
||||
cat <<EOF
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
$refresh_meta
|
||||
<title>OpenWrt Full Backup</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; --bg: #f6f7f9; --panel: #fff; --text: #15181c; --muted: #667085; --line: #d9dee7; --accent: #16a34a; --accent-hover: #15803d; --button-text: #fff; --bad: #dc2626; --bad-hover: #b91c1c; --ok: #067647; --hot: #dc2626; --warn: #eab308; }
|
||||
@media (prefers-color-scheme: dark) { :root { --bg: #111418; --panel: #181d23; --text: #eef2f6; --muted: #a6b0bf; --line: #2d3642; --accent: #16a34a; --accent-hover: #15803d; --button-text: #fff; --bad: #dc2626; --bad-hover: #b91c1c; --ok: #7ee0a3; --hot: #dc2626; --warn: #eab308; } }
|
||||
* { box-sizing: border-box; }
|
||||
html { min-height: 100%; }
|
||||
body { margin: 0; overflow-x: hidden; background: var(--bg); color: var(--text); font: 14px/1.45 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
|
||||
main { max-width: 1280px; margin: 0 auto; padding: 18px; display: grid; gap: 14px; transform: scale(.9); transform-origin: top center; }
|
||||
h1 { margin: 0; font-size: 22px; }
|
||||
h2 { margin: 0 0 12px; font-size: 16px; }
|
||||
p { margin: 6px 0; color: var(--muted); }
|
||||
.hero { padding: 16px 18px; }
|
||||
.hero h1 { font-size: 24px; line-height: 1.15; }
|
||||
.hero p { max-width: 680px; margin-top: 8px; }
|
||||
.hero-top { display: flex; align-items: center; justify-content: space-between; gap: 14px; flex-wrap: wrap; }
|
||||
.brand-block { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
||||
.brand-logo { min-width: 74px; min-height: 34px; border-radius: 7px; background: linear-gradient(135deg, var(--accent), var(--accent-hover)); color: var(--button-text); display: inline-flex; align-items: center; justify-content: center; font-weight: 800; letter-spacing: .2px; }
|
||||
.brand-text { min-width: 0; }
|
||||
.brand-links { display: flex; flex-wrap: wrap; gap: 9px; margin-top: 5px; }
|
||||
.brand-links a { color: var(--accent); font-weight: 700; text-decoration: none; }
|
||||
.brand-links a:hover { color: var(--accent-hover); text-decoration: underline; }
|
||||
.hero-top .button { min-height: 34px; }
|
||||
.hero .pill { background: rgba(127,127,127,.08); color: var(--text); }
|
||||
.hot-text { color: var(--hot); }
|
||||
.warn-text { color: var(--warn); }
|
||||
.hint { font-size: 12px; color: var(--muted); margin-top: 8px; }
|
||||
.warn-hint { color: var(--warn); }
|
||||
.grid { display: grid; gap: 14px; grid-template-columns: repeat(12, 1fr); }
|
||||
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 14px; }
|
||||
.span4 { grid-column: span 4; }
|
||||
.span6 { grid-column: span 6; }
|
||||
.span8 { grid-column: span 8; }
|
||||
.span12 { grid-column: span 12; }
|
||||
label { display: block; margin: 9px 0 4px; font-weight: 600; }
|
||||
input[type=text], input[type=number] { width: 100%; border: 1px solid var(--line); border-radius: 6px; background: transparent; color: var(--text); padding: 9px; }
|
||||
.checks label { font-weight: 500; display: flex; gap: 8px; align-items: center; margin: 8px 0; }
|
||||
button, .button { display: inline-flex; align-items: center; justify-content: center; min-height: 36px; border: 0; border-radius: 6px; background: var(--accent); color: var(--button-text); padding: 8px 12px; text-decoration: none; font-weight: 700; cursor: pointer; }
|
||||
button:hover, .button:hover { background: var(--accent-hover); }
|
||||
.small { min-height: 30px; padding: 6px 9px; font-size: 12px; }
|
||||
.danger { background: var(--bad); color: #fff; }
|
||||
.danger:hover { background: var(--bad-hover); }
|
||||
.restore-submit { margin-top: 12px; }
|
||||
.muted { color: var(--muted); }
|
||||
.file-input { width: 100%; border: 1px dashed var(--line); border-radius: 6px; padding: 12px; color: var(--muted); }
|
||||
.result-card, .job-card { border-left: 4px solid var(--accent); }
|
||||
.result-card.ok, .job-card.ok { border-left-color: var(--ok); }
|
||||
.result-card.error, .job-card.error { border-left-color: var(--bad); }
|
||||
.job-card.running { border-left-color: var(--accent); }
|
||||
.result-output, .console { white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; }
|
||||
.console { max-height: 340px; }
|
||||
.console-title { margin: 12px 0 6px; font-weight: 700; }
|
||||
.device-card { min-width: 0; }
|
||||
.device-body { display: grid; gap: 14px; margin-top: 12px; }
|
||||
.device-section h3 { margin: 0 0 10px; font-size: 14px; }
|
||||
.disk-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 10px; margin-top: 12px; }
|
||||
.disk-widget { border: 1px solid var(--line); border-radius: 8px; padding: 10px; background: rgba(127,127,127,.06); }
|
||||
.disk-top { display: flex; justify-content: space-between; gap: 8px; align-items: flex-start; }
|
||||
.disk-top strong, .disk-top span, .disk-top b { display: block; }
|
||||
.disk-top span { margin-top: 3px; color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.disk-top b { color: var(--hot); font-size: 16px; }
|
||||
.meter { height: 8px; border-radius: 999px; background: rgba(127,127,127,.18); overflow: hidden; margin: 10px 0; }
|
||||
.meter span { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, var(--accent), var(--hot)); }
|
||||
.disk-meta { display: grid; gap: 3px; color: var(--muted); font-size: 12px; }
|
||||
.temp-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 10px; }
|
||||
.temp-widget { border: 1px solid var(--line); border-radius: 8px; padding: 10px; background: rgba(127,127,127,.06); display: grid; gap: 7px; }
|
||||
.temp-widget strong, .temp-widget span, .temp-widget b { display: block; }
|
||||
.temp-widget span { color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.temp-widget b { color: var(--hot); font-size: 16px; white-space: nowrap; }
|
||||
.settings-tools { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 18px; }
|
||||
.settings-tools form { min-width: 0; }
|
||||
.settings-tools h2 { margin-top: 0; }
|
||||
code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
||||
pre { overflow: auto; background: rgba(127,127,127,.12); border-radius: 6px; padding: 10px; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
td, th { border-bottom: 1px solid var(--line); padding: 8px 6px; text-align: left; vertical-align: top; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.actions form { margin: 0; }
|
||||
.section-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.status { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.pill { border: 1px solid var(--line); border-radius: 999px; padding: 5px 9px; color: var(--muted); }
|
||||
@media (max-width: 820px) { main { padding: 12px; transform: none; } .span4, .span6, .span8, .span12 { grid-column: 1 / -1; } .section-head, .hero-top { flex-direction: column; align-items: flex-start; } .settings-tools { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
</head>
|
||||
<body data-scale="90">
|
||||
<main>
|
||||
<header class="hero panel">
|
||||
<div class="hero-top">
|
||||
<div class="brand-block">
|
||||
<div class="brand-logo">byzks95</div>
|
||||
<div class="brand-text">
|
||||
<h1>OpenWrt Full Backup</h1>
|
||||
<div class="brand-links">
|
||||
<a href="https://t.me/kzolotarev95" target="_blank" rel="noopener">Telegram</a>
|
||||
<a href="https://github.com/kzolotarev95" target="_blank" rel="noopener">GitHub</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<a class="button" href="/cgi-bin/luci/admin/status/overview">Вернуться в OpenWrt</a>
|
||||
</div>
|
||||
<p>Веб-панель для полного бэкапа OpenWrt без сборки IPK. <span class="warn-text">Держи эту ссылку в секрете.</span></p>
|
||||
</header>
|
||||
EOF
|
||||
|
||||
cat <<EOF
|
||||
<section class="grid">
|
||||
EOF
|
||||
|
||||
if [ -n "$RESULT_FILE" ]; then
|
||||
if [ "$RESULT_CODE" = "0" ]; then
|
||||
result_class="ok"
|
||||
result_status="Готово"
|
||||
else
|
||||
result_class="error"
|
||||
result_status="Ошибка, код выхода: $RESULT_CODE"
|
||||
fi
|
||||
printf '<section class="panel span6 result-card %s"><div class="section-head"><div><h2>%s</h2><p>%s</p></div><a class="button small" href="%s?key=%s">Скрыть сообщение</a></div><pre class="result-output">' "$result_class" "$(h "$RESULT_TITLE")" "$(h "$result_status")" "$(self_url)" "$key"
|
||||
html_escape <"$RESULT_FILE"
|
||||
printf '</pre></section>'
|
||||
fi
|
||||
|
||||
if [ -n "$job_id" ]; then
|
||||
render_job_panel "$job_id"
|
||||
fi
|
||||
|
||||
cat <<EOF
|
||||
<div class="panel span12 device-card">
|
||||
<h2>Устройство</h2>
|
||||
<div class="status">
|
||||
<span class="pill">Имя: $(h "$(system_value host)")</span>
|
||||
<span class="pill">Версия: $(h "$(system_value release)")</span>
|
||||
<span class="pill">Плата: $(h "$(system_value board)")</span>
|
||||
</div>
|
||||
<div class="device-body">
|
||||
<div class="device-section">
|
||||
<h3>Разделы памяти</h3>
|
||||
<div class="disk-grid">$(storage_widgets)</div>
|
||||
</div>
|
||||
<div class="device-section">
|
||||
<h3>Температура роутера</h3>
|
||||
<div class="temp-list">$(temperature_widgets)</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form class="panel span12" method="post" enctype="multipart/form-data" action="$(self_url)?key=$key&action=upload_backup">
|
||||
<h2>Загрузить архив бэкапа</h2>
|
||||
<p>Выбери архив <code>.tar.gz</code> с компьютера. Он будет сохранен в $(h "$output_dir") и появится в списке архивов.</p>
|
||||
<input class="file-input" type="file" name="archive" accept=".tar.gz,application/gzip,application/x-gzip">
|
||||
<button type="submit">Загрузить архив</button>
|
||||
</form>
|
||||
|
||||
<div class="panel span12">
|
||||
<h2>Архивы в $(h "$output_dir")</h2>
|
||||
<table><thead><tr><th>Файл</th><th>Размер</th><th>Дата</th><th>Действие</th></tr></thead><tbody>
|
||||
$(backup_rows)
|
||||
</tbody></table>
|
||||
</div>
|
||||
|
||||
<div class="panel span12 settings-tools">
|
||||
<form method="post" action="$(self_url)">
|
||||
<h2>Создать бэкап</h2>
|
||||
<input type="hidden" name="key" value="$key">
|
||||
<input type="hidden" name="action" value="create">
|
||||
<label>Папка для архива</label>
|
||||
<input type="text" name="output_dir" value="$(h "$output_dir")">
|
||||
<label>Имя архива</label>
|
||||
<input type="text" name="name" placeholder="автоматически">
|
||||
<label>Путь к файлу прошивки</label>
|
||||
<input type="text" name="firmware_image" placeholder="/tmp/openwrt-sysupgrade.bin">
|
||||
<div class="checks">
|
||||
<label><input type="checkbox" name="include_overlay" value="1"$(checkbox_attr "$include_overlay")> добавить /overlay/upper</label>
|
||||
<label><input type="checkbox" name="include_rom" value="1"$(checkbox_attr "$include_rom")> добавить снимок /rom</label>
|
||||
<label><input type="checkbox" name="include_raw_mtd" value="1"$(checkbox_attr "$include_raw_mtd")> добавить raw MTD dump</label>
|
||||
</div>
|
||||
<p class="hint warn-hint">Raw MTD сохраняй только на USB/диск, например <code>/mnt/usb</code>. В <code>/tmp</code> обычно не хватит места.</p>
|
||||
<button type="submit">Создать бэкап</button>
|
||||
</form>
|
||||
|
||||
<form method="post" action="$(self_url)">
|
||||
<h2>Настройки по умолчанию</h2>
|
||||
<input type="hidden" name="key" value="$key">
|
||||
<input type="hidden" name="action" value="save_defaults">
|
||||
<label>Папка для архивов по умолчанию</label>
|
||||
<input type="text" name="default_output_dir" value="$(h "$output_dir")">
|
||||
<label>Хранить дней, 0 отключает автоочистку</label>
|
||||
<input type="number" min="0" name="keep_days" value="$(h "$keep_days")">
|
||||
<div class="checks">
|
||||
<label><input type="checkbox" name="default_include_overlay" value="1"$(checkbox_attr "$include_overlay")> добавлять overlay по умолчанию</label>
|
||||
<label><input type="checkbox" name="default_include_rom" value="1"$(checkbox_attr "$include_rom")> добавлять ROM по умолчанию</label>
|
||||
<label><input type="checkbox" name="default_include_raw_mtd" value="1"$(checkbox_attr "$include_raw_mtd")> добавлять raw MTD по умолчанию</label>
|
||||
</div>
|
||||
<button type="submit">Сохранить настройки</button>
|
||||
</form>
|
||||
|
||||
<form method="post" action="$(self_url)">
|
||||
<h2>Посмотреть архив</h2>
|
||||
<input type="hidden" name="key" value="$key">
|
||||
<input type="hidden" name="action" value="inspect">
|
||||
<label>Путь к архиву</label>
|
||||
<input type="text" name="archive" placeholder="/mnt/usb/router-owrt-full-backup.tar.gz">
|
||||
<button type="submit">Посмотреть</button>
|
||||
</form>
|
||||
|
||||
<form method="post" action="$(self_url)">
|
||||
<h2>Восстановить архив</h2>
|
||||
<input type="hidden" name="key" value="$key">
|
||||
<input type="hidden" name="action" value="restore">
|
||||
<label>Путь к архиву</label>
|
||||
<input type="text" name="archive" placeholder="/mnt/usb/router-owrt-full-backup.tar.gz">
|
||||
<div class="checks">
|
||||
<label><input type="checkbox" name="restore_configs" value="1" checked> восстановить настройки</label>
|
||||
<label><input type="checkbox" name="restore_packages" value="1"> переустановить список пакетов</label>
|
||||
<label><input type="checkbox" name="restore_overlay" value="1"> восстановить overlay snapshot</label>
|
||||
<label><input type="checkbox" name="flash_firmware" value="1"> прошить firmware image и перезагрузить</label>
|
||||
</div>
|
||||
<label>Введи RESTORE для подтверждения</label>
|
||||
<input type="text" name="confirm" autocomplete="off">
|
||||
<button class="danger restore-submit" type="submit">Запустить восстановление</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
EOF
|
||||
}
|
||||
|
||||
read_request
|
||||
if ! authorized; then
|
||||
http_unauthorized
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$(param action)" = "download" ]; then
|
||||
download_file
|
||||
fi
|
||||
|
||||
if [ "${REQUEST_METHOD:-GET}" = "POST" ]; then
|
||||
handle_action
|
||||
fi
|
||||
|
||||
page
|
||||
@@ -0,0 +1,378 @@
|
||||
#!/bin/sh
|
||||
|
||||
KEY_FILE="${KEY_FILE:-/etc/owrt-remote/web.key}"
|
||||
AGENT="${AGENT:-/usr/sbin/owrt-remote}"
|
||||
PARAMS_FILE="${TMPDIR:-/tmp}/owrt-remote-cgi.$$"
|
||||
RESULT_TITLE=""
|
||||
RESULT_BODY=""
|
||||
RESULT_KIND="info"
|
||||
|
||||
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')"
|
||||
value="$(url_decode "$value" | tr '\r\n\t' ' ')"
|
||||
[ -n "$key" ] && printf '%s\t%s\n' "$key" "$value" >>"$PARAMS_FILE"
|
||||
done
|
||||
IFS="$old_ifs"
|
||||
}
|
||||
|
||||
param() {
|
||||
awk -F ' ' -v k="$1" '$1 == k { print $2; exit }' "$PARAMS_FILE"
|
||||
}
|
||||
|
||||
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}"
|
||||
}
|
||||
|
||||
save_config() {
|
||||
local enabled field
|
||||
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 admin_host admin_port public_url; do
|
||||
uci_set "$field" "$(param "$field")"
|
||||
done
|
||||
uci commit owrtremote
|
||||
set_result "Настройки сохранены" "Если менял Xray или VPS-поля, перезапусти сервис." "ok"
|
||||
}
|
||||
|
||||
run_action() {
|
||||
local action output rc
|
||||
action="$1"
|
||||
output="${TMPDIR:-/tmp}/owrt-remote-action.$$"
|
||||
rc=0
|
||||
case "$action" in
|
||||
start)
|
||||
/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)
|
||||
/etc/init.d/owrt-remote stop >"$output" 2>&1 || rc=$?
|
||||
/etc/init.d/owrt-remote disable >>"$output" 2>&1 || rc=$?
|
||||
set_result "Сервис остановлен" "$(cat "$output")" "warn"
|
||||
;;
|
||||
restart)
|
||||
/etc/init.d/owrt-remote restart >"$output" 2>&1 || rc=$?
|
||||
set_result "Сервис перезапущен" "$(cat "$output")" "ok"
|
||||
;;
|
||||
heartbeat)
|
||||
"$AGENT" heartbeat >"$output" 2>&1 || rc=$?
|
||||
set_result "Heartbeat" "$(cat "$output")" "ok"
|
||||
;;
|
||||
doctor)
|
||||
"$AGENT" doctor >"$output" 2>&1 || rc=$?
|
||||
set_result "Проверка" "$(cat "$output")" "ok"
|
||||
;;
|
||||
esac
|
||||
if [ "$rc" != "0" ]; then
|
||||
set_result "$RESULT_TITLE" "$(cat "$output")" "bad"
|
||||
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 '<label class="field"><span>%s</span>' "$(h "$label")"
|
||||
printf '<input name="%s" type="%s" value="%s" autocomplete="off">' "$(h "$name")" "$(h "$type")" "$(h "$value")"
|
||||
if [ -n "$help" ]; then
|
||||
printf '<small>%s</small>' "$(h "$help")"
|
||||
fi
|
||||
printf '</label>'
|
||||
}
|
||||
|
||||
metric() {
|
||||
local label value tone
|
||||
label="$1"
|
||||
value="$2"
|
||||
tone="${3:-}"
|
||||
printf '<div class="metric %s"><span>%s</span><strong>%s</strong></div>' "$(h "$tone")" "$(h "$label")" "$(h "$value")"
|
||||
}
|
||||
|
||||
render_unauthorized() {
|
||||
http_html
|
||||
cat <<'EOF'
|
||||
<!doctype html><html><head><meta charset="utf-8"><title>OpenWrt Remote</title></head>
|
||||
<body><h1>Доступ запрещен</h1><p>Открой панель из LuCI или по ссылке, которую показал install.sh.</p></body></html>
|
||||
EOF
|
||||
}
|
||||
|
||||
render_page() {
|
||||
local key router_id router_name hub_url vps_host service_state service_tone xray_state xray_tone enabled_checked status_text
|
||||
key="$(param key)"
|
||||
router_id="$(uci_get router_id main)"
|
||||
router_name="$(uci_get router_name "$router_id")"
|
||||
hub_url="$(uci_get hub_url '')"
|
||||
vps_host="$(uci_get vps_host '')"
|
||||
|
||||
if service_enabled; then
|
||||
service_state="enabled"
|
||||
service_tone="good"
|
||||
else
|
||||
service_state="disabled"
|
||||
service_tone="warn"
|
||||
fi
|
||||
if xray_running; then
|
||||
xray_state="running"
|
||||
xray_tone="good"
|
||||
else
|
||||
xray_state="stopped"
|
||||
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 <<EOF
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>OpenWrt Remote</title>
|
||||
<style>
|
||||
:root{color-scheme:light;--bg:#f5f7fb;--panel:#fff;--text:#172033;--muted:#667085;--line:#d9e1ec;--blue:#2563eb;--green:#16a34a;--red:#dc2626;--amber:#d97706;--soft:#eef4ff}
|
||||
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:14px/1.45 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
||||
.wrap{max-width:1180px;margin:0 auto;padding:22px}.hero{display:flex;gap:18px;align-items:center;justify-content:space-between;padding:20px 0 18px;border-bottom:1px solid var(--line)}
|
||||
.brand{display:flex;gap:14px;align-items:center}.mark{width:54px;height:54px;border-radius:8px;background:#0f766e;color:#fff;display:grid;place-items:center;font-weight:800;font-size:24px;box-shadow:0 12px 30px rgba(15,118,110,.22)}
|
||||
h1{margin:0;font-size:28px;letter-spacing:0}.sub{margin:4px 0 0;color:var(--muted)}
|
||||
.pill{display:inline-flex;align-items:center;gap:8px;border:1px solid var(--line);background:var(--panel);border-radius:999px;padding:8px 12px;color:var(--muted);white-space:nowrap}.dot{width:9px;height:9px;border-radius:50%;background:var(--amber)}.dot.good{background:var(--green)}.dot.bad{background:var(--red)}
|
||||
.grid{display:grid;grid-template-columns:1.05fr .95fr;gap:16px;margin-top:18px}.panel{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:16px;box-shadow:0 10px 28px rgba(20,35,60,.05)}
|
||||
.panel h2{font-size:18px;margin:0 0 12px}.metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.metric{border:1px solid var(--line);border-radius:8px;padding:12px;background:#fafcff}.metric span{display:block;color:var(--muted);font-size:12px}.metric strong{display:block;margin-top:4px;font-size:18px;word-break:break-word}.metric.good strong{color:var(--green)}.metric.bad strong{color:var(--red)}.metric.warn strong{color:var(--amber)}
|
||||
form{margin:0}.formgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.field{display:block}.field span{display:block;font-weight:650;margin-bottom:6px}.field input{width:100%;border:1px solid var(--line);border-radius:8px;background:#fff;padding:10px 11px;color:var(--text)}.field small{display:block;margin-top:5px;color:var(--muted)}
|
||||
.check{display:flex;gap:10px;align-items:center;margin-bottom:12px;font-weight:700}.check input{width:18px;height:18px}.actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:14px}.btn{border:0;border-radius:8px;padding:10px 13px;font-weight:750;cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;background:#e8eef8;color:#1f2a44}.btn.primary{background:var(--blue);color:#fff}.btn.good{background:var(--green);color:#fff}.btn.bad{background:#fee2e2;color:#991b1b}.btn.warn{background:#fff7ed;color:#9a3412;border:1px solid #fed7aa}
|
||||
.notice{margin-top:16px;border-radius:8px;padding:12px;border:1px solid var(--line);background:#f8fbff;white-space:pre-wrap}.notice.ok{border-color:#bbf7d0;background:#f0fdf4}.notice.bad{border-color:#fecaca;background:#fef2f2}.notice.warn{border-color:#fed7aa;background:#fff7ed}
|
||||
.code{background:#101827;color:#d7e2f2;border-radius:8px;padding:12px;overflow:auto;min-height:120px;font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace}
|
||||
@media(max-width:820px){.grid,.formgrid,.metrics{grid-template-columns:1fr}.hero{align-items:flex-start;flex-direction:column}.wrap{padding:14px}h1{font-size:24px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="wrap">
|
||||
<section class="hero">
|
||||
<div class="brand">
|
||||
<div class="mark">R</div>
|
||||
<div>
|
||||
<h1>OpenWrt Remote</h1>
|
||||
<p class="sub">$(h "$router_name") · $(h "$router_id") · $(h "$status_text")</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pill"><span class="dot $(h "$xray_tone")"></span>Xray: $(h "$xray_state")</div>
|
||||
</section>
|
||||
|
||||
<section class="grid">
|
||||
<div class="panel">
|
||||
<h2>Состояние</h2>
|
||||
<div class="metrics">
|
||||
EOF
|
||||
metric "procd service" "$service_state" "$service_tone"
|
||||
metric "xray tunnel" "$xray_state" "$xray_tone"
|
||||
metric "VPS host" "${vps_host:-не задан}" ""
|
||||
metric "Hub URL" "${hub_url:-не задан}" ""
|
||||
cat <<EOF
|
||||
</div>
|
||||
<form method="post" class="actions">
|
||||
<input type="hidden" name="key" value="$(h "$key")">
|
||||
<button class="btn good" name="action" value="start">Запустить</button>
|
||||
<button class="btn warn" name="action" value="restart">Перезапустить</button>
|
||||
<button class="btn bad" name="action" value="stop">Остановить</button>
|
||||
<button class="btn" name="action" value="heartbeat">Heartbeat</button>
|
||||
<button class="btn" name="action" value="doctor">Проверка</button>
|
||||
<a class="btn" href="?key=$(h "$key")&action=download_config">Скачать Xray config</a>
|
||||
</form>
|
||||
EOF
|
||||
if [ -n "$RESULT_TITLE" ]; then
|
||||
printf '<div class="notice %s"><strong>%s</strong>\n%s</div>' "$(h "$RESULT_KIND")" "$(h "$RESULT_TITLE")" "$(h "$RESULT_BODY")"
|
||||
fi
|
||||
cat <<EOF
|
||||
</div>
|
||||
|
||||
<div class="panel">
|
||||
<h2>Шпаргалка</h2>
|
||||
<div class="code">/etc/init.d/owrt-remote enable
|
||||
/etc/init.d/owrt-remote restart
|
||||
owrt-remote heartbeat
|
||||
owrt-remote status</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel" style="margin-top:16px">
|
||||
<h2>Настройки роутера</h2>
|
||||
<form method="post">
|
||||
<input type="hidden" name="key" value="$(h "$key")">
|
||||
<label class="check"><input type="checkbox" name="enabled" value="1" $enabled_checked> Включить агент и автозапуск</label>
|
||||
<div class="formgrid">
|
||||
EOF
|
||||
field router_id "Router ID" text "Например main или office-1"
|
||||
field router_name "Название" text "Будет видно на VPS-карточке"
|
||||
field role "Роль" text "main для главного, node для остальных"
|
||||
field public_url "Public URL" text "Можно оставить пустым, если используешь proxy через hub"
|
||||
field hub_url "Hub URL" text "Например https://vps.example.com:8088"
|
||||
field hub_token "Hub token" password "AGENT_TOKEN с VPS"
|
||||
field heartbeat_interval "Heartbeat, секунд" number "Минимум 10"
|
||||
field xray_bin "Xray binary" text "/usr/bin/xray"
|
||||
field xray_config "Xray config" text "/etc/xray/owrt-remote-client.json"
|
||||
field vps_host "VPS host" text "IP или домен VPS для Xray"
|
||||
field vps_port "VPS Xray port" number "Обычно 8443"
|
||||
field vless_uuid "VLESS UUID" text "Из карточки роутера на VPS"
|
||||
field vless_encryption "VLESS encryption" text "По умолчанию none"
|
||||
field vless_flow "VLESS flow" text "Обычно пусто"
|
||||
field reverse_tag "Reverse tag" text "Обычно reverse-in"
|
||||
field admin_host "Admin host" text "Обычно 127.0.0.1"
|
||||
field admin_port "Admin port" number "LuCI/uhttpd обычно 80"
|
||||
cat <<EOF
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button class="btn primary" name="action" value="save">Сохранить</button>
|
||||
<button class="btn good" name="action" value="save_start">Сохранить и запустить</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
EOF
|
||||
}
|
||||
|
||||
read_request
|
||||
|
||||
if ! authorized; then
|
||||
render_unauthorized
|
||||
exit 0
|
||||
fi
|
||||
|
||||
action="$(param action)"
|
||||
|
||||
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)
|
||||
save_config
|
||||
run_action start
|
||||
;;
|
||||
start|stop|restart|heartbeat|doctor)
|
||||
run_action "$action"
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
render_page
|
||||
|
||||
+8
-8
@@ -1,11 +1,10 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require fs';
|
||||
'require ui';
|
||||
|
||||
return view.extend({
|
||||
load: function() {
|
||||
return fs.read('/etc/owrt-full-backup/web.key').catch(function() {
|
||||
return fs.read('/etc/owrt-remote/web.key').catch(function() {
|
||||
return '';
|
||||
});
|
||||
},
|
||||
@@ -15,24 +14,24 @@ return view.extend({
|
||||
|
||||
if (!key) {
|
||||
return E('div', { 'class': 'cbi-map' }, [
|
||||
E('h2', {}, _('OpenWrt Full Backup')),
|
||||
E('h2', {}, _('OpenWrt Remote')),
|
||||
E('div', { 'class': 'alert-message warning' }, [
|
||||
_('Веб-ключ не найден. Переустанови модуль командой install.sh.')
|
||||
_('Web key not found. Reinstall the module or create /etc/owrt-remote/web.key.')
|
||||
])
|
||||
]);
|
||||
}
|
||||
|
||||
var url = '/cgi-bin/owrt-full-backup?key=' + encodeURIComponent(key);
|
||||
var url = '/cgi-bin/owrt-remote?key=' + encodeURIComponent(key);
|
||||
|
||||
window.setTimeout(function() {
|
||||
window.location.replace(url);
|
||||
}, 100);
|
||||
|
||||
return E('div', { 'class': 'cbi-map' }, [
|
||||
E('h2', {}, _('OpenWrt Full Backup')),
|
||||
E('p', {}, _('Открываю веб-панель полного бэкапа...')),
|
||||
E('h2', {}, _('OpenWrt Remote')),
|
||||
E('p', {}, _('Opening remote access panel...')),
|
||||
E('p', {}, [
|
||||
E('a', { 'class': 'btn cbi-button cbi-button-apply', 'href': url }, _('Открыть панель'))
|
||||
E('a', { 'class': 'btn cbi-button cbi-button-apply', 'href': url }, _('Open panel'))
|
||||
])
|
||||
]);
|
||||
},
|
||||
@@ -41,3 +40,4 @@ return view.extend({
|
||||
handleSave: null,
|
||||
handleReset: null
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user