Add OpenWrt remote hub
This commit is contained in:
1 parent
48cba62f21
commit
38a92b0b1f
19 files changed
+2080
-2123
No files matched your search
@@ -7,3 +7,5 @@ bin/
|
|||||||
dl/
|
dl/
|
||||||
staging_dir/
|
staging_dir/
|
||||||
tmp/
|
tmp/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
@@ -1,238 +1,160 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
# OpenWrt Full Backup
|
# OpenWrt Remote Hub
|
||||||
|
|
||||||
**LuCI web-панель и SSH-утилита для полного бэкапа OpenWrt без сборки `.ipk`.**
|
**Легкий удаленный доступ к OpenWrt через свой VPS: карточки роутеров, online/offline, Xray reverse и локальная LuCI-интеграция без тяжелого VPN.**
|
||||||
|
|
||||||
[](https://openwrt.org/)
|
[](https://openwrt.org/)
|
||||||
[](https://openwrt.org/docs/guide-user/luci/start)
|
[](https://xtls.github.io/en/document/level-2/vless_reverse.html)
|
||||||
[](#если-в-luci-ошибка-no-lua-runtime-installed)
|
[](#быстрый-старт)
|
||||||
[](#быстрая-установка)
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<img width="1920" height="1146" alt="1111111111111111111111" src="https://github.com/user-attachments/assets/e30f7974-e552-4d3b-9f13-5ad8ad4e917f" />
|
## Что это
|
||||||
|
|
||||||
|
`luci-app-owrt-remote` собирает схему "роутер за NAT -> VPS -> красивая панель -> админка роутера".
|
||||||
|
|
||||||
## Зачем нужен модуль
|
На роутере ставится маленький агент:
|
||||||
|
|
||||||
`luci-app-owrt-full-backup` делает удобную панель в OpenWrt для создания, скачивания, загрузки и восстановления архивов бэкапа. Подходит для обычного сохранения настроек, переноса конфигурации после перепрошивки и подготовки полного архива роутера перед экспериментами.
|
- пункт в LuCI: `Службы -> OpenWrt Remote`;
|
||||||
|
- `/usr/sbin/owrt-remote` для старта Xray reverse, heartbeat и генерации client config;
|
||||||
|
- `/etc/init.d/owrt-remote` для автозапуска через `procd`;
|
||||||
|
- локальная CGI-панель настройки, без Lua runtime.
|
||||||
|
|
||||||
> [!IMPORTANT]
|
На VPS запускается `vps/owrt-remote-hub.py`:
|
||||||
> После установки скрипт покажет приватную ссылку с `key=...`. Не отдавай ее посторонним: по этой ссылке можно создавать и восстанавливать бэкапы.
|
|
||||||
|
|
||||||
## Быстрая установка
|
- веб-панель с карточками роутеров;
|
||||||
|
- online/offline по heartbeat;
|
||||||
|
- кнопка "Открыть админку";
|
||||||
|
- прокси к локальному Xray entry port, чтобы наружу не торчали админки всех роутеров;
|
||||||
|
- генерация server-side Xray config для нескольких роутеров.
|
||||||
|
|
||||||
Зайди на роутер по SSH и выполни:
|
ZeroTier, Tailscale и WireGuard тут не используются. Xray-бинарь в репозиторий не кладется, чтобы не занимать флешку OpenWrt.
|
||||||
|
|
||||||
```sh
|
## Как работает
|
||||||
wget -O - https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-full-backup/main/install.sh | sh
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
User["Браузер админа"] --> Hub["VPS: OpenWrt Remote Hub"]
|
||||||
|
Hub --> LocalEntry["127.0.0.1:18080<br/>Xray tunnel inbound"]
|
||||||
|
LocalEntry --> Reverse["VLESS reverse tunnel"]
|
||||||
|
Router["OpenWrt router<br/>owrt-remote + Xray"] --> Reverse
|
||||||
|
Router --> LuCI["127.0.0.1:80<br/>LuCI/uhttpd"]
|
||||||
```
|
```
|
||||||
|
|
||||||
После установки открой:
|
1. Роутер сам подключается к VPS и держит reverse tunnel.
|
||||||
|
2. VPS-панель показывает карточку роутера и статус.
|
||||||
|
3. Когда нажимаешь "Открыть админку", хаб проксирует запрос в локальный entry port Xray.
|
||||||
|
4. Xray возвращает этот поток через reverse tunnel на LuCI роутера.
|
||||||
|
|
||||||
|
## Быстрый старт
|
||||||
|
|
||||||
|
### 1. VPS
|
||||||
|
|
||||||
|
На VPS нужен Python 3 и Xray. Скопируй папку `vps` на сервер и запусти:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo mkdir -p /opt/owrt-remote /var/lib/owrt-remote
|
||||||
|
sudo cp vps/owrt-remote-hub.py /opt/owrt-remote/
|
||||||
|
sudo chmod +x /opt/owrt-remote/owrt-remote-hub.py
|
||||||
|
sudo /opt/owrt-remote/owrt-remote-hub.py init
|
||||||
|
sudo /opt/owrt-remote/owrt-remote-hub.py add-router --id main --name "Главный роутер" --role main --entry-port 18080 --vps-host YOUR_VPS_DOMAIN_OR_IP
|
||||||
|
sudo /opt/owrt-remote/owrt-remote-hub.py render-xray --out /etc/xray/owrt-remote.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Запусти хаб:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo OWRT_REMOTE_BIND=0.0.0.0 OWRT_REMOTE_PORT=8088 /opt/owrt-remote/owrt-remote-hub.py serve
|
||||||
|
```
|
||||||
|
|
||||||
|
Панель:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
LuCI -> Службы -> OpenWrt Full Backup
|
http://YOUR_VPS_IP:8088/?token=ADMIN_TOKEN
|
||||||
```
|
```
|
||||||
|
|
||||||
Также установщик покажет прямую ссылку:
|
`ADMIN_TOKEN` хаб покажет при первом `init`/`serve`, также он лежит в `/var/lib/owrt-remote/admin.token`.
|
||||||
|
|
||||||
|
### 2. OpenWrt
|
||||||
|
|
||||||
|
На роутере:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
wget -O - https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/install.sh | sh
|
||||||
|
```
|
||||||
|
|
||||||
|
После установки:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
http://192.168.1.1/cgi-bin/owrt-full-backup?key=SECRET
|
LuCI -> Службы -> OpenWrt Remote
|
||||||
```
|
```
|
||||||
|
|
||||||
## Что умеет
|
В VPS-панели открой карточку роутера и скопируй готовые UCI-команды из "OpenWrt config". Вставь их на роутер, затем:
|
||||||
|
|
||||||
| Возможность | Что делает |
|
|
||||||
| --- | --- |
|
|
||||||
| Веб-панель LuCI | Пункт `Службы -> OpenWrt Full Backup` и отдельная защищенная CGI-панель |
|
|
||||||
| Бэкап настроек | Создает стандартный `sysupgrade` backup конфигурации OpenWrt |
|
|
||||||
| Список пакетов | Сохраняет список установленных пакетов `opkg` |
|
|
||||||
| Overlay snapshot | Может добавить `/overlay/upper` |
|
|
||||||
| ROM snapshot | Может добавить снимок `/rom` |
|
|
||||||
| Firmware image | Может положить в архив готовый `sysupgrade.bin` |
|
|
||||||
| Raw MTD dump | Может сохранить `/dev/mtd*`, если архив пишется на USB/диск |
|
|
||||||
| Архивы в веб-панели | Скачать, загрузить, посмотреть и удалить архив |
|
|
||||||
| Восстановление | Отдельные галочки для настроек, пакетов, overlay и firmware |
|
|
||||||
| Виджеты роутера | Показывает разделы памяти, свободное место и температуру |
|
|
||||||
|
|
||||||
## Как выглядит сценарий работы
|
|
||||||
|
|
||||||
1. Открываешь `Службы -> OpenWrt Full Backup`.
|
|
||||||
2. Выбираешь папку для архива, лучше USB или диск: `/mnt/usb`.
|
|
||||||
3. Нажимаешь `Создать бэкап`.
|
|
||||||
4. На странице виден журнал выполнения и таймер.
|
|
||||||
5. После завершения архив появляется в списке.
|
|
||||||
6. Архив можно скачать, удалить, загрузить обратно или восстановить.
|
|
||||||
|
|
||||||
## Безопасное место для архива
|
|
||||||
|
|
||||||
`/tmp` в OpenWrt обычно находится в RAM. Для маленького бэкапа настроек этого может хватить, но для больших архивов лучше сразу использовать USB/диск.
|
|
||||||
|
|
||||||
Рекомендуемый путь:
|
|
||||||
|
|
||||||
```text
|
|
||||||
/mnt/usb
|
|
||||||
```
|
|
||||||
|
|
||||||
> [!WARNING]
|
|
||||||
> Raw MTD dump может быть очень большим и привязан к конкретной модели роутера. Модуль не дает сохранять raw MTD в `/tmp`, чтобы не забить RAM и не получить `No space left on device`.
|
|
||||||
|
|
||||||
## CLI-команды
|
|
||||||
|
|
||||||
Создать бэкап на USB:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
owrt-full-backup create -o /mnt/usb
|
/etc/init.d/owrt-remote enable
|
||||||
```
|
/etc/init.d/owrt-remote restart
|
||||||
|
owrt-remote heartbeat
|
||||||
Добавить firmware image:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
owrt-full-backup create -o /mnt/usb --firmware-image /tmp/openwrt-sysupgrade.bin
|
|
||||||
```
|
|
||||||
|
|
||||||
Посмотреть архив:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
owrt-full-backup inspect /mnt/usb/router-owrt-full-backup.tar.gz
|
|
||||||
```
|
|
||||||
|
|
||||||
Восстановить только настройки:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
owrt-full-backup restore /mnt/usb/router-owrt-full-backup.tar.gz --yes --no-packages
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Что ставится на роутер
|
## Что ставится на роутер
|
||||||
|
|
||||||
| Путь | Назначение |
|
| Путь | Назначение |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `/usr/sbin/owrt-full-backup` | Основная CLI-команда |
|
| `/usr/sbin/owrt-remote` | CLI-агент: render config, heartbeat, status |
|
||||||
| `/usr/sbin/owrt-full-backup-upload` | Потоковая загрузка `.tar.gz` из браузера без Lua |
|
| `/etc/init.d/owrt-remote` | сервис автозапуска Xray reverse + heartbeat loop |
|
||||||
| `/www/cgi-bin/owrt-full-backup` | Основная веб-панель |
|
| `/www/cgi-bin/owrt-remote` | локальная красивая панель настройки |
|
||||||
| `/www/luci-static/resources/view/owrt_full_backup.js` | LuCI-страница-редирект без Lua runtime |
|
| `/www/luci-static/resources/view/owrt_remote.js` | LuCI-страница-редирект |
|
||||||
| `/usr/share/luci/menu.d/luci-app-owrt-full-backup.json` | Пункт меню LuCI |
|
| `/usr/share/luci/menu.d/luci-app-owrt-remote.json` | пункт меню LuCI |
|
||||||
| `/usr/share/rpcd/acl.d/luci-app-owrt-full-backup.json` | ACL-доступ LuCI к приватному ключу |
|
| `/usr/share/rpcd/acl.d/luci-app-owrt-remote.json` | ACL для чтения web key |
|
||||||
| `/etc/config/fullbackup` | Настройки по умолчанию |
|
| `/etc/config/owrtremote` | UCI-настройки агента |
|
||||||
| `/etc/owrt-full-backup/web.key` | Приватный ключ веб-панели |
|
| `/etc/owrt-remote/web.key` | приватный ключ локальной панели |
|
||||||
|
|
||||||
## Структура проекта
|
## Память OpenWrt
|
||||||
|
|
||||||
```text
|
Сам модуль маленький: shell-скрипты, LuCI redirect и CGI. Самый тяжелый компонент - `xray-core`, но он не включен в этот репозиторий. Если на роутере мало флешки, лучше поставить Xray на extroot/USB или использовать сборку прошивки, где Xray уже включен.
|
||||||
.
|
|
||||||
├── install.sh
|
|
||||||
├── uninstall.sh
|
|
||||||
├── README.md
|
|
||||||
├── LICENSE
|
|
||||||
└── files
|
|
||||||
├── etc
|
|
||||||
│ └── config
|
|
||||||
│ └── fullbackup
|
|
||||||
├── usr
|
|
||||||
│ ├── sbin
|
|
||||||
│ │ ├── owrt-full-backup
|
|
||||||
│ │ └── owrt-full-backup-upload
|
|
||||||
│ └── share
|
|
||||||
│ ├── luci
|
|
||||||
│ │ └── menu.d
|
|
||||||
│ │ └── luci-app-owrt-full-backup.json
|
|
||||||
│ └── rpcd
|
|
||||||
│ └── acl.d
|
|
||||||
│ └── luci-app-owrt-full-backup.json
|
|
||||||
└── www
|
|
||||||
├── cgi-bin
|
|
||||||
│ └── owrt-full-backup
|
|
||||||
└── luci-static
|
|
||||||
└── resources
|
|
||||||
└── view
|
|
||||||
└── owrt_full_backup.js
|
|
||||||
```
|
|
||||||
|
|
||||||
## Обновление
|
## Команды агента
|
||||||
|
|
||||||
Принудительно поставить свежую версию с GitHub:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-full-backup/main/install.sh?v=$(date +%s)" | sh
|
owrt-remote status
|
||||||
|
owrt-remote render-client
|
||||||
|
owrt-remote render-client --stdout
|
||||||
|
owrt-remote heartbeat
|
||||||
|
owrt-remote doctor
|
||||||
```
|
```
|
||||||
|
|
||||||
Скрипт обновляет файлы, удаляет старый Lua-controller, чистит кэш LuCI и перезапускает `rpcd/uhttpd`.
|
## Команды VPS-хаба
|
||||||
|
|
||||||
|
```sh
|
||||||
|
vps/owrt-remote-hub.py init
|
||||||
|
vps/owrt-remote-hub.py add-router --id main --name "Главный" --role main --entry-port 18080 --vps-host example.com
|
||||||
|
vps/owrt-remote-hub.py list-routers
|
||||||
|
vps/owrt-remote-hub.py render-xray --out /etc/xray/owrt-remote.json
|
||||||
|
vps/owrt-remote-hub.py print-openwrt-config --id main
|
||||||
|
vps/owrt-remote-hub.py serve --host 0.0.0.0 --port 8088
|
||||||
|
```
|
||||||
|
|
||||||
## Удаление
|
## Удаление
|
||||||
|
|
||||||
Удалить модуль, но оставить конфиг и веб-ключ:
|
С роутера:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
wget -O - https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-full-backup/main/uninstall.sh | sh
|
wget -O - https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/uninstall.sh | sh
|
||||||
```
|
```
|
||||||
|
|
||||||
Удалить модуль, конфиг и веб-ключ:
|
Полностью, вместе с конфигом:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
wget -O - https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-full-backup/main/uninstall.sh | PURGE=1 sh
|
wget -O - https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/uninstall.sh | PURGE=1 sh
|
||||||
```
|
```
|
||||||
|
|
||||||
Архивы бэкапов при удалении не стираются.
|
## Важное по безопасности
|
||||||
|
|
||||||
## Диагностика
|
- Не открывай LuCI роутеров напрямую наружу.
|
||||||
|
- Entry ports Xray на VPS по умолчанию слушают `127.0.0.1`, а наружу отдается только dashboard.
|
||||||
|
- Панель хаба защищена `ADMIN_TOKEN`, а heartbeat от роутеров - отдельным `AGENT_TOKEN`.
|
||||||
|
- Для боевого режима лучше посадить dashboard за HTTPS reverse proxy: Caddy, Nginx или Traefik.
|
||||||
|
- Xray VLESS reverse можно усилить своим `xray vlessenc`; по умолчанию конфиг использует совместимый режим `none`.
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Пункт не появился в LuCI</summary>
|
|
||||||
|
|
||||||
Обнови модуль и перезапусти кэш LuCI:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-full-backup/main/install.sh?v=$(date +%s)" | sh
|
|
||||||
rm -rf /tmp/luci-indexcache /tmp/luci-modulecache /tmp/luci-indexcache.* /tmp/luci-modulecache.*
|
|
||||||
/etc/init.d/rpcd restart
|
|
||||||
/etc/init.d/uhttpd restart
|
|
||||||
```
|
|
||||||
|
|
||||||
Потом обнови страницу LuCI или выйди и зайди снова.
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>В LuCI ошибка `No Lua runtime installed`</summary>
|
|
||||||
|
|
||||||
Поставь свежую версию. Модуль больше не использует Lua-controller для пункта меню LuCI.
|
|
||||||
|
|
||||||
```sh
|
|
||||||
wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-full-backup/main/install.sh?v=$(date +%s)" | sh
|
|
||||||
```
|
|
||||||
|
|
||||||
Проверка:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
test ! -e /usr/lib/lua/luci/controller/owrt_full_backup.lua && echo "Lua controller удален"
|
|
||||||
```
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Ошибка `No space left on device`</summary>
|
|
||||||
|
|
||||||
Архив создается в `/tmp`, а там закончилась RAM. Используй USB/диск:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
mkdir -p /mnt/usb
|
|
||||||
owrt-full-backup create -o /mnt/usb
|
|
||||||
```
|
|
||||||
|
|
||||||
В веб-панели тоже укажи `/mnt/usb`.
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Браузер пишет `ERR_CONNECTION_RESET` при загрузке архива</summary>
|
|
||||||
|
|
||||||
Обнови модуль. Загрузка архива идет потоково и не держит весь `.tar.gz` в памяти.
|
|
||||||
|
|
||||||
Если ошибка осталась, проверь свободное место в папке архива и используй USB/диск:
|
|
||||||
|
|
||||||
```text
|
|
||||||
/mnt/usb
|
|
||||||
```
|
|
||||||
|
|
||||||
**Full Changelog**: https://github.com/kzolotarev95/luci-app-owrt-full-backup/commits/v1
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
config backup 'main'
|
|
||||||
option output_dir '/tmp'
|
|
||||||
option include_overlay '1'
|
|
||||||
option include_rom '0'
|
|
||||||
option include_raw_mtd '0'
|
|
||||||
option keep_days '0'
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
config remote 'main'
|
||||||
|
option enabled '0'
|
||||||
|
option router_id 'main'
|
||||||
|
option router_name 'Главный роутер'
|
||||||
|
option role 'main'
|
||||||
|
option hub_url ''
|
||||||
|
option hub_token ''
|
||||||
|
option heartbeat_interval '30'
|
||||||
|
option xray_bin '/usr/bin/xray'
|
||||||
|
option xray_config '/etc/xray/owrt-remote-client.json'
|
||||||
|
option vps_host ''
|
||||||
|
option vps_port '8443'
|
||||||
|
option vless_uuid ''
|
||||||
|
option vless_encryption 'none'
|
||||||
|
option vless_flow ''
|
||||||
|
option reverse_tag 'reverse-in'
|
||||||
|
option admin_host '127.0.0.1'
|
||||||
|
option admin_port '80'
|
||||||
|
option public_url ''
|
||||||
|
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
#!/bin/sh /etc/rc.common
|
||||||
|
|
||||||
|
USE_PROCD=1
|
||||||
|
START=99
|
||||||
|
STOP=10
|
||||||
|
|
||||||
|
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"
|
||||||
|
}
|
||||||
|
|
||||||
|
enabled() {
|
||||||
|
case "$(uci_get enabled 0)" in
|
||||||
|
1|yes|true|on|enabled) return 0 ;;
|
||||||
|
*) return 1 ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
start_service() {
|
||||||
|
if ! enabled; then
|
||||||
|
echo "owrt-remote disabled in /etc/config/owrtremote"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
procd_open_instance xray
|
||||||
|
procd_set_param command /usr/sbin/owrt-remote run
|
||||||
|
procd_set_param respawn 3600 5 5
|
||||||
|
procd_set_param stdout 1
|
||||||
|
procd_set_param stderr 1
|
||||||
|
procd_close_instance
|
||||||
|
|
||||||
|
procd_open_instance heartbeat
|
||||||
|
procd_set_param command /usr/sbin/owrt-remote heartbeat-loop
|
||||||
|
procd_set_param respawn 3600 5 5
|
||||||
|
procd_set_param stdout 1
|
||||||
|
procd_set_param stderr 1
|
||||||
|
procd_close_instance
|
||||||
|
}
|
||||||
|
|
||||||
|
reload_service() {
|
||||||
|
stop
|
||||||
|
start
|
||||||
|
}
|
||||||
|
|
||||||
|
service_triggers() {
|
||||||
|
procd_add_reload_trigger owrtremote
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,693 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
|
|
||||||
VERSION="1.0.0"
|
|
||||||
FORMAT="owrt-full-backup-v1"
|
|
||||||
DEFAULT_OUTPUT_DIR="/tmp"
|
|
||||||
WORKDIR=""
|
|
||||||
|
|
||||||
log() {
|
|
||||||
printf '%s\n' "$*" >&2
|
|
||||||
}
|
|
||||||
|
|
||||||
warn() {
|
|
||||||
printf 'ВНИМАНИЕ: %s\n' "$*" >&2
|
|
||||||
}
|
|
||||||
|
|
||||||
die() {
|
|
||||||
printf 'ОШИБКА: %s\n' "$*" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup() {
|
|
||||||
if [ -n "$WORKDIR" ] && [ -d "$WORKDIR" ]; then
|
|
||||||
rm -rf "$WORKDIR"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
trap cleanup EXIT INT TERM
|
|
||||||
|
|
||||||
usage() {
|
|
||||||
cat <<'EOF'
|
|
||||||
Использование:
|
|
||||||
owrt-full-backup create [options]
|
|
||||||
owrt-full-backup restore <archive.tar.gz> [options]
|
|
||||||
owrt-full-backup inspect <archive.tar.gz>
|
|
||||||
owrt-full-backup help
|
|
||||||
|
|
||||||
Опции создания:
|
|
||||||
-o, --output-dir DIR Папка для итогового архива
|
|
||||||
-n, --name NAME Имя архива без .tar.gz
|
|
||||||
--no-overlay Не добавлять снимок /overlay/upper
|
|
||||||
--include-rom Добавить read-only снимок /rom
|
|
||||||
--firmware-image FILE Скопировать sysupgrade-образ в архив
|
|
||||||
--include-raw-mtd Добавить dump разделов /dev/mtd*
|
|
||||||
|
|
||||||
Опции восстановления:
|
|
||||||
--yes Не спрашивать подтверждение
|
|
||||||
--no-configs Не восстанавливать sysupgrade config backup
|
|
||||||
--no-packages Не переустанавливать пакеты из списка
|
|
||||||
--overlay Восстановить снимок /overlay/upper в /
|
|
||||||
--flash-firmware Прошить firmware image из архива через sysupgrade
|
|
||||||
|
|
||||||
Примеры:
|
|
||||||
owrt-full-backup create -o /mnt/usb
|
|
||||||
owrt-full-backup create -o /mnt/usb --firmware-image /tmp/openwrt.bin
|
|
||||||
owrt-full-backup restore /mnt/usb/router-backup.tar.gz --yes
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
need_cmd() {
|
|
||||||
command -v "$1" >/dev/null 2>&1 || die "нужная команда не найдена: $1"
|
|
||||||
}
|
|
||||||
|
|
||||||
make_workdir() {
|
|
||||||
local base
|
|
||||||
base="${1:-${TMPDIR:-/tmp}}"
|
|
||||||
[ -d "$base" ] || base="${TMPDIR:-/tmp}"
|
|
||||||
WORKDIR="$(mktemp -d "$base/owrt-full-backup.XXXXXX" 2>/dev/null || true)"
|
|
||||||
if [ -z "$WORKDIR" ] || [ ! -d "$WORKDIR" ]; then
|
|
||||||
WORKDIR="$base/owrt-full-backup.$$"
|
|
||||||
mkdir -p "$WORKDIR" || die "не удалось создать временную папку: $WORKDIR"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
abs_path() {
|
|
||||||
local path
|
|
||||||
path="$1"
|
|
||||||
if command -v readlink >/dev/null 2>&1; then
|
|
||||||
readlink -f "$path" 2>/dev/null && return
|
|
||||||
fi
|
|
||||||
(cd "$path" 2>/dev/null && pwd -P) || printf '%s\n' "$path"
|
|
||||||
}
|
|
||||||
|
|
||||||
is_tmp_path() {
|
|
||||||
local path
|
|
||||||
path="$(abs_path "$1")"
|
|
||||||
case "$path" in
|
|
||||||
/tmp|/tmp/*) return 0 ;;
|
|
||||||
*) return 1 ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
uci_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)"
|
|
||||||
if [ -n "$value" ]; then
|
|
||||||
printf '%s' "$value"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
printf '%s' "$default"
|
|
||||||
}
|
|
||||||
|
|
||||||
copy_if_exists() {
|
|
||||||
local src dst
|
|
||||||
src="$1"
|
|
||||||
dst="$2"
|
|
||||||
if [ -e "$src" ]; then
|
|
||||||
cp -p "$src" "$dst" 2>/dev/null || cp "$src" "$dst" 2>/dev/null || true
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
sanitize() {
|
|
||||||
printf '%s' "$1" | tr -cs 'A-Za-z0-9._-' '_'
|
|
||||||
}
|
|
||||||
|
|
||||||
hostname_safe() {
|
|
||||||
local name
|
|
||||||
name="$(hostname 2>/dev/null || printf 'openwrt')"
|
|
||||||
sanitize "$name"
|
|
||||||
}
|
|
||||||
|
|
||||||
board_name() {
|
|
||||||
if [ -r /tmp/sysinfo/board_name ]; then
|
|
||||||
cat /tmp/sysinfo/board_name
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -r /etc/openwrt_release ]; then
|
|
||||||
(
|
|
||||||
. /etc/openwrt_release 2>/dev/null
|
|
||||||
printf '%s' "${DISTRIB_TARGET:-openwrt}"
|
|
||||||
)
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
printf 'openwrt'
|
|
||||||
}
|
|
||||||
|
|
||||||
release_text() {
|
|
||||||
if [ -r /etc/openwrt_release ]; then
|
|
||||||
(
|
|
||||||
. /etc/openwrt_release 2>/dev/null
|
|
||||||
printf '%s %s' "${DISTRIB_ID:-OpenWrt}" "${DISTRIB_RELEASE:-unknown}"
|
|
||||||
)
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
printf 'OpenWrt unknown'
|
|
||||||
}
|
|
||||||
|
|
||||||
write_command_output() {
|
|
||||||
local out
|
|
||||||
out="$1"
|
|
||||||
shift
|
|
||||||
"$@" >"$out" 2>"$out.err" || true
|
|
||||||
if [ ! -s "$out.err" ]; then
|
|
||||||
rm -f "$out.err"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
validate_tar_paths() {
|
|
||||||
local archive label
|
|
||||||
archive="$1"
|
|
||||||
label="$2"
|
|
||||||
|
|
||||||
if tar -tzf "$archive" | grep -Eq '(^/|(^|/)\.\.(/|$))'; then
|
|
||||||
die "$label содержит небезопасные пути"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
create_metadata() {
|
|
||||||
local meta packages firmware
|
|
||||||
meta="$WORKDIR/meta"
|
|
||||||
packages="$WORKDIR/packages"
|
|
||||||
firmware="$WORKDIR/firmware"
|
|
||||||
mkdir -p "$meta" "$packages" "$firmware"
|
|
||||||
|
|
||||||
cat >"$WORKDIR/MANIFEST" <<EOF
|
|
||||||
format=$FORMAT
|
|
||||||
tool_version=$VERSION
|
|
||||||
created_at_utc=$(date -u '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || date)
|
|
||||||
hostname=$(hostname 2>/dev/null || printf 'openwrt')
|
|
||||||
board=$(board_name)
|
|
||||||
release=$(release_text)
|
|
||||||
kernel=$(uname -a 2>/dev/null || true)
|
|
||||||
EOF
|
|
||||||
|
|
||||||
copy_if_exists /etc/openwrt_release "$meta/openwrt_release"
|
|
||||||
copy_if_exists /etc/openwrt_version "$meta/openwrt_version"
|
|
||||||
copy_if_exists /etc/board.json "$meta/board.json"
|
|
||||||
copy_if_exists /etc/sysupgrade.conf "$meta/sysupgrade.conf"
|
|
||||||
copy_if_exists /proc/mtd "$meta/proc-mtd.txt"
|
|
||||||
copy_if_exists /proc/partitions "$meta/proc-partitions.txt"
|
|
||||||
|
|
||||||
write_command_output "$meta/uname.txt" uname -a
|
|
||||||
write_command_output "$meta/mounts.txt" mount
|
|
||||||
write_command_output "$meta/df-h.txt" df -h
|
|
||||||
|
|
||||||
if command -v ubus >/dev/null 2>&1; then
|
|
||||||
write_command_output "$meta/system-board.json" ubus call system board
|
|
||||||
fi
|
|
||||||
|
|
||||||
if command -v uci >/dev/null 2>&1; then
|
|
||||||
write_command_output "$meta/uci-show.txt" uci show
|
|
||||||
fi
|
|
||||||
|
|
||||||
if command -v opkg >/dev/null 2>&1; then
|
|
||||||
write_command_output "$packages/installed.txt" opkg list-installed
|
|
||||||
write_command_output "$packages/print-architecture.txt" opkg print-architecture
|
|
||||||
write_command_output "$packages/changed-conffiles.txt" opkg list-changed-conffiles
|
|
||||||
copy_if_exists /usr/lib/opkg/status "$packages/opkg-status"
|
|
||||||
else
|
|
||||||
printf 'opkg недоступен на этой системе.\n' >"$packages/installed.txt"
|
|
||||||
fi
|
|
||||||
|
|
||||||
cat >"$firmware/README.txt" <<'EOF'
|
|
||||||
OpenWrt обычно не хранит исходный sysupgrade-образ на роутере.
|
|
||||||
Используй --firmware-image /path/to/openwrt-sysupgrade.bin при создании
|
|
||||||
бэкапа, если хочешь добавить в архив прошиваемый firmware image.
|
|
||||||
|
|
||||||
Raw MTD dumps можно добавить через --include-raw-mtd, но они завязаны на
|
|
||||||
конкретное железо и разметку flash. Прошивка таких dump на другом устройстве
|
|
||||||
или другой разметке может окончательно сломать роутер.
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
create_sysupgrade_backup() {
|
|
||||||
if command -v sysupgrade >/dev/null 2>&1; then
|
|
||||||
if sysupgrade -b "$WORKDIR/config-backup.tar.gz" >/dev/null 2>"$WORKDIR/meta/sysupgrade-backup.err"; then
|
|
||||||
rm -f "$WORKDIR/meta/sysupgrade-backup.err"
|
|
||||||
else
|
|
||||||
warn "sysupgrade config backup не сработал; делаю fallback-снимок /etc"
|
|
||||||
tar -czf "$WORKDIR/config-backup.tar.gz" -C / etc 2>"$WORKDIR/meta/etc-backup.err" || die "не удалось создать config backup"
|
|
||||||
fi
|
|
||||||
sysupgrade -l >"$WORKDIR/meta/sysupgrade-file-list.txt" 2>/dev/null || true
|
|
||||||
else
|
|
||||||
warn "команда sysupgrade не найдена; делаю tar-снимок /etc"
|
|
||||||
tar -czf "$WORKDIR/config-backup.tar.gz" -C / etc 2>"$WORKDIR/meta/etc-backup.err" || die "не удалось создать config backup"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
create_overlay_snapshot() {
|
|
||||||
if [ ! -d /overlay/upper ]; then
|
|
||||||
printf 'Папка /overlay/upper на этой системе не найдена.\n' >"$WORKDIR/overlay-upper.README.txt"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
if tar -czf "$WORKDIR/overlay-upper.tar.gz" -C /overlay/upper . 2>"$WORKDIR/meta/overlay-upper.err"; then
|
|
||||||
rm -f "$WORKDIR/meta/overlay-upper.err"
|
|
||||||
else
|
|
||||||
warn "снимок overlay не получился; бэкап продолжится без него"
|
|
||||||
rm -f "$WORKDIR/overlay-upper.tar.gz"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
create_rom_snapshot() {
|
|
||||||
if [ ! -d /rom ]; then
|
|
||||||
printf 'Папка /rom на этой системе не найдена.\n' >"$WORKDIR/rom-rootfs.README.txt"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
if tar -czf "$WORKDIR/rom-rootfs.tar.gz" -C /rom . 2>"$WORKDIR/meta/rom-rootfs.err"; then
|
|
||||||
rm -f "$WORKDIR/meta/rom-rootfs.err"
|
|
||||||
else
|
|
||||||
warn "снимок ROM rootfs не получился; бэкап продолжится без него"
|
|
||||||
rm -f "$WORKDIR/rom-rootfs.tar.gz"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
copy_firmware_image() {
|
|
||||||
local image base
|
|
||||||
image="$1"
|
|
||||||
[ -n "$image" ] || return
|
|
||||||
[ -r "$image" ] || die "firmware image недоступен для чтения: $image"
|
|
||||||
|
|
||||||
base="$(basename "$image")"
|
|
||||||
mkdir -p "$WORKDIR/firmware"
|
|
||||||
cp "$image" "$WORKDIR/firmware/$base" || die "не удалось скопировать firmware image"
|
|
||||||
if command -v sha256sum >/dev/null 2>&1; then
|
|
||||||
(
|
|
||||||
cd "$WORKDIR/firmware" && sha256sum "$base" >"$base.sha256"
|
|
||||||
) || true
|
|
||||||
fi
|
|
||||||
printf '%s\n' "$base" >"$WORKDIR/firmware/IMAGE"
|
|
||||||
}
|
|
||||||
|
|
||||||
dump_raw_mtd() {
|
|
||||||
local raw line dev name safe out
|
|
||||||
if [ ! -r /proc/mtd ]; then
|
|
||||||
warn "/proc/mtd недоступен; raw MTD dump пропущен"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
raw="$WORKDIR/raw-mtd"
|
|
||||||
mkdir -p "$raw"
|
|
||||||
cp /proc/mtd "$raw/proc-mtd.txt" 2>/dev/null || true
|
|
||||||
|
|
||||||
while IFS= read -r line; do
|
|
||||||
case "$line" in
|
|
||||||
mtd*:*)
|
|
||||||
dev="${line%%:*}"
|
|
||||||
name="$(printf '%s\n' "$line" | sed 's/.*"\(.*\)".*/\1/')"
|
|
||||||
safe="$(sanitize "$name")"
|
|
||||||
if [ -e "/dev/$dev" ]; then
|
|
||||||
log "Сохраняю /dev/$dev ($name)"
|
|
||||||
out="$raw/$dev-$safe.bin"
|
|
||||||
if dd if="/dev/$dev" of="$out" bs=64k 2>"$raw/$dev-$safe.dd.log"; then
|
|
||||||
:
|
|
||||||
else
|
|
||||||
rm -f "$out"
|
|
||||||
warn "не удалось сохранить /dev/$dev"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done </proc/mtd
|
|
||||||
}
|
|
||||||
|
|
||||||
prune_old_backups() {
|
|
||||||
local output_dir keep_days
|
|
||||||
output_dir="$1"
|
|
||||||
keep_days="$2"
|
|
||||||
|
|
||||||
case "$keep_days" in
|
|
||||||
''|0) return ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
case "$keep_days" in
|
|
||||||
*[!0-9]*)
|
|
||||||
warn "keep_days должен быть числом; очистка пропущена"
|
|
||||||
return
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
find "$output_dir" -type f -name '*-owrt-full-backup.tar.gz' -mtime "+$keep_days" -exec rm -f {} \; 2>/dev/null || true
|
|
||||||
find "$output_dir" -type f -name '*-owrt-full-backup.tar.gz.sha256' -mtime "+$keep_days" -exec rm -f {} \; 2>/dev/null || true
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd_create() {
|
|
||||||
local output_dir name include_overlay include_rom include_raw_mtd firmware_image timestamp host board archive keep_days
|
|
||||||
output_dir="$(uci_get output_dir "$DEFAULT_OUTPUT_DIR")"
|
|
||||||
include_overlay="$(uci_get include_overlay 1)"
|
|
||||||
include_rom="$(uci_get include_rom 0)"
|
|
||||||
include_raw_mtd="$(uci_get include_raw_mtd 0)"
|
|
||||||
keep_days="$(uci_get keep_days 0)"
|
|
||||||
name=""
|
|
||||||
firmware_image=""
|
|
||||||
|
|
||||||
while [ $# -gt 0 ]; do
|
|
||||||
case "$1" in
|
|
||||||
-o|--output-dir)
|
|
||||||
[ $# -ge 2 ] || die "$1 требует папку"
|
|
||||||
output_dir="$2"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
-n|--name)
|
|
||||||
[ $# -ge 2 ] || die "$1 требует имя"
|
|
||||||
name="$2"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--no-overlay)
|
|
||||||
include_overlay=0
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
--include-rom)
|
|
||||||
include_rom=1
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
--firmware-image)
|
|
||||||
[ $# -ge 2 ] || die "$1 требует файл"
|
|
||||||
firmware_image="$2"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--include-raw-mtd)
|
|
||||||
include_raw_mtd=1
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
-h|--help)
|
|
||||||
usage
|
|
||||||
exit 0
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
die "неизвестная опция create: $1"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
need_cmd tar
|
|
||||||
need_cmd gzip
|
|
||||||
mkdir -p "$output_dir" || die "не удалось создать папку для архива: $output_dir"
|
|
||||||
if [ "$include_raw_mtd" = "1" ] && is_tmp_path "$output_dir"; then
|
|
||||||
die "raw MTD dump нельзя сохранять в /tmp: там обычно мало RAM. Укажи USB/диск, например /mnt/usb, или отключи raw MTD dump."
|
|
||||||
fi
|
|
||||||
make_workdir "$output_dir"
|
|
||||||
|
|
||||||
timestamp="$(date '+%Y%m%d-%H%M%S' 2>/dev/null || date '+%s')"
|
|
||||||
host="$(hostname_safe)"
|
|
||||||
board="$(sanitize "$(board_name)")"
|
|
||||||
if [ -z "$name" ]; then
|
|
||||||
name="$host-$board-$timestamp-owrt-full-backup"
|
|
||||||
fi
|
|
||||||
archive="$output_dir/$name.tar.gz"
|
|
||||||
|
|
||||||
log "Готовлю временную папку для бэкапа"
|
|
||||||
create_metadata
|
|
||||||
create_sysupgrade_backup
|
|
||||||
|
|
||||||
if [ "$include_overlay" = "1" ]; then
|
|
||||||
log "Добавляю снимок overlay"
|
|
||||||
create_overlay_snapshot
|
|
||||||
else
|
|
||||||
printf 'Снимок overlay отключен опцией.\n' >"$WORKDIR/overlay-upper.README.txt"
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ "$include_rom" = "1" ]; then
|
|
||||||
log "Добавляю снимок ROM rootfs"
|
|
||||||
create_rom_snapshot
|
|
||||||
else
|
|
||||||
printf 'Снимок ROM rootfs отключен опцией.\n' >"$WORKDIR/rom-rootfs.README.txt"
|
|
||||||
fi
|
|
||||||
|
|
||||||
copy_firmware_image "$firmware_image"
|
|
||||||
|
|
||||||
if [ "$include_raw_mtd" = "1" ]; then
|
|
||||||
warn "raw MTD dumps завязаны на конкретное устройство и могут быть очень большими"
|
|
||||||
dump_raw_mtd
|
|
||||||
fi
|
|
||||||
|
|
||||||
if tar -czf "$archive" -C "$WORKDIR" .; then
|
|
||||||
:
|
|
||||||
else
|
|
||||||
die "не удалось создать архив: $archive"
|
|
||||||
fi
|
|
||||||
|
|
||||||
if command -v sha256sum >/dev/null 2>&1; then
|
|
||||||
sha256sum "$archive" >"$archive.sha256" 2>/dev/null || true
|
|
||||||
fi
|
|
||||||
|
|
||||||
prune_old_backups "$output_dir" "$keep_days"
|
|
||||||
log "Бэкап создан: $archive"
|
|
||||||
if [ -f "$archive.sha256" ]; then
|
|
||||||
log "Checksum создан: $archive.sha256"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
extract_archive() {
|
|
||||||
local archive
|
|
||||||
archive="$1"
|
|
||||||
[ -r "$archive" ] || die "архив недоступен для чтения: $archive"
|
|
||||||
need_cmd tar
|
|
||||||
need_cmd gzip
|
|
||||||
validate_tar_paths "$archive" "archive"
|
|
||||||
make_workdir
|
|
||||||
tar -xzf "$archive" -C "$WORKDIR" || die "не удалось распаковать архив"
|
|
||||||
[ -r "$WORKDIR/MANIFEST" ] || die "в архиве нет MANIFEST"
|
|
||||||
grep -q "^format=$FORMAT" "$WORKDIR/MANIFEST" || die "неподдерживаемый формат бэкапа"
|
|
||||||
}
|
|
||||||
|
|
||||||
show_manifest_summary() {
|
|
||||||
local count
|
|
||||||
if [ -r "$WORKDIR/MANIFEST" ]; then
|
|
||||||
sed -n '1,40p' "$WORKDIR/MANIFEST"
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -r "$WORKDIR/packages/installed.txt" ]; then
|
|
||||||
count="$(grep -c ' - ' "$WORKDIR/packages/installed.txt" 2>/dev/null)"
|
|
||||||
[ -n "$count" ] || count=0
|
|
||||||
printf 'installed_packages_count=%s\n' "$count"
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -r "$WORKDIR/firmware/IMAGE" ]; then
|
|
||||||
printf 'firmware_image=%s\n' "$(cat "$WORKDIR/firmware/IMAGE")"
|
|
||||||
else
|
|
||||||
printf 'firmware_image=not_included\n'
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -r "$WORKDIR/overlay-upper.tar.gz" ]; then
|
|
||||||
printf 'overlay_snapshot=included\n'
|
|
||||||
else
|
|
||||||
printf 'overlay_snapshot=not_included\n'
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -r "$WORKDIR/rom-rootfs.tar.gz" ]; then
|
|
||||||
printf 'rom_rootfs_snapshot=included\n'
|
|
||||||
else
|
|
||||||
printf 'rom_rootfs_snapshot=not_included\n'
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ -d "$WORKDIR/raw-mtd" ]; then
|
|
||||||
printf 'raw_mtd=included\n'
|
|
||||||
else
|
|
||||||
printf 'raw_mtd=not_included\n'
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
confirm_restore() {
|
|
||||||
local yes answer
|
|
||||||
yes="$1"
|
|
||||||
if [ "$yes" = "1" ]; then
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
printf 'Это изменит файлы на OpenWrt-устройстве. Введи "yes" для продолжения: ' >&2
|
|
||||||
read -r answer
|
|
||||||
[ "$answer" = "yes" ] || die "восстановление отменено"
|
|
||||||
}
|
|
||||||
|
|
||||||
restore_configs() {
|
|
||||||
if [ ! -r "$WORKDIR/config-backup.tar.gz" ]; then
|
|
||||||
warn "config-backup.tar.gz не найден; восстановление настроек пропущено"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
log "Восстанавливаю config backup"
|
|
||||||
validate_tar_paths "$WORKDIR/config-backup.tar.gz" "config backup"
|
|
||||||
tar -xzpf "$WORKDIR/config-backup.tar.gz" -C / || die "восстановление настроек не удалось"
|
|
||||||
}
|
|
||||||
|
|
||||||
restore_packages() {
|
|
||||||
local installed line pkg failed
|
|
||||||
installed="$WORKDIR/packages/installed.txt"
|
|
||||||
[ -r "$installed" ] || {
|
|
||||||
warn "список пакетов не найден; восстановление пакетов пропущено"
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if ! command -v opkg >/dev/null 2>&1; then
|
|
||||||
warn "opkg не найден; восстановление пакетов пропущено"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
log "Обновляю списки пакетов"
|
|
||||||
opkg update || warn "opkg update не сработал; установка пакетов все равно будет попробована"
|
|
||||||
|
|
||||||
failed=0
|
|
||||||
while IFS= read -r line; do
|
|
||||||
case "$line" in
|
|
||||||
*' - '*)
|
|
||||||
pkg="${line%% - *}"
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
continue
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
if opkg status "$pkg" 2>/dev/null | grep -q '^Status:.* installed'; then
|
|
||||||
continue
|
|
||||||
fi
|
|
||||||
|
|
||||||
log "Устанавливаю пакет: $pkg"
|
|
||||||
if ! opkg install "$pkg"; then
|
|
||||||
warn "не удалось установить пакет: $pkg"
|
|
||||||
failed=1
|
|
||||||
fi
|
|
||||||
done <"$installed"
|
|
||||||
|
|
||||||
if [ "$failed" = "1" ]; then
|
|
||||||
warn "часть пакетов не установилась; проверь совместимость feeds с этой версией OpenWrt"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
restore_overlay() {
|
|
||||||
if [ ! -r "$WORKDIR/overlay-upper.tar.gz" ]; then
|
|
||||||
warn "снимок overlay не найден; восстановление overlay пропущено"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
warn "overlay лучше восстанавливать на том же устройстве и той же версии OpenWrt"
|
|
||||||
log "Восстанавливаю overlay snapshot в /"
|
|
||||||
validate_tar_paths "$WORKDIR/overlay-upper.tar.gz" "overlay snapshot"
|
|
||||||
tar -xzpf "$WORKDIR/overlay-upper.tar.gz" -C / || die "восстановление overlay не удалось"
|
|
||||||
}
|
|
||||||
|
|
||||||
flash_firmware() {
|
|
||||||
local image_name image_path
|
|
||||||
[ -r "$WORKDIR/firmware/IMAGE" ] || die "в архиве нет firmware image"
|
|
||||||
image_name="$(cat "$WORKDIR/firmware/IMAGE")"
|
|
||||||
case "$image_name" in
|
|
||||||
*/*|../*|*/../*|..)
|
|
||||||
die "имя firmware image небезопасно"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
image_path="$WORKDIR/firmware/$image_name"
|
|
||||||
[ -r "$image_path" ] || die "firmware image указан в архиве, но файл отсутствует: $image_name"
|
|
||||||
command -v sysupgrade >/dev/null 2>&1 || die "команда sysupgrade не найдена"
|
|
||||||
|
|
||||||
warn "sysupgrade прошьет firmware и перезагрузит устройство"
|
|
||||||
sysupgrade "$image_path"
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd_restore() {
|
|
||||||
local archive yes do_configs do_packages do_overlay do_flash
|
|
||||||
[ $# -ge 1 ] || die "restore требует путь к архиву"
|
|
||||||
archive="$1"
|
|
||||||
shift
|
|
||||||
|
|
||||||
yes=0
|
|
||||||
do_configs=1
|
|
||||||
do_packages=1
|
|
||||||
do_overlay=0
|
|
||||||
do_flash=0
|
|
||||||
|
|
||||||
while [ $# -gt 0 ]; do
|
|
||||||
case "$1" in
|
|
||||||
--yes)
|
|
||||||
yes=1
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
--no-configs)
|
|
||||||
do_configs=0
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
--no-packages)
|
|
||||||
do_packages=0
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
--overlay)
|
|
||||||
do_overlay=1
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
--flash-firmware)
|
|
||||||
do_flash=1
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
-h|--help)
|
|
||||||
usage
|
|
||||||
exit 0
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
die "неизвестная опция restore: $1"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
extract_archive "$archive"
|
|
||||||
show_manifest_summary >&2
|
|
||||||
confirm_restore "$yes"
|
|
||||||
|
|
||||||
if [ "$do_flash" = "1" ]; then
|
|
||||||
flash_firmware
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ "$do_configs" = "1" ]; then
|
|
||||||
restore_configs
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ "$do_packages" = "1" ]; then
|
|
||||||
restore_packages
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ "$do_overlay" = "1" ]; then
|
|
||||||
restore_overlay
|
|
||||||
fi
|
|
||||||
|
|
||||||
log "Восстановление завершено. Рекомендуется перезагрузка."
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd_inspect() {
|
|
||||||
[ $# -ge 1 ] || die "inspect требует путь к архиву"
|
|
||||||
extract_archive "$1"
|
|
||||||
show_manifest_summary
|
|
||||||
}
|
|
||||||
|
|
||||||
main() {
|
|
||||||
local cmd
|
|
||||||
cmd="${1:-help}"
|
|
||||||
case "$cmd" in
|
|
||||||
create)
|
|
||||||
shift
|
|
||||||
cmd_create "$@"
|
|
||||||
;;
|
|
||||||
restore)
|
|
||||||
shift
|
|
||||||
cmd_restore "$@"
|
|
||||||
;;
|
|
||||||
inspect)
|
|
||||||
shift
|
|
||||||
cmd_inspect "$@"
|
|
||||||
;;
|
|
||||||
help|-h|--help)
|
|
||||||
usage
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
die "неизвестная команда: $cmd"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
@@ -1,278 +0,0 @@
|
|||||||
#!/usr/bin/ucode
|
|
||||||
'use strict';
|
|
||||||
|
|
||||||
import * as fs from 'fs';
|
|
||||||
|
|
||||||
const default_dir = ARGV[0] || '/tmp';
|
|
||||||
const content_type = getenv('CONTENT_TYPE') || '';
|
|
||||||
let input_available = +getenv('CONTENT_LENGTH') || 0;
|
|
||||||
let input = fs.fdopen(0, 'r');
|
|
||||||
let output = fs.fdopen(1, 'w');
|
|
||||||
let error = fs.fdopen(2, 'w');
|
|
||||||
let pending = '';
|
|
||||||
let target_tmp = null;
|
|
||||||
|
|
||||||
function cleanup() {
|
|
||||||
if (target_tmp)
|
|
||||||
fs.unlink(target_tmp);
|
|
||||||
}
|
|
||||||
|
|
||||||
function fail(message) {
|
|
||||||
cleanup();
|
|
||||||
error.write('ОШИБКА: ' + message + '\n');
|
|
||||||
exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ok(message) {
|
|
||||||
output.write(message + '\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
function valid_path(path) {
|
|
||||||
return type(path) == 'string' && match(path, /^\/[A-Za-z0-9._\/-]+$/);
|
|
||||||
}
|
|
||||||
|
|
||||||
function safe_filename(name) {
|
|
||||||
name = name != null ? '' + name : '';
|
|
||||||
name = replace(name, /\\/g, '/');
|
|
||||||
name = fs.basename(name);
|
|
||||||
return replace(name, /[^A-Za-z0-9._-]/g, '_');
|
|
||||||
}
|
|
||||||
|
|
||||||
function trim_crlf(line) {
|
|
||||||
line = line != null ? '' + line : '';
|
|
||||||
line = replace(line, /\r\n$/, '');
|
|
||||||
return replace(line, /\n$/, '');
|
|
||||||
}
|
|
||||||
|
|
||||||
function append_array(array, value) {
|
|
||||||
array[length(array)] = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function concat_array(array, separator) {
|
|
||||||
let result = '';
|
|
||||||
|
|
||||||
for (let i = 0; i < length(array); i++) {
|
|
||||||
if (i > 0)
|
|
||||||
result += separator;
|
|
||||||
|
|
||||||
result += array[i];
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
function read_from_stdin(size) {
|
|
||||||
if (input_available <= 0)
|
|
||||||
return null;
|
|
||||||
|
|
||||||
size = size != null ? size : 8192;
|
|
||||||
let chunk = input.read(min(input_available, size, 8192));
|
|
||||||
|
|
||||||
if (chunk == null) {
|
|
||||||
input_available = 0;
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
input_available -= length(chunk);
|
|
||||||
return chunk;
|
|
||||||
}
|
|
||||||
|
|
||||||
function read_line() {
|
|
||||||
while (true) {
|
|
||||||
let pos = index(pending, '\n');
|
|
||||||
|
|
||||||
if (pos != null && pos >= 0) {
|
|
||||||
let line = substr(pending, 0, pos + 1);
|
|
||||||
pending = substr(pending, pos + 1);
|
|
||||||
return line;
|
|
||||||
}
|
|
||||||
|
|
||||||
let chunk = read_from_stdin(1024);
|
|
||||||
|
|
||||||
if (chunk == null) {
|
|
||||||
if (length(pending) > 0) {
|
|
||||||
let line = pending;
|
|
||||||
pending = '';
|
|
||||||
return line;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
pending += chunk;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let boundary_match = match(content_type, /boundary="?([^";]+)"?/);
|
|
||||||
let boundary = boundary_match ? boundary_match[1] : null;
|
|
||||||
|
|
||||||
if (!boundary)
|
|
||||||
fail('multipart boundary не найден');
|
|
||||||
|
|
||||||
if (input_available <= 0)
|
|
||||||
fail('пустой upload');
|
|
||||||
|
|
||||||
const marker = '--' + boundary;
|
|
||||||
const delimiter = '\r\n' + marker;
|
|
||||||
|
|
||||||
let first_line = trim_crlf(read_line());
|
|
||||||
if (first_line != marker)
|
|
||||||
fail('multipart boundary не найден в теле запроса');
|
|
||||||
|
|
||||||
function read_headers() {
|
|
||||||
let headers = [];
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
let line = read_line();
|
|
||||||
|
|
||||||
if (line == null)
|
|
||||||
fail('не удалось прочитать заголовки upload');
|
|
||||||
|
|
||||||
line = trim_crlf(line);
|
|
||||||
|
|
||||||
if (line == '')
|
|
||||||
break;
|
|
||||||
|
|
||||||
append_array(headers, line);
|
|
||||||
}
|
|
||||||
|
|
||||||
return concat_array(headers, '\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
function read_part(out, max_text) {
|
|
||||||
let keep = length(delimiter) + 4;
|
|
||||||
let buffer = '';
|
|
||||||
let text = [];
|
|
||||||
let text_size = 0;
|
|
||||||
let part_size = 0;
|
|
||||||
|
|
||||||
function consume(data) {
|
|
||||||
if (data == null || length(data) == 0)
|
|
||||||
return;
|
|
||||||
|
|
||||||
part_size += length(data);
|
|
||||||
|
|
||||||
if (out) {
|
|
||||||
out.write(data);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
text_size += length(data);
|
|
||||||
|
|
||||||
max_text = max_text != null ? max_text : 4096;
|
|
||||||
|
|
||||||
if (text_size > max_text)
|
|
||||||
fail('поле формы слишком большое');
|
|
||||||
|
|
||||||
append_array(text, data);
|
|
||||||
}
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
let chunk;
|
|
||||||
|
|
||||||
if (length(pending) > 0) {
|
|
||||||
chunk = pending;
|
|
||||||
pending = '';
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
chunk = read_from_stdin(8192);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (chunk == null)
|
|
||||||
fail('не найден конец multipart upload');
|
|
||||||
|
|
||||||
buffer += chunk;
|
|
||||||
|
|
||||||
let start_pos = index(buffer, delimiter);
|
|
||||||
|
|
||||||
if (start_pos != null && start_pos >= 0) {
|
|
||||||
consume(substr(buffer, 0, start_pos));
|
|
||||||
|
|
||||||
let after = start_pos + length(delimiter);
|
|
||||||
let final = false;
|
|
||||||
|
|
||||||
if (substr(buffer, after, 2) == '--') {
|
|
||||||
final = true;
|
|
||||||
after += 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (substr(buffer, after, 2) == '\r\n')
|
|
||||||
after += 2;
|
|
||||||
|
|
||||||
pending = substr(buffer, after);
|
|
||||||
return [ final, concat_array(text, ''), part_size ];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (length(buffer) > keep) {
|
|
||||||
consume(substr(buffer, 0, length(buffer) - keep));
|
|
||||||
buffer = substr(buffer, length(buffer) - keep);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let upload_dir = default_dir;
|
|
||||||
let saved_path = null;
|
|
||||||
let saved_size = 0;
|
|
||||||
let final = false;
|
|
||||||
|
|
||||||
while (!final) {
|
|
||||||
let headers = read_headers();
|
|
||||||
let disposition_match = match(headers, /[Cc]ontent-[Dd]isposition:\s*([^\n]+)/);
|
|
||||||
let disposition = disposition_match ? disposition_match[1] : null;
|
|
||||||
let name_match = disposition ? match(disposition, /name="([^"]+)"/) : null;
|
|
||||||
let filename_match = disposition ? match(disposition, /filename="([^"]*)"/) : null;
|
|
||||||
let name = name_match ? name_match[1] : null;
|
|
||||||
let filename = filename_match ? filename_match[1] : null;
|
|
||||||
|
|
||||||
if (name == 'upload_dir' && filename == null) {
|
|
||||||
let part = read_part(null, 4096);
|
|
||||||
final = part[0];
|
|
||||||
upload_dir = part[1] != null ? '' + part[1] : '';
|
|
||||||
upload_dir = replace(upload_dir, /[\r\n]/g, '');
|
|
||||||
}
|
|
||||||
else if (name == 'archive' && filename != null && filename != '') {
|
|
||||||
if (!valid_path(upload_dir))
|
|
||||||
fail('неверная папка для загрузки: ' + upload_dir);
|
|
||||||
|
|
||||||
let file_name = safe_filename(filename);
|
|
||||||
|
|
||||||
if (!file_name)
|
|
||||||
fail('файл архива не выбран');
|
|
||||||
|
|
||||||
if (!match(file_name, /\.tar\.gz$/))
|
|
||||||
fail('можно загружать только архивы .tar.gz');
|
|
||||||
|
|
||||||
fs.mkdir(upload_dir, 0755);
|
|
||||||
|
|
||||||
let target = replace(upload_dir, /\/+$/, '') + '/' + file_name;
|
|
||||||
target_tmp = target + '.uploading.' + time() + '.' + input_available;
|
|
||||||
|
|
||||||
let out = fs.open(target_tmp, 'w', 384);
|
|
||||||
if (!out)
|
|
||||||
fail('не удалось открыть файл для записи: ' + target);
|
|
||||||
|
|
||||||
let part = read_part(out, 0);
|
|
||||||
final = part[0];
|
|
||||||
saved_size = part[2];
|
|
||||||
out.close();
|
|
||||||
|
|
||||||
if (saved_size <= 0)
|
|
||||||
fail('файл пустой');
|
|
||||||
|
|
||||||
if (!fs.rename(target_tmp, target))
|
|
||||||
fail('не удалось сохранить файл: ' + target);
|
|
||||||
|
|
||||||
target_tmp = null;
|
|
||||||
saved_path = target;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
let part = read_part(null, 1024);
|
|
||||||
final = part[0];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!saved_path)
|
|
||||||
fail('файл архива не выбран');
|
|
||||||
|
|
||||||
ok('Архив загружен: ' + saved_path);
|
|
||||||
ok('Размер: ' + saved_size + ' байт');
|
|
||||||
@@ -0,0 +1,428 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
CONFIG="owrtremote"
|
||||||
|
SECTION="main"
|
||||||
|
|
||||||
|
log() {
|
||||||
|
printf '%s\n' "$*" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
die() {
|
||||||
|
printf 'ОШИБКА: %s\n' "$*" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
cat <<'EOF'
|
||||||
|
Использование:
|
||||||
|
owrt-remote status
|
||||||
|
owrt-remote doctor
|
||||||
|
owrt-remote render-client [--stdout]
|
||||||
|
owrt-remote run
|
||||||
|
owrt-remote heartbeat
|
||||||
|
owrt-remote heartbeat-loop
|
||||||
|
|
||||||
|
Настройки лежат в /etc/config/owrtremote.
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
uci_get() {
|
||||||
|
local key default value
|
||||||
|
key="$1"
|
||||||
|
default="$2"
|
||||||
|
value="$(uci -q get "$CONFIG.$SECTION.$key" 2>/dev/null || true)"
|
||||||
|
[ -n "$value" ] && {
|
||||||
|
printf '%s' "$value"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
printf '%s' "$default"
|
||||||
|
}
|
||||||
|
|
||||||
|
truthy() {
|
||||||
|
case "$1" in
|
||||||
|
1|yes|true|on|enabled) return 0 ;;
|
||||||
|
*) return 1 ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
json_escape() {
|
||||||
|
printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g; s/ /\\t/g'
|
||||||
|
}
|
||||||
|
|
||||||
|
json_string() {
|
||||||
|
printf '"%s"' "$(json_escape "$1")"
|
||||||
|
}
|
||||||
|
|
||||||
|
safe_num() {
|
||||||
|
case "$1" in
|
||||||
|
''|*[!0-9]*) printf '%s' "$2" ;;
|
||||||
|
*) printf '%s' "$1" ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
safe_id() {
|
||||||
|
printf '%s' "$1" | tr -cs 'A-Za-z0-9._-' '-'
|
||||||
|
}
|
||||||
|
|
||||||
|
host_model() {
|
||||||
|
if [ -r /tmp/sysinfo/model ]; then
|
||||||
|
cat /tmp/sysinfo/model
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
if [ -r /proc/device-tree/model ]; then
|
||||||
|
tr -d '\000' </proc/device-tree/model
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
printf 'OpenWrt router'
|
||||||
|
}
|
||||||
|
|
||||||
|
board_name() {
|
||||||
|
if [ -r /tmp/sysinfo/board_name ]; then
|
||||||
|
cat /tmp/sysinfo/board_name
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
printf 'unknown'
|
||||||
|
}
|
||||||
|
|
||||||
|
release_text() {
|
||||||
|
if [ -r /etc/openwrt_release ]; then
|
||||||
|
(
|
||||||
|
. /etc/openwrt_release 2>/dev/null
|
||||||
|
printf '%s %s' "${DISTRIB_ID:-OpenWrt}" "${DISTRIB_RELEASE:-unknown}"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
printf 'OpenWrt unknown'
|
||||||
|
}
|
||||||
|
|
||||||
|
uptime_seconds() {
|
||||||
|
if [ -r /proc/uptime ]; then
|
||||||
|
cut -d. -f1 /proc/uptime
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
printf '0'
|
||||||
|
}
|
||||||
|
|
||||||
|
load_text() {
|
||||||
|
if [ -r /proc/loadavg ]; then
|
||||||
|
awk '{print $1" "$2" "$3}' /proc/loadavg
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
printf '0 0 0'
|
||||||
|
}
|
||||||
|
|
||||||
|
memory_text() {
|
||||||
|
if [ -r /proc/meminfo ]; then
|
||||||
|
awk '
|
||||||
|
/^MemTotal:/ { total=$2 }
|
||||||
|
/^MemAvailable:/ { avail=$2 }
|
||||||
|
/^MemFree:/ && avail=="" { avail=$2 }
|
||||||
|
END {
|
||||||
|
if (total == "") total = 0
|
||||||
|
if (avail == "") avail = 0
|
||||||
|
printf "%s/%s kB", avail, total
|
||||||
|
}
|
||||||
|
' /proc/meminfo
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
printf '0/0 kB'
|
||||||
|
}
|
||||||
|
|
||||||
|
ps_all() {
|
||||||
|
ps w 2>/dev/null || ps 2>/dev/null || true
|
||||||
|
}
|
||||||
|
|
||||||
|
xray_running() {
|
||||||
|
local config
|
||||||
|
config="$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
|
||||||
|
ps_all | grep '[x]ray' | grep -F "$config" >/dev/null 2>&1
|
||||||
|
}
|
||||||
|
|
||||||
|
service_enabled() {
|
||||||
|
/etc/init.d/owrt-remote enabled >/dev/null 2>&1
|
||||||
|
}
|
||||||
|
|
||||||
|
render_client_config() {
|
||||||
|
local out stdout router_id vps_host vps_port uuid encryption flow reverse_tag admin_host admin_port xray_config
|
||||||
|
stdout="0"
|
||||||
|
if [ "${1:-}" = "--stdout" ]; then
|
||||||
|
stdout="1"
|
||||||
|
fi
|
||||||
|
|
||||||
|
router_id="$(safe_id "$(uci_get router_id main)")"
|
||||||
|
vps_host="$(uci_get vps_host '')"
|
||||||
|
vps_port="$(safe_num "$(uci_get vps_port 8443)" 8443)"
|
||||||
|
uuid="$(uci_get vless_uuid '')"
|
||||||
|
encryption="$(uci_get vless_encryption none)"
|
||||||
|
flow="$(uci_get vless_flow '')"
|
||||||
|
reverse_tag="$(safe_id "$(uci_get reverse_tag reverse-in)")"
|
||||||
|
admin_host="$(uci_get admin_host 127.0.0.1)"
|
||||||
|
admin_port="$(safe_num "$(uci_get admin_port 80)" 80)"
|
||||||
|
xray_config="$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
|
||||||
|
|
||||||
|
[ -n "$vps_host" ] || die "vps_host пустой"
|
||||||
|
[ -n "$uuid" ] || die "vless_uuid пустой"
|
||||||
|
|
||||||
|
out="${TMPDIR:-/tmp}/owrt-remote-client.$$"
|
||||||
|
cat >"$out" <<EOF
|
||||||
|
{
|
||||||
|
"log": {
|
||||||
|
"loglevel": "warning"
|
||||||
|
},
|
||||||
|
"inbounds": [],
|
||||||
|
"outbounds": [
|
||||||
|
{
|
||||||
|
"tag": "router-admin",
|
||||||
|
"protocol": "freedom",
|
||||||
|
"settings": {
|
||||||
|
"redirect": "$(json_escape "$admin_host"):$admin_port",
|
||||||
|
"finalRules": [
|
||||||
|
{
|
||||||
|
"action": "allow",
|
||||||
|
"network": "tcp",
|
||||||
|
"ip": "$(json_escape "$admin_host")",
|
||||||
|
"port": "$admin_port"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tag": "$(json_escape "$reverse_tag")",
|
||||||
|
"protocol": "vless",
|
||||||
|
"settings": {
|
||||||
|
"address": "$(json_escape "$vps_host")",
|
||||||
|
"port": $vps_port,
|
||||||
|
"id": "$(json_escape "$uuid")",
|
||||||
|
"encryption": "$(json_escape "$encryption")",
|
||||||
|
"flow": "$(json_escape "$flow")",
|
||||||
|
"reverse": {
|
||||||
|
"tag": "$(json_escape "$reverse_tag")"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"streamSettings": {
|
||||||
|
"network": "tcp",
|
||||||
|
"security": "none"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"routing": {
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"inboundTag": [
|
||||||
|
"$(json_escape "$reverse_tag")"
|
||||||
|
],
|
||||||
|
"outboundTag": "router-admin"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"remarks": "OpenWrt Remote client for $(json_escape "$router_id")"
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
if [ "$stdout" = "1" ]; then
|
||||||
|
cat "$out"
|
||||||
|
rm -f "$out"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$(dirname "$xray_config")"
|
||||||
|
cp "$out" "$xray_config"
|
||||||
|
chmod 0600 "$xray_config"
|
||||||
|
rm -f "$out"
|
||||||
|
printf '%s\n' "$xray_config"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_xray() {
|
||||||
|
local enabled xray_bin xray_config
|
||||||
|
enabled="$(uci_get enabled 0)"
|
||||||
|
truthy "$enabled" || die "сервис выключен: включи option enabled '1'"
|
||||||
|
|
||||||
|
xray_bin="$(uci_get xray_bin /usr/bin/xray)"
|
||||||
|
xray_config="$(render_client_config)"
|
||||||
|
[ -x "$xray_bin" ] || die "xray не найден или не исполняемый: $xray_bin"
|
||||||
|
|
||||||
|
if "$xray_bin" help 2>/dev/null | grep -q 'run'; then
|
||||||
|
exec "$xray_bin" run -config "$xray_config"
|
||||||
|
fi
|
||||||
|
exec "$xray_bin" -config "$xray_config"
|
||||||
|
}
|
||||||
|
|
||||||
|
heartbeat_json() {
|
||||||
|
local router_id router_name role public_url hub_url xray_state service_state
|
||||||
|
router_id="$(safe_id "$(uci_get router_id main)")"
|
||||||
|
router_name="$(uci_get router_name "$router_id")"
|
||||||
|
role="$(uci_get role node)"
|
||||||
|
public_url="$(uci_get public_url '')"
|
||||||
|
hub_url="$(uci_get hub_url '')"
|
||||||
|
|
||||||
|
if xray_running; then
|
||||||
|
xray_state="running"
|
||||||
|
else
|
||||||
|
xray_state="stopped"
|
||||||
|
fi
|
||||||
|
if service_enabled; then
|
||||||
|
service_state="enabled"
|
||||||
|
else
|
||||||
|
service_state="disabled"
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat <<EOF
|
||||||
|
{
|
||||||
|
"id": $(json_string "$router_id"),
|
||||||
|
"name": $(json_string "$router_name"),
|
||||||
|
"role": $(json_string "$role"),
|
||||||
|
"model": $(json_string "$(host_model)"),
|
||||||
|
"board": $(json_string "$(board_name)"),
|
||||||
|
"release": $(json_string "$(release_text)"),
|
||||||
|
"hostname": $(json_string "$(hostname 2>/dev/null || printf openwrt)"),
|
||||||
|
"public_url": $(json_string "$public_url"),
|
||||||
|
"admin_host": $(json_string "$(uci_get admin_host 127.0.0.1)"),
|
||||||
|
"admin_port": $(safe_num "$(uci_get admin_port 80)" 80),
|
||||||
|
"hub_url": $(json_string "$hub_url"),
|
||||||
|
"uptime": $(safe_num "$(uptime_seconds)" 0),
|
||||||
|
"load": $(json_string "$(load_text)"),
|
||||||
|
"memory": $(json_string "$(memory_text)"),
|
||||||
|
"xray": $(json_string "$xray_state"),
|
||||||
|
"service": $(json_string "$service_state")
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
post_json() {
|
||||||
|
local url token file
|
||||||
|
url="$1"
|
||||||
|
token="$2"
|
||||||
|
file="$3"
|
||||||
|
|
||||||
|
if command -v uclient-fetch >/dev/null 2>&1; then
|
||||||
|
uclient-fetch -q -O - \
|
||||||
|
--header="Authorization: Bearer $token" \
|
||||||
|
--header="Content-Type: application/json" \
|
||||||
|
--post-file="$file" "$url"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
if command -v wget >/dev/null 2>&1; then
|
||||||
|
wget -q -O - \
|
||||||
|
--header="Authorization: Bearer $token" \
|
||||||
|
--header="Content-Type: application/json" \
|
||||||
|
--post-file="$file" "$url"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
if command -v curl >/dev/null 2>&1; then
|
||||||
|
curl -fsS \
|
||||||
|
-H "Authorization: Bearer $token" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
--data-binary "@$file" "$url"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
die "для heartbeat нужен uclient-fetch, wget или curl"
|
||||||
|
}
|
||||||
|
|
||||||
|
send_heartbeat() {
|
||||||
|
local hub_url token endpoint tmp
|
||||||
|
hub_url="$(uci_get hub_url '')"
|
||||||
|
token="$(uci_get hub_token '')"
|
||||||
|
[ -n "$hub_url" ] || die "hub_url пустой"
|
||||||
|
[ -n "$token" ] || die "hub_token пустой"
|
||||||
|
|
||||||
|
endpoint="${hub_url%/}/api/heartbeat"
|
||||||
|
tmp="${TMPDIR:-/tmp}/owrt-remote-heartbeat.$$"
|
||||||
|
heartbeat_json >"$tmp"
|
||||||
|
post_json "$endpoint" "$token" "$tmp"
|
||||||
|
rm -f "$tmp"
|
||||||
|
}
|
||||||
|
|
||||||
|
heartbeat_loop() {
|
||||||
|
local interval
|
||||||
|
interval="$(safe_num "$(uci_get heartbeat_interval 30)" 30)"
|
||||||
|
[ "$interval" -lt 10 ] && interval=10
|
||||||
|
while :; do
|
||||||
|
send_heartbeat >/dev/null 2>&1 || true
|
||||||
|
sleep "$interval"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
status() {
|
||||||
|
printf 'router_id: %s\n' "$(uci_get router_id main)"
|
||||||
|
printf 'router_name: %s\n' "$(uci_get router_name '')"
|
||||||
|
printf 'enabled: %s\n' "$(uci_get enabled 0)"
|
||||||
|
printf 'hub_url: %s\n' "$(uci_get hub_url '')"
|
||||||
|
printf 'vps_host: %s\n' "$(uci_get vps_host '')"
|
||||||
|
printf 'vps_port: %s\n' "$(uci_get vps_port 8443)"
|
||||||
|
printf 'xray_bin: %s\n' "$(uci_get xray_bin /usr/bin/xray)"
|
||||||
|
printf 'xray_config: %s\n' "$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
|
||||||
|
if xray_running; then
|
||||||
|
printf 'xray_state: running\n'
|
||||||
|
else
|
||||||
|
printf 'xray_state: stopped\n'
|
||||||
|
fi
|
||||||
|
if service_enabled; then
|
||||||
|
printf 'service: enabled\n'
|
||||||
|
else
|
||||||
|
printf 'service: disabled\n'
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
doctor() {
|
||||||
|
local ok xray_bin
|
||||||
|
ok=1
|
||||||
|
xray_bin="$(uci_get xray_bin /usr/bin/xray)"
|
||||||
|
|
||||||
|
[ -x "$xray_bin" ] || {
|
||||||
|
log "нет Xray: $xray_bin"
|
||||||
|
ok=0
|
||||||
|
}
|
||||||
|
[ -n "$(uci_get hub_url '')" ] || {
|
||||||
|
log "hub_url пустой"
|
||||||
|
ok=0
|
||||||
|
}
|
||||||
|
[ -n "$(uci_get hub_token '')" ] || {
|
||||||
|
log "hub_token пустой"
|
||||||
|
ok=0
|
||||||
|
}
|
||||||
|
[ -n "$(uci_get vps_host '')" ] || {
|
||||||
|
log "vps_host пустой"
|
||||||
|
ok=0
|
||||||
|
}
|
||||||
|
[ -n "$(uci_get vless_uuid '')" ] || {
|
||||||
|
log "vless_uuid пустой"
|
||||||
|
ok=0
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ "$ok" = "1" ]; then
|
||||||
|
printf '%s\n' "OK: конфиг выглядит готовым"
|
||||||
|
else
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd="${1:-help}"
|
||||||
|
shift || true
|
||||||
|
|
||||||
|
case "$cmd" in
|
||||||
|
help|-h|--help)
|
||||||
|
usage
|
||||||
|
;;
|
||||||
|
status)
|
||||||
|
status
|
||||||
|
;;
|
||||||
|
doctor)
|
||||||
|
doctor
|
||||||
|
;;
|
||||||
|
render-client)
|
||||||
|
render_client_config "$@"
|
||||||
|
;;
|
||||||
|
run)
|
||||||
|
run_xray
|
||||||
|
;;
|
||||||
|
heartbeat)
|
||||||
|
send_heartbeat
|
||||||
|
;;
|
||||||
|
heartbeat-loop)
|
||||||
|
heartbeat_loop
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
usage >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
{
|
|
||||||
"admin/services/owrt-full-backup": {
|
|
||||||
"title": "OpenWrt Full Backup",
|
|
||||||
"order": 90,
|
|
||||||
"action": {
|
|
||||||
"type": "view",
|
|
||||||
"path": "owrt_full_backup"
|
|
||||||
},
|
|
||||||
"depends": {
|
|
||||||
"acl": [
|
|
||||||
"luci-app-owrt-full-backup"
|
|
||||||
],
|
|
||||||
"fs": {
|
|
||||||
"/www/cgi-bin/owrt-full-backup": "executable"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"admin/services/owrt-remote": {
|
||||||
|
"title": "OpenWrt Remote",
|
||||||
|
"order": 91,
|
||||||
|
"action": {
|
||||||
|
"type": "view",
|
||||||
|
"path": "owrt_remote"
|
||||||
|
},
|
||||||
|
"depends": {
|
||||||
|
"acl": [
|
||||||
|
"luci-app-owrt-remote"
|
||||||
|
],
|
||||||
|
"fs": {
|
||||||
|
"/www/cgi-bin/owrt-remote": "executable"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
{
|
|
||||||
"luci-app-owrt-full-backup": {
|
|
||||||
"description": "Grant access to OpenWrt Full Backup LuCI helper",
|
|
||||||
"read": {
|
|
||||||
"ubus": {
|
|
||||||
"file": [
|
|
||||||
"read"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"file": {
|
|
||||||
"/etc/owrt-full-backup/web.key": [
|
|
||||||
"read"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"luci-app-owrt-remote": {
|
||||||
|
"description": "Grant access to OpenWrt Remote LuCI helper",
|
||||||
|
"read": {
|
||||||
|
"ubus": {
|
||||||
|
"file": [
|
||||||
|
"read"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"file": {
|
||||||
|
"/etc/owrt-remote/web.key": [
|
||||||
|
"read"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -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';
|
'use strict';
|
||||||
'require view';
|
'require view';
|
||||||
'require fs';
|
'require fs';
|
||||||
'require ui';
|
|
||||||
|
|
||||||
return view.extend({
|
return view.extend({
|
||||||
load: function() {
|
load: function() {
|
||||||
return fs.read('/etc/owrt-full-backup/web.key').catch(function() {
|
return fs.read('/etc/owrt-remote/web.key').catch(function() {
|
||||||
return '';
|
return '';
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -15,24 +14,24 @@ return view.extend({
|
|||||||
|
|
||||||
if (!key) {
|
if (!key) {
|
||||||
return E('div', { 'class': 'cbi-map' }, [
|
return E('div', { 'class': 'cbi-map' }, [
|
||||||
E('h2', {}, _('OpenWrt Full Backup')),
|
E('h2', {}, _('OpenWrt Remote')),
|
||||||
E('div', { 'class': 'alert-message warning' }, [
|
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.setTimeout(function() {
|
||||||
window.location.replace(url);
|
window.location.replace(url);
|
||||||
}, 100);
|
}, 100);
|
||||||
|
|
||||||
return E('div', { 'class': 'cbi-map' }, [
|
return E('div', { 'class': 'cbi-map' }, [
|
||||||
E('h2', {}, _('OpenWrt Full Backup')),
|
E('h2', {}, _('OpenWrt Remote')),
|
||||||
E('p', {}, _('Открываю веб-панель полного бэкапа...')),
|
E('p', {}, _('Opening remote access panel...')),
|
||||||
E('p', {}, [
|
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,
|
handleSave: null,
|
||||||
handleReset: null
|
handleReset: null
|
||||||
});
|
});
|
||||||
|
|
||||||
+16
-16
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
RAW_URL="${RAW_URL:-https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-full-backup/main}"
|
RAW_URL="${RAW_URL:-https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main}"
|
||||||
ROOT="${ROOT:-/}"
|
ROOT="${ROOT:-/}"
|
||||||
SCRIPT_DIR="$(CDPATH= cd "$(dirname "$0")" 2>/dev/null && pwd)"
|
SCRIPT_DIR="$(CDPATH= cd "$(dirname "$0")" 2>/dev/null && pwd)"
|
||||||
|
|
||||||
@@ -50,12 +50,12 @@ install_file() {
|
|||||||
|
|
||||||
install_config() {
|
install_config() {
|
||||||
local rel src dst bust
|
local rel src dst bust
|
||||||
rel="etc/config/fullbackup"
|
rel="etc/config/owrtremote"
|
||||||
src="$SCRIPT_DIR/files/$rel"
|
src="$SCRIPT_DIR/files/$rel"
|
||||||
dst="$(target_path "$rel")"
|
dst="$(target_path "$rel")"
|
||||||
mkdir -p "$(dirname "$dst")"
|
mkdir -p "$(dirname "$dst")"
|
||||||
if [ -f "$dst" ]; then
|
if [ -f "$dst" ]; then
|
||||||
info "Оставляю существующий файл: $dst"
|
info "Оставляю существующий конфиг: $dst"
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
if [ -f "$src" ]; then
|
if [ -f "$src" ]; then
|
||||||
@@ -69,7 +69,7 @@ install_config() {
|
|||||||
|
|
||||||
make_key() {
|
make_key() {
|
||||||
local key_dir key_file key
|
local key_dir key_file key
|
||||||
key_dir="$(target_path etc/owrt-full-backup)"
|
key_dir="$(target_path etc/owrt-remote)"
|
||||||
key_file="$key_dir/web.key"
|
key_file="$key_dir/web.key"
|
||||||
mkdir -p "$key_dir"
|
mkdir -p "$key_dir"
|
||||||
if [ ! -s "$key_file" ]; then
|
if [ ! -s "$key_file" ]; then
|
||||||
@@ -101,16 +101,15 @@ router_ip() {
|
|||||||
printf '192.168.1.1'
|
printf '192.168.1.1'
|
||||||
}
|
}
|
||||||
|
|
||||||
install_file "usr/sbin/owrt-full-backup" 0755
|
install_file "usr/sbin/owrt-remote" 0755
|
||||||
install_file "usr/sbin/owrt-full-backup-upload" 0755
|
install_file "etc/init.d/owrt-remote" 0755
|
||||||
ln -sf owrt-full-backup "$(target_path usr/sbin/owrt-backup)"
|
|
||||||
install_config
|
install_config
|
||||||
install_file "www/cgi-bin/owrt-full-backup" 0755
|
install_file "www/cgi-bin/owrt-remote" 0755
|
||||||
install_file "usr/share/luci/menu.d/luci-app-owrt-full-backup.json" 0644
|
install_file "usr/share/luci/menu.d/luci-app-owrt-remote.json" 0644
|
||||||
install_file "usr/share/rpcd/acl.d/luci-app-owrt-full-backup.json" 0644
|
install_file "usr/share/rpcd/acl.d/luci-app-owrt-remote.json" 0644
|
||||||
install_file "www/luci-static/resources/view/owrt_full_backup.js" 0644
|
install_file "www/luci-static/resources/view/owrt_remote.js" 0644
|
||||||
rm -f "$(target_path usr/lib/lua/luci/controller/owrt_full_backup.lua)" 2>/dev/null || true
|
|
||||||
|
|
||||||
|
rm -f "$(target_path usr/lib/lua/luci/controller/owrt_remote.lua)" 2>/dev/null || true
|
||||||
rm -rf "$(target_path tmp/luci-indexcache)" "$(target_path tmp/luci-modulecache)" "$(target_path tmp/luci-indexcache.)"* "$(target_path tmp/luci-modulecache.)"* 2>/dev/null || true
|
rm -rf "$(target_path tmp/luci-indexcache)" "$(target_path tmp/luci-modulecache)" "$(target_path tmp/luci-indexcache.)"* "$(target_path tmp/luci-modulecache.)"* 2>/dev/null || true
|
||||||
|
|
||||||
if [ -x "$(target_path etc/init.d/rpcd)" ]; then
|
if [ -x "$(target_path etc/init.d/rpcd)" ]; then
|
||||||
@@ -124,7 +123,8 @@ fi
|
|||||||
key="$(make_key)"
|
key="$(make_key)"
|
||||||
ip="$(router_ip)"
|
ip="$(router_ip)"
|
||||||
|
|
||||||
info "Веб-панель OpenWrt Full Backup установлена."
|
info "OpenWrt Remote установлен."
|
||||||
info "LuCI: Службы -> OpenWrt Full Backup"
|
info "LuCI: Службы -> OpenWrt Remote"
|
||||||
info "Открыть: http://$ip/cgi-bin/owrt-full-backup?key=$key"
|
info "Панель: http://$ip/cgi-bin/owrt-remote?key=$key"
|
||||||
info "CLI: owrt-full-backup create -o /mnt/usb"
|
info "CLI: owrt-remote doctor"
|
||||||
|
|
||||||
+19
-13
@@ -13,19 +13,24 @@ rmf() {
|
|||||||
rm -f "$(target_path "$1")"
|
rm -f "$(target_path "$1")"
|
||||||
}
|
}
|
||||||
|
|
||||||
rmf usr/sbin/owrt-full-backup
|
if [ -x "$(target_path etc/init.d/owrt-remote)" ]; then
|
||||||
rmf usr/sbin/owrt-full-backup-upload
|
"$(target_path etc/init.d/owrt-remote)" stop >/dev/null 2>&1 || true
|
||||||
rmf usr/sbin/owrt-backup
|
"$(target_path etc/init.d/owrt-remote)" disable >/dev/null 2>&1 || true
|
||||||
rmf www/cgi-bin/owrt-full-backup
|
fi
|
||||||
rmf usr/lib/lua/luci/controller/owrt_full_backup.lua
|
|
||||||
rmf usr/share/luci/menu.d/luci-app-owrt-full-backup.json
|
rmf usr/sbin/owrt-remote
|
||||||
rmf usr/share/rpcd/acl.d/luci-app-owrt-full-backup.json
|
rmf etc/init.d/owrt-remote
|
||||||
rmf www/luci-static/resources/view/owrt_full_backup.js
|
rmf www/cgi-bin/owrt-remote
|
||||||
|
rmf usr/lib/lua/luci/controller/owrt_remote.lua
|
||||||
|
rmf usr/share/luci/menu.d/luci-app-owrt-remote.json
|
||||||
|
rmf usr/share/rpcd/acl.d/luci-app-owrt-remote.json
|
||||||
|
rmf www/luci-static/resources/view/owrt_remote.js
|
||||||
|
|
||||||
if [ "$PURGE" = "1" ]; then
|
if [ "$PURGE" = "1" ]; then
|
||||||
rmf etc/config/fullbackup
|
rmf etc/config/owrtremote
|
||||||
rmf etc/owrt-full-backup/web.key
|
rmf etc/owrt-remote/web.key
|
||||||
rmdir "$(target_path etc/owrt-full-backup)" 2>/dev/null || true
|
rm -f "$(target_path etc/xray/owrt-remote-client.json)" 2>/dev/null || true
|
||||||
|
rmdir "$(target_path etc/owrt-remote)" 2>/dev/null || true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
rm -rf "$(target_path tmp/luci-indexcache)" "$(target_path tmp/luci-modulecache)" "$(target_path tmp/luci-indexcache.)"* "$(target_path tmp/luci-modulecache.)"* 2>/dev/null || true
|
rm -rf "$(target_path tmp/luci-indexcache)" "$(target_path tmp/luci-modulecache)" "$(target_path tmp/luci-indexcache.)"* "$(target_path tmp/luci-modulecache.)"* 2>/dev/null || true
|
||||||
@@ -38,7 +43,8 @@ if [ -x "$(target_path etc/init.d/uhttpd)" ]; then
|
|||||||
"$(target_path etc/init.d/uhttpd)" reload >/dev/null 2>&1 || "$(target_path etc/init.d/uhttpd)" restart >/dev/null 2>&1 || true
|
"$(target_path etc/init.d/uhttpd)" reload >/dev/null 2>&1 || "$(target_path etc/init.d/uhttpd)" restart >/dev/null 2>&1 || true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
printf '%s\n' "Веб-панель OpenWrt Full Backup удалена."
|
printf '%s\n' "OpenWrt Remote удален."
|
||||||
if [ "$PURGE" != "1" ]; then
|
if [ "$PURGE" != "1" ]; then
|
||||||
printf '%s\n' "Конфиг и веб-ключ оставлены. Для полного удаления запусти с PURGE=1."
|
printf '%s\n' "Конфиг и web key оставлены. Для полного удаления запусти с PURGE=1."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -0,0 +1,992 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
import argparse
|
||||||
|
import datetime as dt
|
||||||
|
import html
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.parse
|
||||||
|
import uuid
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
APP_NAME = "OpenWrt Remote Hub"
|
||||||
|
STATE_DIR = Path(os.environ.get("OWRT_REMOTE_STATE_DIR", "/var/lib/owrt-remote"))
|
||||||
|
DB_PATH = Path(os.environ.get("OWRT_REMOTE_DB", str(STATE_DIR / "hub.db")))
|
||||||
|
ADMIN_TOKEN_FILE = STATE_DIR / "admin.token"
|
||||||
|
AGENT_TOKEN_FILE = STATE_DIR / "agent.token"
|
||||||
|
ONLINE_AFTER_SECONDS = int(os.environ.get("OWRT_REMOTE_ONLINE_AFTER", "75"))
|
||||||
|
DEFAULT_VLESS_PORT = int(os.environ.get("OWRT_REMOTE_VLESS_PORT", "8443"))
|
||||||
|
|
||||||
|
|
||||||
|
def now_ts():
|
||||||
|
return int(time.time())
|
||||||
|
|
||||||
|
|
||||||
|
def iso_time(ts):
|
||||||
|
if not ts:
|
||||||
|
return ""
|
||||||
|
return dt.datetime.fromtimestamp(int(ts), tz=dt.timezone.utc).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_state():
|
||||||
|
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def read_or_make_token(path):
|
||||||
|
ensure_state()
|
||||||
|
if path.exists():
|
||||||
|
token = path.read_text(encoding="utf-8").strip()
|
||||||
|
if token:
|
||||||
|
return token
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
path.write_text(token + "\n", encoding="utf-8")
|
||||||
|
try:
|
||||||
|
os.chmod(path, 0o600)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def admin_token():
|
||||||
|
return os.environ.get("OWRT_REMOTE_ADMIN_TOKEN") or read_or_make_token(ADMIN_TOKEN_FILE)
|
||||||
|
|
||||||
|
|
||||||
|
def agent_token():
|
||||||
|
return os.environ.get("OWRT_REMOTE_AGENT_TOKEN") or read_or_make_token(AGENT_TOKEN_FILE)
|
||||||
|
|
||||||
|
|
||||||
|
def clean_router_id(value):
|
||||||
|
value = (value or "").strip()
|
||||||
|
out = []
|
||||||
|
for ch in value:
|
||||||
|
if ch.isalnum() or ch in "._-":
|
||||||
|
out.append(ch)
|
||||||
|
else:
|
||||||
|
out.append("-")
|
||||||
|
result = "".join(out).strip(".-_")
|
||||||
|
if not result:
|
||||||
|
raise ValueError("router id is empty")
|
||||||
|
return result[:64]
|
||||||
|
|
||||||
|
|
||||||
|
def connect(db_path=DB_PATH):
|
||||||
|
ensure_state()
|
||||||
|
conn = sqlite3.connect(str(db_path))
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
def init_db(conn):
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
create table if not exists routers (
|
||||||
|
id text primary key,
|
||||||
|
name text not null,
|
||||||
|
role text not null default 'node',
|
||||||
|
entry_port integer not null default 0,
|
||||||
|
vps_host text not null default '',
|
||||||
|
vless_port integer not null default 8443,
|
||||||
|
vless_uuid text not null,
|
||||||
|
vless_encryption text not null default 'none',
|
||||||
|
vless_decryption text not null default 'none',
|
||||||
|
vless_flow text not null default '',
|
||||||
|
reverse_tag text not null default 'reverse-in',
|
||||||
|
public_url text not null default '',
|
||||||
|
admin_host text not null default '127.0.0.1',
|
||||||
|
admin_port integer not null default 80,
|
||||||
|
created_at integer not null,
|
||||||
|
updated_at integer not null,
|
||||||
|
last_seen integer,
|
||||||
|
status_json text not null default '{}'
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def get_router(conn, router_id):
|
||||||
|
return conn.execute("select * from routers where id = ?", (router_id,)).fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def list_router_rows(conn):
|
||||||
|
return conn.execute(
|
||||||
|
"""
|
||||||
|
select * from routers
|
||||||
|
order by case role when 'main' then 0 else 1 end, lower(id)
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
|
||||||
|
def row_to_router(row):
|
||||||
|
data = dict(row)
|
||||||
|
try:
|
||||||
|
status = json.loads(data.get("status_json") or "{}")
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
status = {}
|
||||||
|
last_seen = data.get("last_seen")
|
||||||
|
online = bool(last_seen and now_ts() - int(last_seen) <= ONLINE_AFTER_SECONDS)
|
||||||
|
data["status"] = status
|
||||||
|
data["online"] = online
|
||||||
|
data["last_seen_iso"] = iso_time(last_seen)
|
||||||
|
data["access_url"] = f"/access/{urllib.parse.quote(data['id'])}/"
|
||||||
|
data["config_url"] = f"/router/{urllib.parse.quote(data['id'])}/config"
|
||||||
|
data["xray_client_url"] = f"/router/{urllib.parse.quote(data['id'])}/xray-client.json"
|
||||||
|
data.pop("status_json", None)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def upsert_router(conn, values):
|
||||||
|
router_id = clean_router_id(values.get("id"))
|
||||||
|
current = get_router(conn, router_id)
|
||||||
|
ts = now_ts()
|
||||||
|
payload = {
|
||||||
|
"id": router_id,
|
||||||
|
"name": values.get("name") or router_id,
|
||||||
|
"role": values.get("role") or "node",
|
||||||
|
"entry_port": int(values.get("entry_port") or 0),
|
||||||
|
"vps_host": values.get("vps_host") or "",
|
||||||
|
"vless_port": int(values.get("vless_port") or DEFAULT_VLESS_PORT),
|
||||||
|
"vless_uuid": values.get("vless_uuid") or str(uuid.uuid4()),
|
||||||
|
"vless_encryption": values.get("vless_encryption") or "none",
|
||||||
|
"vless_decryption": values.get("vless_decryption") or "none",
|
||||||
|
"vless_flow": values.get("vless_flow") or "",
|
||||||
|
"reverse_tag": values.get("reverse_tag") or "reverse-in",
|
||||||
|
"public_url": values.get("public_url") or "",
|
||||||
|
"admin_host": values.get("admin_host") or "127.0.0.1",
|
||||||
|
"admin_port": int(values.get("admin_port") or 80),
|
||||||
|
"updated_at": ts,
|
||||||
|
}
|
||||||
|
if current:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
update routers set
|
||||||
|
name = :name,
|
||||||
|
role = :role,
|
||||||
|
entry_port = :entry_port,
|
||||||
|
vps_host = :vps_host,
|
||||||
|
vless_port = :vless_port,
|
||||||
|
vless_uuid = :vless_uuid,
|
||||||
|
vless_encryption = :vless_encryption,
|
||||||
|
vless_decryption = :vless_decryption,
|
||||||
|
vless_flow = :vless_flow,
|
||||||
|
reverse_tag = :reverse_tag,
|
||||||
|
public_url = :public_url,
|
||||||
|
admin_host = :admin_host,
|
||||||
|
admin_port = :admin_port,
|
||||||
|
updated_at = :updated_at
|
||||||
|
where id = :id
|
||||||
|
""",
|
||||||
|
payload,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
payload["created_at"] = ts
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
insert into routers (
|
||||||
|
id, name, role, entry_port, vps_host, vless_port, vless_uuid,
|
||||||
|
vless_encryption, vless_decryption, vless_flow, reverse_tag,
|
||||||
|
public_url, admin_host, admin_port, created_at, updated_at
|
||||||
|
) values (
|
||||||
|
:id, :name, :role, :entry_port, :vps_host, :vless_port, :vless_uuid,
|
||||||
|
:vless_encryption, :vless_decryption, :vless_flow, :reverse_tag,
|
||||||
|
:public_url, :admin_host, :admin_port, :created_at, :updated_at
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
payload,
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return get_router(conn, router_id)
|
||||||
|
|
||||||
|
|
||||||
|
def heartbeat(conn, payload):
|
||||||
|
router_id = clean_router_id(payload.get("id"))
|
||||||
|
row = get_router(conn, router_id)
|
||||||
|
ts = now_ts()
|
||||||
|
if not row:
|
||||||
|
row = upsert_router(
|
||||||
|
conn,
|
||||||
|
{
|
||||||
|
"id": router_id,
|
||||||
|
"name": payload.get("name") or router_id,
|
||||||
|
"role": payload.get("role") or "node",
|
||||||
|
"entry_port": payload.get("entry_port") or 0,
|
||||||
|
"vps_host": payload.get("vps_host") or "",
|
||||||
|
"admin_host": payload.get("admin_host") or "127.0.0.1",
|
||||||
|
"admin_port": payload.get("admin_port") or 80,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
update routers set
|
||||||
|
name = coalesce(nullif(?, ''), name),
|
||||||
|
role = coalesce(nullif(?, ''), role),
|
||||||
|
public_url = coalesce(nullif(?, ''), public_url),
|
||||||
|
admin_host = coalesce(nullif(?, ''), admin_host),
|
||||||
|
admin_port = coalesce(?, admin_port),
|
||||||
|
last_seen = ?,
|
||||||
|
status_json = ?,
|
||||||
|
updated_at = ?
|
||||||
|
where id = ?
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
payload.get("name") or "",
|
||||||
|
payload.get("role") or "",
|
||||||
|
payload.get("public_url") or "",
|
||||||
|
payload.get("admin_host") or "",
|
||||||
|
int(payload["admin_port"]) if str(payload.get("admin_port", "")).isdigit() else None,
|
||||||
|
ts,
|
||||||
|
json.dumps(payload, ensure_ascii=False, separators=(",", ":")),
|
||||||
|
ts,
|
||||||
|
router_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
return row_to_router(get_router(conn, router_id))
|
||||||
|
|
||||||
|
|
||||||
|
def make_server_xray_config(rows, listen_host="0.0.0.0", listen_port=DEFAULT_VLESS_PORT, decryption="none"):
|
||||||
|
clients = []
|
||||||
|
inbounds = [
|
||||||
|
{
|
||||||
|
"tag": "owrt-remote-vless",
|
||||||
|
"listen": listen_host,
|
||||||
|
"port": int(listen_port),
|
||||||
|
"protocol": "vless",
|
||||||
|
"settings": {
|
||||||
|
"clients": clients,
|
||||||
|
"decryption": decryption,
|
||||||
|
},
|
||||||
|
"streamSettings": {
|
||||||
|
"network": "tcp",
|
||||||
|
"security": "none",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
]
|
||||||
|
rules = []
|
||||||
|
|
||||||
|
for row in rows:
|
||||||
|
router_id = clean_router_id(row["id"])
|
||||||
|
entry_port = int(row["entry_port"] or 0)
|
||||||
|
if entry_port <= 0:
|
||||||
|
continue
|
||||||
|
reverse_out = f"reverse-{router_id}"
|
||||||
|
portal_in = f"portal-{router_id}"
|
||||||
|
client = {
|
||||||
|
"id": row["vless_uuid"],
|
||||||
|
"email": f"{router_id}@owrt-remote",
|
||||||
|
"reverse": {
|
||||||
|
"tag": reverse_out,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if row["vless_flow"]:
|
||||||
|
client["flow"] = row["vless_flow"]
|
||||||
|
clients.append(client)
|
||||||
|
inbounds.append(
|
||||||
|
{
|
||||||
|
"tag": portal_in,
|
||||||
|
"listen": "127.0.0.1",
|
||||||
|
"port": entry_port,
|
||||||
|
"protocol": "tunnel",
|
||||||
|
"settings": {
|
||||||
|
"allowedNetwork": "tcp",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
rules.append(
|
||||||
|
{
|
||||||
|
"type": "field",
|
||||||
|
"inboundTag": [portal_in],
|
||||||
|
"outboundTag": reverse_out,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"log": {"loglevel": "warning"},
|
||||||
|
"inbounds": inbounds,
|
||||||
|
"outbounds": [{"tag": "direct", "protocol": "freedom"}],
|
||||||
|
"routing": {"rules": rules},
|
||||||
|
"remarks": "OpenWrt Remote Hub server config",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def make_router_xray_config(row):
|
||||||
|
return {
|
||||||
|
"log": {"loglevel": "warning"},
|
||||||
|
"inbounds": [],
|
||||||
|
"outbounds": [
|
||||||
|
{
|
||||||
|
"tag": "router-admin",
|
||||||
|
"protocol": "freedom",
|
||||||
|
"settings": {
|
||||||
|
"redirect": f"{row['admin_host']}:{int(row['admin_port'])}",
|
||||||
|
"finalRules": [
|
||||||
|
{
|
||||||
|
"action": "allow",
|
||||||
|
"network": "tcp",
|
||||||
|
"ip": row["admin_host"],
|
||||||
|
"port": str(int(row["admin_port"])),
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tag": row["reverse_tag"],
|
||||||
|
"protocol": "vless",
|
||||||
|
"settings": {
|
||||||
|
"address": row["vps_host"],
|
||||||
|
"port": int(row["vless_port"]),
|
||||||
|
"id": row["vless_uuid"],
|
||||||
|
"encryption": row["vless_encryption"],
|
||||||
|
"flow": row["vless_flow"],
|
||||||
|
"reverse": {"tag": row["reverse_tag"]},
|
||||||
|
},
|
||||||
|
"streamSettings": {"network": "tcp", "security": "none"},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"routing": {
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"inboundTag": [row["reverse_tag"]],
|
||||||
|
"outboundTag": "router-admin",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"remarks": f"OpenWrt Remote client for {row['id']}",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def make_openwrt_config(row, hub_url):
|
||||||
|
lines = [
|
||||||
|
"uci -q delete owrtremote.main",
|
||||||
|
"uci set owrtremote.main=remote",
|
||||||
|
"uci set owrtremote.main.enabled='1'",
|
||||||
|
f"uci set owrtremote.main.router_id='{sh_quote(row['id'])}'",
|
||||||
|
f"uci set owrtremote.main.router_name='{sh_quote(row['name'])}'",
|
||||||
|
f"uci set owrtremote.main.role='{sh_quote(row['role'])}'",
|
||||||
|
f"uci set owrtremote.main.hub_url='{sh_quote(hub_url)}'",
|
||||||
|
f"uci set owrtremote.main.hub_token='{sh_quote(agent_token())}'",
|
||||||
|
"uci set owrtremote.main.heartbeat_interval='30'",
|
||||||
|
"uci set owrtremote.main.xray_bin='/usr/bin/xray'",
|
||||||
|
"uci set owrtremote.main.xray_config='/etc/xray/owrt-remote-client.json'",
|
||||||
|
f"uci set owrtremote.main.vps_host='{sh_quote(row['vps_host'])}'",
|
||||||
|
f"uci set owrtremote.main.vps_port='{int(row['vless_port'])}'",
|
||||||
|
f"uci set owrtremote.main.vless_uuid='{sh_quote(row['vless_uuid'])}'",
|
||||||
|
f"uci set owrtremote.main.vless_encryption='{sh_quote(row['vless_encryption'])}'",
|
||||||
|
f"uci set owrtremote.main.vless_flow='{sh_quote(row['vless_flow'])}'",
|
||||||
|
f"uci set owrtremote.main.reverse_tag='{sh_quote(row['reverse_tag'])}'",
|
||||||
|
f"uci set owrtremote.main.admin_host='{sh_quote(row['admin_host'])}'",
|
||||||
|
f"uci set owrtremote.main.admin_port='{int(row['admin_port'])}'",
|
||||||
|
f"uci set owrtremote.main.public_url='{sh_quote(row['public_url'])}'",
|
||||||
|
"uci commit owrtremote",
|
||||||
|
"owrt-remote render-client",
|
||||||
|
"/etc/init.d/owrt-remote enable",
|
||||||
|
"/etc/init.d/owrt-remote restart",
|
||||||
|
"owrt-remote heartbeat",
|
||||||
|
]
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def sh_quote(value):
|
||||||
|
return str(value).replace("'", "'\"'\"'")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_cookies(header):
|
||||||
|
cookies = {}
|
||||||
|
for chunk in (header or "").split(";"):
|
||||||
|
if "=" in chunk:
|
||||||
|
key, value = chunk.split("=", 1)
|
||||||
|
cookies[key.strip()] = value.strip()
|
||||||
|
return cookies
|
||||||
|
|
||||||
|
|
||||||
|
def clean_forward_cookie(cookie_header):
|
||||||
|
parts = []
|
||||||
|
for chunk in (cookie_header or "").split(";"):
|
||||||
|
if not chunk.strip():
|
||||||
|
continue
|
||||||
|
if chunk.strip().startswith("owrt_remote_admin="):
|
||||||
|
continue
|
||||||
|
parts.append(chunk.strip())
|
||||||
|
return "; ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def dashboard_html(routers, token):
|
||||||
|
routers_json = json.dumps(routers, ensure_ascii=False)
|
||||||
|
safe_token = html.escape(token, quote=True)
|
||||||
|
return f"""<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>{APP_NAME}</title>
|
||||||
|
<style>
|
||||||
|
:root{{color-scheme:light;--bg:#f5f7fb;--panel:#fff;--text:#152033;--muted:#687385;--line:#d9e1ec;--blue:#2563eb;--green:#16a34a;--red:#dc2626;--amber:#d97706;--teal:#0f766e}}
|
||||||
|
*{{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:1220px;margin:0 auto;padding:22px}}.top{{display:flex;align-items:center;justify-content:space-between;gap:16px;border-bottom:1px solid var(--line);padding:4px 0 18px}}
|
||||||
|
.brand{{display:flex;align-items:center;gap:14px}}.logo{{width:54px;height:54px;border-radius:8px;background:var(--teal);color:#fff;display:grid;place-items:center;font-weight:900;font-size:24px;box-shadow:0 14px 34px rgba(15,118,110,.22)}}
|
||||||
|
h1{{margin:0;font-size:29px;letter-spacing:0}}.muted{{color:var(--muted)}}.top p{{margin:4px 0 0}}.badge{{display:inline-flex;gap:8px;align-items:center;border:1px solid var(--line);background:#fff;border-radius:999px;padding:8px 12px;color:var(--muted);white-space:nowrap}}
|
||||||
|
.dot{{width:9px;height:9px;border-radius:999px;background:var(--red)}}.dot.on{{background:var(--green)}}.toolbar{{display:grid;grid-template-columns:1fr 1fr 110px 110px 150px auto;gap:10px;margin:18px 0;padding:14px;background:var(--panel);border:1px solid var(--line);border-radius:8px}}
|
||||||
|
input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding:10px 11px;background:#fff;color:var(--text)}}button,.btn{{border:0;border-radius:8px;padding:10px 13px;background:#e8eef8;color:#1f2a44;font-weight:800;text-decoration:none;cursor:pointer;display:inline-flex;justify-content:center;align-items:center}}button.primary,.btn.primary{{background:var(--blue);color:#fff}}button.bad{{background:#fee2e2;color:#991b1b}}
|
||||||
|
.cards{{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}}.card{{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:15px;box-shadow:0 12px 30px rgba(20,35,60,.05)}}
|
||||||
|
.cardHead{{display:flex;gap:12px;align-items:flex-start;justify-content:space-between}}.routerIcon{{width:46px;height:46px;border-radius:8px;background:#eef6ff;color:#1d4ed8;display:grid;place-items:center;font-weight:900;font-size:20px;border:1px solid #dbeafe}}
|
||||||
|
.title{{display:flex;gap:10px;align-items:center;min-width:0}}.title h2{{font-size:18px;margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}.role{{border:1px solid var(--line);border-radius:999px;padding:3px 8px;color:var(--muted);font-size:12px;background:#fbfdff}}
|
||||||
|
.state{{display:flex;align-items:center;gap:7px;font-weight:800}}.state.off{{color:var(--red)}}.state.on{{color:var(--green)}}.meta{{display:grid;grid-template-columns:1fr 1fr;gap:9px;margin:14px 0}}.metric{{border:1px solid var(--line);border-radius:8px;padding:10px;background:#fafcff}}.metric span{{display:block;color:var(--muted);font-size:12px}}.metric strong{{display:block;margin-top:3px;word-break:break-word}}
|
||||||
|
.actions{{display:flex;gap:8px;flex-wrap:wrap}}.empty{{border:1px dashed var(--line);border-radius:8px;padding:30px;background:#fff;text-align:center;color:var(--muted)}}.hint{{margin-top:16px;padding:13px;border:1px solid var(--line);border-radius:8px;background:#fff}}code{{background:#eef2f7;border-radius:6px;padding:2px 5px}}
|
||||||
|
@media(max-width:980px){{.cards{{grid-template-columns:repeat(2,minmax(0,1fr))}}.toolbar{{grid-template-columns:1fr 1fr}}}}
|
||||||
|
@media(max-width:680px){{.wrap{{padding:14px}}.cards,.toolbar{{grid-template-columns:1fr}}.top{{align-items:flex-start;flex-direction:column}}h1{{font-size:24px}}}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="wrap">
|
||||||
|
<section class="top">
|
||||||
|
<div class="brand">
|
||||||
|
<div class="logo">R</div>
|
||||||
|
<div>
|
||||||
|
<h1>OpenWrt Remote Hub</h1>
|
||||||
|
<p class="muted">Карточки роутеров, heartbeat и вход в LuCI через VPS.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="badge"><span class="dot on"></span>Hub online</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<form class="toolbar" id="routerForm">
|
||||||
|
<input name="id" placeholder="router id: main" required>
|
||||||
|
<input name="name" placeholder="Название роутера" required>
|
||||||
|
<select name="role"><option value="node">node</option><option value="main">main</option></select>
|
||||||
|
<input name="entry_port" placeholder="18080" inputmode="numeric" required>
|
||||||
|
<input name="vps_host" placeholder="VPS IP/domain" required>
|
||||||
|
<button class="primary">Добавить</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<section id="cards" class="cards"></section>
|
||||||
|
<div class="hint muted">После добавления роутера открой <code>OpenWrt config</code>, вставь команды на роутере и перегенерируй server Xray config командой <code>owrt-remote-hub.py render-xray --out /etc/xray/owrt-remote.json</code>.</div>
|
||||||
|
</main>
|
||||||
|
<script>
|
||||||
|
window.ADMIN_TOKEN = "{safe_token}";
|
||||||
|
window.ROUTERS = {routers_json};
|
||||||
|
const cards = document.getElementById('cards');
|
||||||
|
const tokenParam = () => 'token=' + encodeURIComponent(window.ADMIN_TOKEN);
|
||||||
|
|
||||||
|
function ago(iso) {{
|
||||||
|
if (!iso) return 'never';
|
||||||
|
const diff = Math.max(0, Math.floor((Date.now() - Date.parse(iso)) / 1000));
|
||||||
|
if (diff < 60) return diff + ' sec ago';
|
||||||
|
if (diff < 3600) return Math.floor(diff / 60) + ' min ago';
|
||||||
|
return Math.floor(diff / 3600) + ' h ago';
|
||||||
|
}}
|
||||||
|
|
||||||
|
function render(list) {{
|
||||||
|
if (!list.length) {{
|
||||||
|
cards.innerHTML = '<div class="empty">Пока нет роутеров. Добавь первый, например <b>main</b>.</div>';
|
||||||
|
return;
|
||||||
|
}}
|
||||||
|
cards.innerHTML = list.map(r => {{
|
||||||
|
const state = r.online ? 'on' : 'off';
|
||||||
|
const stateText = r.online ? 'online' : 'offline';
|
||||||
|
const model = (r.status && r.status.model) || r.status?.board || 'OpenWrt';
|
||||||
|
const release = (r.status && r.status.release) || 'waiting heartbeat';
|
||||||
|
const xray = (r.status && r.status.xray) || 'unknown';
|
||||||
|
const access = r.public_url || (r.access_url + '?' + tokenParam());
|
||||||
|
return `<article class="card">
|
||||||
|
<div class="cardHead">
|
||||||
|
<div class="title">
|
||||||
|
<div class="routerIcon">R</div>
|
||||||
|
<div>
|
||||||
|
<h2>${{escapeHtml(r.name)}}</h2>
|
||||||
|
<div class="muted">${{escapeHtml(r.id)}} · <span class="role">${{escapeHtml(r.role)}}</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="state ${{state}}"><span class="dot ${{state === 'on' ? 'on' : ''}}"></span>${{stateText}}</div>
|
||||||
|
</div>
|
||||||
|
<div class="meta">
|
||||||
|
<div class="metric"><span>Model</span><strong>${{escapeHtml(model)}}</strong></div>
|
||||||
|
<div class="metric"><span>OpenWrt</span><strong>${{escapeHtml(release)}}</strong></div>
|
||||||
|
<div class="metric"><span>Xray</span><strong>${{escapeHtml(xray)}}</strong></div>
|
||||||
|
<div class="metric"><span>Last seen</span><strong>${{escapeHtml(ago(r.last_seen_iso))}}</strong></div>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<a class="btn primary" href="${{access}}">Открыть админку</a>
|
||||||
|
<a class="btn" href="${{r.config_url}}?${{tokenParam()}}">OpenWrt config</a>
|
||||||
|
<a class="btn" href="${{r.xray_client_url}}?${{tokenParam()}}">Client JSON</a>
|
||||||
|
<button class="bad" data-delete="${{escapeHtml(r.id)}}">Удалить</button>
|
||||||
|
</div>
|
||||||
|
</article>`;
|
||||||
|
}}).join('');
|
||||||
|
}}
|
||||||
|
|
||||||
|
function escapeHtml(s) {{
|
||||||
|
return String(s ?? '').replace(/[&<>"']/g, ch => ({{'&':'&','<':'<','>':'>','"':'"',"'":'''}}[ch]));
|
||||||
|
}}
|
||||||
|
|
||||||
|
async function loadRouters() {{
|
||||||
|
const res = await fetch('/api/routers?' + tokenParam(), {{cache: 'no-store'}});
|
||||||
|
if (res.ok) {{
|
||||||
|
const data = await res.json();
|
||||||
|
window.ROUTERS = data.routers;
|
||||||
|
render(window.ROUTERS);
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
|
||||||
|
document.getElementById('routerForm').addEventListener('submit', async (ev) => {{
|
||||||
|
ev.preventDefault();
|
||||||
|
const body = new URLSearchParams(new FormData(ev.currentTarget));
|
||||||
|
const res = await fetch('/api/router?' + tokenParam(), {{method: 'POST', body}});
|
||||||
|
if (res.ok) {{
|
||||||
|
ev.currentTarget.reset();
|
||||||
|
await loadRouters();
|
||||||
|
}} else {{
|
||||||
|
alert(await res.text());
|
||||||
|
}}
|
||||||
|
}});
|
||||||
|
|
||||||
|
cards.addEventListener('click', async (ev) => {{
|
||||||
|
const id = ev.target?.dataset?.delete;
|
||||||
|
if (!id) return;
|
||||||
|
if (!confirm('Удалить роутер ' + id + '?')) return;
|
||||||
|
const res = await fetch('/api/router/' + encodeURIComponent(id) + '/delete?' + tokenParam(), {{method: 'POST'}});
|
||||||
|
if (res.ok) await loadRouters();
|
||||||
|
}});
|
||||||
|
|
||||||
|
render(window.ROUTERS);
|
||||||
|
setInterval(loadRouters, 5000);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>"""
|
||||||
|
|
||||||
|
|
||||||
|
def login_html():
|
||||||
|
return """<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenWrt Remote Hub</title>
|
||||||
|
<style>body{margin:0;background:#f5f7fb;color:#172033;font:14px/1.45 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.box{max-width:380px;margin:12vh auto;background:#fff;border:1px solid #d9e1ec;border-radius:8px;padding:20px;box-shadow:0 12px 30px rgba(20,35,60,.06)}h1{margin:0 0 8px;font-size:24px}p{color:#687385}input,button{width:100%;border-radius:8px;padding:11px;margin-top:10px}input{border:1px solid #d9e1ec}button{border:0;background:#2563eb;color:#fff;font-weight:800}</style></head>
|
||||||
|
<body><form class="box" method="get"><h1>OpenWrt Remote Hub</h1><p>Вставь ADMIN_TOKEN с VPS.</p><input name="token" type="password" autofocus><button>Открыть</button></form></body></html>"""
|
||||||
|
|
||||||
|
|
||||||
|
class App:
|
||||||
|
def __init__(self, db_path, admin, agent, public_url):
|
||||||
|
self.db_path = Path(db_path)
|
||||||
|
self.admin_token = admin
|
||||||
|
self.agent_token = agent
|
||||||
|
self.public_url = public_url.rstrip("/")
|
||||||
|
|
||||||
|
def conn(self):
|
||||||
|
conn = connect(self.db_path)
|
||||||
|
init_db(conn)
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
server_version = "owrt-remote-hub/1.0"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def app(self):
|
||||||
|
return self.server.app
|
||||||
|
|
||||||
|
def log_message(self, fmt, *args):
|
||||||
|
sys.stderr.write("%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), fmt % args))
|
||||||
|
|
||||||
|
def parsed(self):
|
||||||
|
return urllib.parse.urlsplit(self.path)
|
||||||
|
|
||||||
|
def query(self):
|
||||||
|
return urllib.parse.parse_qs(self.parsed().query)
|
||||||
|
|
||||||
|
def admin_ok(self):
|
||||||
|
query_token = self.query().get("token", [""])[0]
|
||||||
|
if secrets.compare_digest(query_token, self.app.admin_token):
|
||||||
|
return True
|
||||||
|
cookies = parse_cookies(self.headers.get("Cookie", ""))
|
||||||
|
return secrets.compare_digest(cookies.get("owrt_remote_admin", ""), self.app.admin_token)
|
||||||
|
|
||||||
|
def admin_cookie_needed(self):
|
||||||
|
query_token = self.query().get("token", [""])[0]
|
||||||
|
return secrets.compare_digest(query_token, self.app.admin_token)
|
||||||
|
|
||||||
|
def agent_ok(self):
|
||||||
|
auth = self.headers.get("Authorization", "")
|
||||||
|
if auth.startswith("Bearer "):
|
||||||
|
return secrets.compare_digest(auth[7:].strip(), self.app.agent_token)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def send_bytes(self, status, body, content_type="text/plain; charset=utf-8", extra_headers=None, set_cookie=False):
|
||||||
|
self.send_response(status)
|
||||||
|
self.send_header("Content-Type", content_type)
|
||||||
|
self.send_header("Cache-Control", "no-store")
|
||||||
|
if set_cookie:
|
||||||
|
self.send_header("Set-Cookie", f"owrt_remote_admin={self.app.admin_token}; HttpOnly; SameSite=Lax; Path=/")
|
||||||
|
if extra_headers:
|
||||||
|
for key, value in extra_headers:
|
||||||
|
self.send_header(key, value)
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def send_text(self, status, text, content_type="text/plain; charset=utf-8"):
|
||||||
|
self.send_bytes(status, text.encode("utf-8"), content_type, set_cookie=self.admin_cookie_needed())
|
||||||
|
|
||||||
|
def send_json(self, status, payload):
|
||||||
|
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||||
|
self.send_bytes(status, body, "application/json; charset=utf-8", set_cookie=self.admin_cookie_needed())
|
||||||
|
|
||||||
|
def require_admin(self):
|
||||||
|
if self.admin_ok():
|
||||||
|
return True
|
||||||
|
self.send_bytes(401, login_html().encode("utf-8"), "text/html; charset=utf-8")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def read_body(self):
|
||||||
|
length = int(self.headers.get("Content-Length", "0") or "0")
|
||||||
|
return self.rfile.read(length) if length else b""
|
||||||
|
|
||||||
|
def read_payload(self):
|
||||||
|
body = self.read_body()
|
||||||
|
ctype = self.headers.get("Content-Type", "")
|
||||||
|
if "application/json" in ctype:
|
||||||
|
return json.loads(body.decode("utf-8") or "{}")
|
||||||
|
parsed = urllib.parse.parse_qs(body.decode("utf-8"))
|
||||||
|
return {k: v[-1] for k, v in parsed.items()}
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
path = self.parsed().path
|
||||||
|
if path == "/health":
|
||||||
|
self.send_json(200, {"ok": True})
|
||||||
|
return
|
||||||
|
if path.startswith("/access/"):
|
||||||
|
self.proxy_access(path)
|
||||||
|
return
|
||||||
|
if not self.require_admin():
|
||||||
|
return
|
||||||
|
if path == "/" or path == "":
|
||||||
|
with self.app.conn() as conn:
|
||||||
|
routers = [row_to_router(r) for r in list_router_rows(conn)]
|
||||||
|
self.send_bytes(
|
||||||
|
200,
|
||||||
|
dashboard_html(routers, self.app.admin_token).encode("utf-8"),
|
||||||
|
"text/html; charset=utf-8",
|
||||||
|
set_cookie=self.admin_cookie_needed(),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
if path == "/api/routers":
|
||||||
|
with self.app.conn() as conn:
|
||||||
|
routers = [row_to_router(r) for r in list_router_rows(conn)]
|
||||||
|
self.send_json(200, {"routers": routers})
|
||||||
|
return
|
||||||
|
if path.startswith("/router/"):
|
||||||
|
self.router_asset(path)
|
||||||
|
return
|
||||||
|
self.send_text(404, "not found")
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
path = self.parsed().path
|
||||||
|
if path == "/api/heartbeat":
|
||||||
|
if not self.agent_ok():
|
||||||
|
self.send_json(401, {"ok": False, "error": "bad agent token"})
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
payload = self.read_payload()
|
||||||
|
with self.app.conn() as conn:
|
||||||
|
router = heartbeat(conn, payload)
|
||||||
|
self.send_json(200, {"ok": True, "router": router})
|
||||||
|
except Exception as exc:
|
||||||
|
self.send_json(400, {"ok": False, "error": str(exc)})
|
||||||
|
return
|
||||||
|
if path.startswith("/access/"):
|
||||||
|
self.proxy_access(path)
|
||||||
|
return
|
||||||
|
if not self.require_admin():
|
||||||
|
return
|
||||||
|
if path == "/api/router":
|
||||||
|
try:
|
||||||
|
payload = self.read_payload()
|
||||||
|
with self.app.conn() as conn:
|
||||||
|
row = upsert_router(conn, payload)
|
||||||
|
router = row_to_router(row)
|
||||||
|
self.send_json(200, {"ok": True, "router": router})
|
||||||
|
except Exception as exc:
|
||||||
|
self.send_text(400, str(exc))
|
||||||
|
return
|
||||||
|
if path.startswith("/api/router/") and path.endswith("/delete"):
|
||||||
|
router_id = urllib.parse.unquote(path.split("/")[3])
|
||||||
|
with self.app.conn() as conn:
|
||||||
|
conn.execute("delete from routers where id = ?", (router_id,))
|
||||||
|
conn.commit()
|
||||||
|
self.send_json(200, {"ok": True})
|
||||||
|
return
|
||||||
|
self.send_text(404, "not found")
|
||||||
|
|
||||||
|
def router_asset(self, path):
|
||||||
|
parts = path.strip("/").split("/")
|
||||||
|
if len(parts) != 3:
|
||||||
|
self.send_text(404, "not found")
|
||||||
|
return
|
||||||
|
_, router_id, asset = parts
|
||||||
|
router_id = urllib.parse.unquote(router_id)
|
||||||
|
with self.app.conn() as conn:
|
||||||
|
row = get_router(conn, router_id)
|
||||||
|
if not row:
|
||||||
|
self.send_text(404, "router not found")
|
||||||
|
return
|
||||||
|
hub_url = self.app.public_url or f"http://{self.headers.get('Host')}"
|
||||||
|
if asset == "config":
|
||||||
|
self.send_text(200, make_openwrt_config(row, hub_url))
|
||||||
|
return
|
||||||
|
if asset == "xray-client.json":
|
||||||
|
self.send_json(200, make_router_xray_config(row))
|
||||||
|
return
|
||||||
|
self.send_text(404, "not found")
|
||||||
|
|
||||||
|
def proxy_access(self, path):
|
||||||
|
if not self.require_admin():
|
||||||
|
return
|
||||||
|
parts = path.split("/", 3)
|
||||||
|
if len(parts) < 3:
|
||||||
|
self.redirect("/access/")
|
||||||
|
return
|
||||||
|
router_id = urllib.parse.unquote(parts[2])
|
||||||
|
rest = "/" + parts[3] if len(parts) == 4 else "/"
|
||||||
|
with self.app.conn() as conn:
|
||||||
|
row = get_router(conn, router_id)
|
||||||
|
if not row:
|
||||||
|
self.send_text(404, "router not found")
|
||||||
|
return
|
||||||
|
port = int(row["entry_port"] or 0)
|
||||||
|
if port <= 0:
|
||||||
|
self.send_text(400, "router has no entry_port")
|
||||||
|
return
|
||||||
|
|
||||||
|
query = urllib.parse.parse_qsl(self.parsed().query, keep_blank_values=True)
|
||||||
|
query = [(k, v) for k, v in query if k != "token"]
|
||||||
|
target = rest
|
||||||
|
if query:
|
||||||
|
target += "?" + urllib.parse.urlencode(query)
|
||||||
|
|
||||||
|
body = self.read_body() if self.command in ("POST", "PUT", "PATCH") else None
|
||||||
|
headers = {}
|
||||||
|
skip = {"host", "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers", "transfer-encoding", "upgrade", "content-length"}
|
||||||
|
for key, value in self.headers.items():
|
||||||
|
if key.lower() in skip:
|
||||||
|
continue
|
||||||
|
if key.lower() == "cookie":
|
||||||
|
value = clean_forward_cookie(value)
|
||||||
|
if not value:
|
||||||
|
continue
|
||||||
|
headers[key] = value
|
||||||
|
headers["Host"] = f"127.0.0.1:{port}"
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Length"] = str(len(body))
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=35)
|
||||||
|
conn.request(self.command, target, body=body, headers=headers)
|
||||||
|
resp = conn.getresponse()
|
||||||
|
resp_body = resp.read()
|
||||||
|
resp_headers = []
|
||||||
|
content_type = resp.getheader("Content-Type", "")
|
||||||
|
prefix = f"/access/{urllib.parse.quote(router_id)}"
|
||||||
|
for key, value in resp.getheaders():
|
||||||
|
low = key.lower()
|
||||||
|
if low in {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers", "transfer-encoding", "upgrade", "content-length"}:
|
||||||
|
continue
|
||||||
|
if low == "location":
|
||||||
|
value = rewrite_location(value, prefix, port)
|
||||||
|
if low == "set-cookie":
|
||||||
|
value = rewrite_cookie_path(value, prefix + "/")
|
||||||
|
resp_headers.append((key, value))
|
||||||
|
if "text/html" in content_type:
|
||||||
|
resp_body = rewrite_html(resp_body, prefix)
|
||||||
|
self.send_bytes(resp.status, resp_body, content_type or "application/octet-stream", resp_headers)
|
||||||
|
except Exception as exc:
|
||||||
|
self.send_text(502, f"proxy error: {exc}")
|
||||||
|
|
||||||
|
def redirect(self, location):
|
||||||
|
self.send_response(302)
|
||||||
|
self.send_header("Location", location)
|
||||||
|
self.end_headers()
|
||||||
|
|
||||||
|
|
||||||
|
def rewrite_location(value, prefix, port):
|
||||||
|
if value.startswith("/"):
|
||||||
|
return prefix + value
|
||||||
|
for base in (f"http://127.0.0.1:{port}", f"http://localhost:{port}"):
|
||||||
|
if value.startswith(base + "/"):
|
||||||
|
return prefix + value[len(base):]
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def rewrite_cookie_path(value, path):
|
||||||
|
chunks = value.split(";")
|
||||||
|
changed = []
|
||||||
|
saw_path = False
|
||||||
|
for chunk in chunks:
|
||||||
|
if chunk.strip().lower().startswith("path="):
|
||||||
|
changed.append(" Path=" + path)
|
||||||
|
saw_path = True
|
||||||
|
else:
|
||||||
|
changed.append(chunk)
|
||||||
|
if not saw_path:
|
||||||
|
changed.append(" Path=" + path)
|
||||||
|
return ";".join(changed)
|
||||||
|
|
||||||
|
|
||||||
|
def rewrite_html(body, prefix):
|
||||||
|
text = body.decode("utf-8", errors="ignore")
|
||||||
|
replacements = {
|
||||||
|
'href="/': f'href="{prefix}/',
|
||||||
|
'src="/': f'src="{prefix}/',
|
||||||
|
'action="/': f'action="{prefix}/',
|
||||||
|
"href='/": f"href='{prefix}/",
|
||||||
|
"src='/": f"src='{prefix}/",
|
||||||
|
"action='/": f"action='{prefix}/",
|
||||||
|
}
|
||||||
|
for old, new in replacements.items():
|
||||||
|
text = text.replace(old, new)
|
||||||
|
return text.encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_init(args):
|
||||||
|
with connect(args.db) as conn:
|
||||||
|
init_db(conn)
|
||||||
|
print(f"DB: {args.db}")
|
||||||
|
print(f"ADMIN_TOKEN: {admin_token()}")
|
||||||
|
print(f"AGENT_TOKEN: {agent_token()}")
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_add_router(args):
|
||||||
|
with connect(args.db) as conn:
|
||||||
|
init_db(conn)
|
||||||
|
row = upsert_router(
|
||||||
|
conn,
|
||||||
|
{
|
||||||
|
"id": args.id,
|
||||||
|
"name": args.name,
|
||||||
|
"role": args.role,
|
||||||
|
"entry_port": args.entry_port,
|
||||||
|
"vps_host": args.vps_host,
|
||||||
|
"vless_port": args.vless_port,
|
||||||
|
"vless_uuid": args.vless_uuid,
|
||||||
|
"vless_encryption": args.vless_encryption,
|
||||||
|
"vless_decryption": args.vless_decryption,
|
||||||
|
"vless_flow": args.vless_flow,
|
||||||
|
"reverse_tag": args.reverse_tag,
|
||||||
|
"public_url": args.public_url,
|
||||||
|
"admin_host": args.admin_host,
|
||||||
|
"admin_port": args.admin_port,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
router = row_to_router(row)
|
||||||
|
print(json.dumps(router, ensure_ascii=False, indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_list(args):
|
||||||
|
with connect(args.db) as conn:
|
||||||
|
init_db(conn)
|
||||||
|
rows = [row_to_router(r) for r in list_router_rows(conn)]
|
||||||
|
print(json.dumps(rows, ensure_ascii=False, indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_render_xray(args):
|
||||||
|
with connect(args.db) as conn:
|
||||||
|
init_db(conn)
|
||||||
|
rows = list_router_rows(conn)
|
||||||
|
config = make_server_xray_config(rows, args.listen_host, args.listen_port, args.decryption)
|
||||||
|
text = json.dumps(config, ensure_ascii=False, indent=2) + "\n"
|
||||||
|
if args.out == "-":
|
||||||
|
print(text, end="")
|
||||||
|
else:
|
||||||
|
out = Path(args.out)
|
||||||
|
out.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
out.write_text(text, encoding="utf-8")
|
||||||
|
try:
|
||||||
|
os.chmod(out, 0o600)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
print(f"written: {out}")
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_print_openwrt(args):
|
||||||
|
with connect(args.db) as conn:
|
||||||
|
init_db(conn)
|
||||||
|
row = get_router(conn, args.id)
|
||||||
|
if not row:
|
||||||
|
raise SystemExit(f"router not found: {args.id}")
|
||||||
|
hub_url = args.hub_url or os.environ.get("OWRT_REMOTE_PUBLIC_URL") or f"http://{args.vps_host}:{args.port}"
|
||||||
|
print(make_openwrt_config(row, hub_url), end="")
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_serve(args):
|
||||||
|
app = App(args.db, admin_token(), agent_token(), args.public_url)
|
||||||
|
with app.conn():
|
||||||
|
pass
|
||||||
|
server = ThreadingHTTPServer((args.host, args.port), Handler)
|
||||||
|
server.app = app
|
||||||
|
print(f"{APP_NAME} listening on http://{args.host}:{args.port}")
|
||||||
|
print(f"ADMIN_TOKEN: {app.admin_token}")
|
||||||
|
print(f"AGENT_TOKEN: {app.agent_token}")
|
||||||
|
try:
|
||||||
|
server.serve_forever()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("")
|
||||||
|
|
||||||
|
|
||||||
|
def parser():
|
||||||
|
p = argparse.ArgumentParser(description=APP_NAME)
|
||||||
|
p.add_argument("--db", default=str(DB_PATH), help="SQLite DB path")
|
||||||
|
sub = p.add_subparsers(dest="cmd", required=True)
|
||||||
|
|
||||||
|
init = sub.add_parser("init", help="initialize state and tokens")
|
||||||
|
init.set_defaults(func=cmd_init)
|
||||||
|
|
||||||
|
add = sub.add_parser("add-router", help="add or update router")
|
||||||
|
add.add_argument("--id", required=True)
|
||||||
|
add.add_argument("--name", required=True)
|
||||||
|
add.add_argument("--role", default="node")
|
||||||
|
add.add_argument("--entry-port", type=int, required=True)
|
||||||
|
add.add_argument("--vps-host", required=True)
|
||||||
|
add.add_argument("--vless-port", type=int, default=DEFAULT_VLESS_PORT)
|
||||||
|
add.add_argument("--vless-uuid", default="")
|
||||||
|
add.add_argument("--vless-encryption", default="none")
|
||||||
|
add.add_argument("--vless-decryption", default="none")
|
||||||
|
add.add_argument("--vless-flow", default="")
|
||||||
|
add.add_argument("--reverse-tag", default="reverse-in")
|
||||||
|
add.add_argument("--public-url", default="")
|
||||||
|
add.add_argument("--admin-host", default="127.0.0.1")
|
||||||
|
add.add_argument("--admin-port", type=int, default=80)
|
||||||
|
add.set_defaults(func=cmd_add_router)
|
||||||
|
|
||||||
|
ls = sub.add_parser("list-routers", help="print routers")
|
||||||
|
ls.set_defaults(func=cmd_list)
|
||||||
|
|
||||||
|
rx = sub.add_parser("render-xray", help="render VPS Xray config")
|
||||||
|
rx.add_argument("--listen-host", default="0.0.0.0")
|
||||||
|
rx.add_argument("--listen-port", type=int, default=DEFAULT_VLESS_PORT)
|
||||||
|
rx.add_argument("--decryption", default="none")
|
||||||
|
rx.add_argument("--out", default="-")
|
||||||
|
rx.set_defaults(func=cmd_render_xray)
|
||||||
|
|
||||||
|
ow = sub.add_parser("print-openwrt-config", help="print UCI commands for router")
|
||||||
|
ow.add_argument("--id", required=True)
|
||||||
|
ow.add_argument("--hub-url", default="")
|
||||||
|
ow.add_argument("--vps-host", default="127.0.0.1")
|
||||||
|
ow.add_argument("--port", type=int, default=8088)
|
||||||
|
ow.set_defaults(func=cmd_print_openwrt)
|
||||||
|
|
||||||
|
serve = sub.add_parser("serve", help="run web dashboard")
|
||||||
|
serve.add_argument("--host", default=os.environ.get("OWRT_REMOTE_BIND", "127.0.0.1"))
|
||||||
|
serve.add_argument("--port", type=int, default=int(os.environ.get("OWRT_REMOTE_PORT", "8088")))
|
||||||
|
serve.add_argument("--public-url", default=os.environ.get("OWRT_REMOTE_PUBLIC_URL", ""))
|
||||||
|
serve.set_defaults(func=cmd_serve)
|
||||||
|
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = parser().parse_args()
|
||||||
|
args.func(args)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=OpenWrt Remote Hub
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
Environment=OWRT_REMOTE_BIND=127.0.0.1
|
||||||
|
Environment=OWRT_REMOTE_PORT=8088
|
||||||
|
Environment=OWRT_REMOTE_STATE_DIR=/var/lib/owrt-remote
|
||||||
|
ExecStart=/opt/owrt-remote/owrt-remote-hub.py serve
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=3
|
||||||
|
DynamicUser=no
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
|
||||||
Reference in new issue
Block a user