Files
luci-app-owrt-remote/files/www/cgi-bin/owrt-full-backup
T

495 lines
17 KiB
Bash

#!/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=""
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/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/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:-}"
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\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._/-]+$'
}
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
}
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"
run_backend "Создание бэкапа" "$@"
}
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 ;;
esac
}
system_value() {
case "$1" in
host) 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
}
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><a href="%s?key=%s&amp;action=download&amp;file=%s">скачать</a></td></tr>' \
"$(h "$base")" "$(h "$size")" "$(h "$mtime")" "$(self_url)" "$key" "$(h "$file")"
done
}
page() {
local key output_dir include_overlay include_rom include_raw_mtd keep_days
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)"
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 Full Backup</title>
<style>
:root { color-scheme: light dark; --bg: #f6f7f9; --panel: #fff; --text: #15181c; --muted: #667085; --line: #d9dee7; --accent: #1769e0; --bad: #b42318; --ok: #067647; }
@media (prefers-color-scheme: dark) { :root { --bg: #111418; --panel: #181d23; --text: #eef2f6; --muted: #a6b0bf; --line: #2d3642; --accent: #6aa4ff; --bad: #ff9b91; --ok: #7ee0a3; } }
* { 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; }
main { max-width: 1180px; margin: 0 auto; padding: 18px; display: grid; gap: 14px; }
h1 { margin: 0; font-size: 22px; }
h2 { margin: 0 0 12px; font-size: 16px; }
p { margin: 6px 0; color: var(--muted); }
.hero { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 16px 18px; }
.hero h1 { font-size: 24px; line-height: 1.15; }
.hero p { max-width: 680px; margin-top: 8px; }
.hero-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; min-width: 260px; }
.hero .pill { background: rgba(127,127,127,.08); color: var(--text); }
.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: #fff; padding: 8px 12px; text-decoration: none; font-weight: 700; cursor: pointer; }
.danger { background: var(--bad); }
.muted { color: var(--muted); }
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; }
.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) { .span4, .span6, .span8, .span12 { grid-column: 1 / -1; } main { padding: 12px; } .hero { align-items: flex-start; flex-direction: column; } .hero-actions { justify-content: flex-start; min-width: 0; } }
</style>
</head>
<body>
<main>
<header class="hero panel">
<div>
<h1>OpenWrt Full Backup</h1>
<p>Веб-панель для полного бэкапа OpenWrt без сборки IPK. Держи эту ссылку в секрете.</p>
</div>
<div class="hero-actions">
<span class="pill">LuCI: Службы</span>
<span class="pill">Backup / Restore</span>
<span class="pill">OpenWrt 22-25</span>
</div>
</header>
EOF
if [ -n "$RESULT_FILE" ]; then
printf '<section class="panel span12"><h2>%s</h2><p>Код выхода: %s</p><pre>' "$(h "$RESULT_TITLE")" "$(h "$RESULT_CODE")"
html_escape <"$RESULT_FILE"
printf '</pre></section>'
fi
cat <<EOF
<section class="grid">
<div class="panel span4">
<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>
<pre>$(df -h 2>/dev/null | html_escape)</pre>
</div>
<form class="panel span8" 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>
<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>
<form class="panel span6" 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 class="panel span6" 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" type="submit">Запустить восстановление</button>
</form>
<form class="panel span6" 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>
<div class="panel span6">
<h2>Установка / удаление через Git</h2>
<p>Установка через clone:</p>
<pre>git clone $(h "$PROJECT_URL").git
cd luci-app-owrt-full-backup
sh install.sh</pre>
<p>Установка одной командой:</p>
<pre>wget -O - $(h "$RAW_URL")/install.sh | sh</pre>
<p>Удаление:</p>
<pre>wget -O - $(h "$RAW_URL")/uninstall.sh | sh</pre>
</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