Remove Lua dependency from LuCI integration

This commit is contained in:
kzolotarev95 committed 2026-06-28 22:35:45 +04:00
1 parent bdd16d3c22
commit d049e272ec
9 files changed
+338 -236

No files matched your search

+2 -1
View File
@@ -12,5 +12,6 @@ files/usr/sbin/owrt-full-backup text eol=lf
files/usr/sbin/owrt-full-backup-upload text eol=lf files/usr/sbin/owrt-full-backup-upload text eol=lf
files/etc/config/fullbackup text eol=lf files/etc/config/fullbackup text eol=lf
files/www/cgi-bin/owrt-full-backup text eol=lf files/www/cgi-bin/owrt-full-backup text eol=lf
files/usr/lib/lua/luci/controller/owrt_full_backup.lua text eol=lf
files/usr/share/luci/menu.d/luci-app-owrt-full-backup.json text eol=lf files/usr/share/luci/menu.d/luci-app-owrt-full-backup.json text eol=lf
files/usr/share/rpcd/acl.d/luci-app-owrt-full-backup.json text eol=lf
files/www/luci-static/resources/view/owrt_full_backup.js text eol=lf
+30 -11
View File
@@ -67,18 +67,20 @@ wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-full-bac
│ ├── sbin │ ├── sbin
│ │ ├── owrt-full-backup │ │ ├── owrt-full-backup
│ │ └── owrt-full-backup-upload │ │ └── owrt-full-backup-upload
│ ├── lib
│ │ └── lua
│ │ └── luci
│ │ └── controller
│ │ └── owrt_full_backup.lua
│ └── share │ └── share
│ └── luci │ ├── luci
│ └── menu.d │ │ └── menu.d
│ │ └── luci-app-owrt-full-backup.json
│ └── rpcd
│ └── acl.d
│ └── luci-app-owrt-full-backup.json │ └── luci-app-owrt-full-backup.json
└── www └── www
└── cgi-bin ├── cgi-bin
└── owrt-full-backup │ └── owrt-full-backup
└── luci-static
└── resources
└── view
└── owrt_full_backup.js
``` ```
## Что ставится на роутер ## Что ставится на роутер
@@ -86,10 +88,11 @@ wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-full-bac
| Путь | Назначение | | Путь | Назначение |
| --- | --- | | --- | --- |
| `/usr/sbin/owrt-full-backup` | CLI-команда для создания, просмотра и восстановления архива | | `/usr/sbin/owrt-full-backup` | CLI-команда для создания, просмотра и восстановления архива |
| `/usr/sbin/owrt-full-backup-upload` | Потоковая загрузка `.tar.gz` из браузера без удержания всего файла в RAM | | `/usr/sbin/owrt-full-backup-upload` | Потоковая загрузка `.tar.gz` из браузера без Lua |
| `/www/cgi-bin/owrt-full-backup` | Веб-панель | | `/www/cgi-bin/owrt-full-backup` | Веб-панель |
| `/usr/lib/lua/luci/controller/owrt_full_backup.lua` | Редирект из LuCI в веб-панель с приватным ключом | | `/www/luci-static/resources/view/owrt_full_backup.js` | LuCI-страница-редирект без Lua runtime |
| `/usr/share/luci/menu.d/luci-app-owrt-full-backup.json` | Пункт меню LuCI для OpenWrt 22-25 | | `/usr/share/luci/menu.d/luci-app-owrt-full-backup.json` | Пункт меню LuCI для OpenWrt 22-25 |
| `/usr/share/rpcd/acl.d/luci-app-owrt-full-backup.json` | Доступ LuCI к приватному веб-ключу |
| `/etc/config/fullbackup` | Настройки по умолчанию | | `/etc/config/fullbackup` | Настройки по умолчанию |
| `/etc/owrt-full-backup/web.key` | Приватный ключ веб-панели | | `/etc/owrt-full-backup/web.key` | Приватный ключ веб-панели |
@@ -159,6 +162,22 @@ rm -rf /tmp/luci-indexcache /tmp/luci-modulecache /tmp/luci-indexcache.* /tmp/lu
Потом обнови страницу LuCI или выйди из LuCI и зайди снова. Прямая приватная ссылка из вывода `install.sh` тоже всегда работает. Потом обнови страницу LuCI или выйди из LuCI и зайди снова. Прямая приватная ссылка из вывода `install.sh` тоже всегда работает.
## Если в LuCI ошибка `No Lua runtime installed`
Поставь свежую версию. Модуль больше не использует Lua-controller для пункта меню LuCI:
```sh
wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-full-backup/main/install.sh?v=$(date +%s)" | sh
```
Установщик удалит старый файл:
```text
/usr/lib/lua/luci/controller/owrt_full_backup.lua
```
И заменит его на LuCI JS-view + rpcd ACL.
## Если ошибка `No space left on device` ## Если ошибка `No space left on device`
Причина почти всегда одна: архив создается в `/tmp`, а там RAM закончилась. Причина почти всегда одна: архив создается в `/tmp`, а там RAM закончилась.
@@ -1,23 +0,0 @@
module("luci.controller.owrt_full_backup", package.seeall)
function index()
entry({"admin", "services", "owrt-full-backup"}, call("action_open"), "OpenWrt Full Backup", 90).dependent = false
end
function action_open()
local http = require "luci.http"
local fs = require "nixio.fs"
local key = fs.readfile("/etc/owrt-full-backup/web.key") or ""
key = key:gsub("%s+", "")
if key == "" then
http.prepare_content("text/html; charset=utf-8")
http.write("<!doctype html><html><head><meta charset=\"utf-8\"><title>OpenWrt Full Backup</title></head><body>")
http.write("<h1>OpenWrt Full Backup</h1>")
http.write("<p>Веб-ключ не найден. Переустанови модуль командой <code>sh install.sh</code>.</p>")
http.write("</body></html>")
return
end
http.redirect("/cgi-bin/owrt-full-backup?key=" .. key)
end
+236 -197
View File
@@ -1,239 +1,278 @@
#!/usr/bin/lua #!/usr/bin/ucode
'use strict';
local default_dir = arg[1] or "/tmp" import * as fs from 'fs';
local content_type = os.getenv("CONTENT_TYPE") or ""
local content_length = tonumber(os.getenv("CONTENT_LENGTH") or "0") or 0
local pending = ""
local target_tmp = nil
local function cleanup() const default_dir = ARGV[0] || '/tmp';
if target_tmp then const content_type = getenv('CONTENT_TYPE') || '';
os.remove(target_tmp) let input_available = +getenv('CONTENT_LENGTH') || 0;
end let input = fs.fdopen(0, 'r');
end let output = fs.fdopen(1, 'w');
let error = fs.fdopen(2, 'w');
let pending = '';
let target_tmp = null;
local function fail(message) function cleanup() {
cleanup() if (target_tmp)
io.stderr:write("ОШИБКА: " .. message .. "\n") fs.unlink(target_tmp);
os.exit(1) }
end
local function ok(message) function fail(message) {
io.stdout:write(message .. "\n") cleanup();
end error.write('ОШИБКА: ' + message + '\n');
exit(1);
}
local function valid_path(path) function ok(message) {
return type(path) == "string" and path:match("^/[A-Za-z0-9%._/%-]+$") ~= nil output.write(message + '\n');
end }
local function shell_quote(value) function valid_path(path) {
return "'" .. tostring(value):gsub("'", "'\\''") .. "'" return type(path) == 'string' && match(path, /^\/[A-Za-z0-9._\/-]+$/);
end }
local function safe_filename(name) function safe_filename(name) {
name = tostring(name or ""):gsub("\\", "/") name = name != null ? '' + name : '';
name = name:match("([^/]+)$") or "" name = replace(name, /\\/g, '/');
name = name:gsub("[^A-Za-z0-9%._%-]", "_") name = fs.basename(name);
return name return replace(name, /[^A-Za-z0-9._-]/g, '_');
end }
local function trim_crlf(line) function trim_crlf(line) {
return tostring(line or ""):gsub("\r\n$", ""):gsub("\n$", "") line = line != null ? '' + line : '';
end line = replace(line, /\r\n$/, '');
return replace(line, /\n$/, '');
}
local function read_from_stdin(size) function append_array(array, value) {
return io.stdin:read(size or 8192) array[length(array)] = value;
end }
local function read_line() function concat_array(array, separator) {
while true do let result = '';
local pos = pending:find("\n", 1, true)
if pos then
local line = pending:sub(1, pos)
pending = pending:sub(pos + 1)
return line
end
local chunk = read_from_stdin(1024) for (let i = 0; i < length(array); i++) {
if not chunk or #chunk == 0 then if (i > 0)
if #pending > 0 then result += separator;
local line = pending
pending = ""
return line
end
return nil
end
pending = pending .. chunk result += array[i];
end }
end
local boundary = content_type:match('boundary="?([^";]+)"?') return result;
if not boundary or boundary == "" then }
fail("multipart boundary не найден")
end
if content_length <= 0 then function read_from_stdin(size) {
fail("пустой upload") if (input_available <= 0)
end return null;
local marker = "--" .. boundary size = size != null ? size : 8192;
local delimiter = "\r\n" .. marker let chunk = input.read(min(input_available, size, 8192));
local first_line = trim_crlf(read_line()) if (chunk == null) {
if first_line ~= marker then input_available = 0;
fail("multipart boundary не найден в теле запроса") return null;
end }
local function read_headers() input_available -= length(chunk);
local headers = {} return chunk;
}
while true do function read_line() {
local line = read_line() while (true) {
if not line then let pos = index(pending, '\n');
fail("не удалось прочитать заголовки upload")
end
line = trim_crlf(line) if (pos != null && pos >= 0) {
if line == "" then let line = substr(pending, 0, pos + 1);
break pending = substr(pending, pos + 1);
end return line;
}
headers[#headers + 1] = line let chunk = read_from_stdin(1024);
end
return table.concat(headers, "\n") if (chunk == null) {
end if (length(pending) > 0) {
let line = pending;
pending = '';
return line;
}
local function read_part(out, max_text) return null;
local keep = #delimiter + 4 }
local buffer = ""
local text = {}
local text_size = 0
local part_size = 0
local function consume(data) pending += chunk;
if not data or #data == 0 then }
return }
end
part_size = part_size + #data let boundary_match = match(content_type, /boundary="?([^";]+)"?/);
if out then let boundary = boundary_match ? boundary_match[1] : null;
local wrote, err = out:write(data)
if not wrote then
fail("не удалось записать upload: " .. tostring(err))
end
return
end
text_size = text_size + #data if (!boundary)
if text_size > (max_text or 4096) then fail('multipart boundary не найден');
fail("поле формы слишком большое")
end
text[#text + 1] = data
end
while true do if (input_available <= 0)
local chunk fail('пустой upload');
if #pending > 0 then
chunk = pending
pending = ""
else
chunk = read_from_stdin(8192)
end
if not chunk then const marker = '--' + boundary;
fail("не найден конец multipart upload") const delimiter = '\r\n' + marker;
end
buffer = buffer .. chunk let first_line = trim_crlf(read_line());
local start_pos, end_pos = buffer:find(delimiter, 1, true) if (first_line != marker)
if start_pos then fail('multipart boundary не найден в теле запроса');
consume(buffer:sub(1, start_pos - 1))
local after = end_pos + 1 function read_headers() {
local final = false let headers = [];
if buffer:sub(after, after + 1) == "--" then
final = true
after = after + 2
end
if buffer:sub(after, after + 1) == "\r\n" then
after = after + 2
end
pending = buffer:sub(after) while (true) {
return final, table.concat(text), part_size let line = read_line();
end
if #buffer > keep then if (line == null)
consume(buffer:sub(1, #buffer - keep)) fail('не удалось прочитать заголовки upload');
buffer = buffer:sub(#buffer - keep + 1)
end
end
end
local upload_dir = default_dir line = trim_crlf(line);
local saved_path = nil
local saved_size = 0
local final = false
while not final do if (line == '')
local headers = read_headers() break;
local disposition = headers:match("[Cc]ontent%-[Dd]isposition:%s*([^\n]+)")
local name = disposition and disposition:match('name="([^"]+)"')
local filename = disposition and disposition:match('filename="([^"]*)"')
if name == "upload_dir" and not filename then append_array(headers, line);
local value }
final, value = read_part(nil, 4096)
upload_dir = tostring(value or ""):gsub("[%z\r\n]", "")
elseif name == "archive" and filename and filename ~= "" then
if not valid_path(upload_dir) then
fail("неверная папка для загрузки: " .. tostring(upload_dir))
end
local file_name = safe_filename(filename) return concat_array(headers, '\n');
if file_name == "" then }
fail("файл архива не выбран")
end
if not file_name:match("%.tar%.gz$") then
fail("можно загружать только архивы .tar.gz")
end
os.execute("mkdir -p " .. shell_quote(upload_dir)) function read_part(out, max_text) {
let keep = length(delimiter) + 4;
let buffer = '';
let text = [];
let text_size = 0;
let part_size = 0;
local target = upload_dir:gsub("/+$", "") .. "/" .. file_name function consume(data) {
target_tmp = target .. ".uploading." .. tostring(os.time()) .. "." .. tostring(content_length) if (data == null || length(data) == 0)
local out, err = io.open(target_tmp, "wb") return;
if not out then
fail("не удалось открыть файл для записи: " .. target .. ": " .. tostring(err))
end
local _ part_size += length(data);
final, _, saved_size = read_part(out, 0)
local closed, close_err = out:close()
if not closed then
fail("не удалось закрыть файл: " .. target .. ": " .. tostring(close_err))
end
if saved_size <= 0 then
fail("файл пустой")
end
local renamed, rename_err = os.rename(target_tmp, target) if (out) {
if not renamed then out.write(data);
fail("не удалось сохранить файл: " .. target .. ": " .. tostring(rename_err)) return;
end }
target_tmp = nil text_size += length(data);
saved_path = target
else
final = read_part(nil, 1024)
end
end
if not saved_path then max_text = max_text != null ? max_text : 4096;
fail("файл архива не выбран")
end
ok("Архив загружен: " .. saved_path) if (text_size > max_text)
ok("Размер: " .. tostring(saved_size) .. " байт") 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 + ' байт');
@@ -3,11 +3,13 @@
"title": "OpenWrt Full Backup", "title": "OpenWrt Full Backup",
"order": 90, "order": 90,
"action": { "action": {
"type": "call", "type": "view",
"module": "luci.controller.owrt_full_backup", "path": "owrt_full_backup"
"function": "action_open"
}, },
"depends": { "depends": {
"acl": [
"luci-app-owrt-full-backup"
],
"fs": { "fs": {
"/www/cgi-bin/owrt-full-backup": "executable" "/www/cgi-bin/owrt-full-backup": "executable"
} }
@@ -0,0 +1,17 @@
{
"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,43 @@
'use strict';
'require view';
'require fs';
'require ui';
return view.extend({
load: function() {
return fs.read('/etc/owrt-full-backup/web.key').catch(function() {
return '';
});
},
render: function(key) {
key = (key || '').trim();
if (!key) {
return E('div', { 'class': 'cbi-map' }, [
E('h2', {}, _('OpenWrt Full Backup')),
E('div', { 'class': 'alert-message warning' }, [
_('Веб-ключ не найден. Переустанови модуль командой install.sh.')
])
]);
}
var url = '/cgi-bin/owrt-full-backup?key=' + encodeURIComponent(key);
window.setTimeout(function() {
window.location.replace(url);
}, 100);
return E('div', { 'class': 'cbi-map' }, [
E('h2', {}, _('OpenWrt Full Backup')),
E('p', {}, _('Открываю веб-панель полного бэкапа...')),
E('p', {}, [
E('a', { 'class': 'btn cbi-button cbi-button-apply', 'href': url }, _('Открыть панель'))
])
]);
},
handleSaveApply: null,
handleSave: null,
handleReset: null
});
+3 -1
View File
@@ -106,8 +106,10 @@ install_file "usr/sbin/owrt-full-backup-upload" 0755
ln -sf owrt-full-backup "$(target_path usr/sbin/owrt-backup)" 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-full-backup" 0755
install_file "usr/lib/lua/luci/controller/owrt_full_backup.lua" 0644
install_file "usr/share/luci/menu.d/luci-app-owrt-full-backup.json" 0644 install_file "usr/share/luci/menu.d/luci-app-owrt-full-backup.json" 0644
install_file "usr/share/rpcd/acl.d/luci-app-owrt-full-backup.json" 0644
install_file "www/luci-static/resources/view/owrt_full_backup.js" 0644
rm -f "$(target_path usr/lib/lua/luci/controller/owrt_full_backup.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
+2
View File
@@ -19,6 +19,8 @@ rmf usr/sbin/owrt-backup
rmf www/cgi-bin/owrt-full-backup rmf www/cgi-bin/owrt-full-backup
rmf usr/lib/lua/luci/controller/owrt_full_backup.lua rmf usr/lib/lua/luci/controller/owrt_full_backup.lua
rmf usr/share/luci/menu.d/luci-app-owrt-full-backup.json rmf usr/share/luci/menu.d/luci-app-owrt-full-backup.json
rmf usr/share/rpcd/acl.d/luci-app-owrt-full-backup.json
rmf www/luci-static/resources/view/owrt_full_backup.js
if [ "$PURGE" = "1" ]; then if [ "$PURGE" = "1" ]; then
rmf etc/config/fullbackup rmf etc/config/fullbackup