mirror of
https://github.com/dikeckaan/mu300-linux.git
synced 2026-12-05 08:02:40 +00:00
feat: add OTA diff tools and shared installation fixes
Integrate the diff studio and on-device OTA updater, native installer packaging and tracked local release workflow. Update boot switching, SIM readiness notifications, dashboard power controls and manual cell locking with regression coverage and usage guides.
This commit is contained in:
1 parent
500e5ea43c
commit
b8d4f222a8
67 files changed
+3780
-86
No files matched your search
@@ -3,6 +3,12 @@ name: Apple Silicon installer
|
||||
on:
|
||||
workflow_call:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
runner:
|
||||
description: Native Apple Silicon runner
|
||||
type: choice
|
||||
options: [macos-15, macos-14]
|
||||
default: macos-15
|
||||
push:
|
||||
branches: ['build/macos-*']
|
||||
|
||||
@@ -11,7 +17,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
macos:
|
||||
runs-on: macos-15
|
||||
runs-on: ${{ inputs.runner || 'macos-15' }}
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
MACOSX_DEPLOYMENT_TARGET: '11.0'
|
||||
@@ -30,7 +36,7 @@ jobs:
|
||||
run: |
|
||||
test "$(uname -m)" = arm64
|
||||
rustup toolchain install 1.90.0 --profile minimal
|
||||
python -m pip install pyinstaller paramiko lz4
|
||||
python -m pip install pyinstaller paramiko lz4 -r installer/ota-requirements.txt
|
||||
- name: Installer tests (no device writes)
|
||||
run: python -m unittest discover -s installer/tests -v
|
||||
- name: Build native portable installer
|
||||
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
- name: Rust build toolchain
|
||||
run: rustup toolchain install 1.90.0 --profile minimal
|
||||
- name: Python build dependencies
|
||||
run: python -m pip install pyinstaller paramiko lz4
|
||||
run: python -m pip install pyinstaller paramiko lz4 -r installer/ota-requirements.txt
|
||||
- name: State and recovery tests (no device writes)
|
||||
run: python -m unittest discover -s installer/tests -v
|
||||
- name: Build portable release
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# Hardware and modem fixes
|
||||
|
||||
- Use each model's stock Android firmware behavior as the reference for power,
|
||||
charging, battery accounting, radio initialization and reconnection.
|
||||
- Prefer the actual device's driver/RIL binary and device tree over a merely
|
||||
similar vendor source tree. Record firmware versions and the evidence used.
|
||||
- Separate confirmed defects, hypotheses and untested hardware behavior in
|
||||
reports. AOSP explains the framework design; its default timers are not proof
|
||||
of the model's carrier or vendor configuration.
|
||||
- Do not hide a symptom with arbitrary percentage caps, forced recalibration,
|
||||
radio resets, disabled sleep or reduced functionality. Preserve existing AT
|
||||
ownership, command ordering, boot replay and explicit user choices.
|
||||
- Apply shared fixes to shared build/update paths. Keep charger-chip and board
|
||||
differences in the model profiles, and do not call an offline test a successful
|
||||
hardware validation.
|
||||
|
||||
# Local builds and release packaging
|
||||
|
||||
- Read `docs/LOCAL-BUILD.zh-CN.md` before a local build or release. Use the
|
||||
version-controlled `tools/build-release.py` entry point for task logging,
|
||||
workspace locking and release assembly. Never generate another release worker
|
||||
in `work/`, or execute/modify an old worker to assemble a new release.
|
||||
- Reuse the existing `/home/kano/openwrt-build` workspace on this machine.
|
||||
Register input paths in `tools/build-layout.json` or an explicitly selected
|
||||
local config. Do not migrate builds to C:, create timestamped source/object
|
||||
trees, clone another kernel, export another Docker volume, or duplicate a
|
||||
complete rootfs as a shortcut. Existing model-specific prepared source/object
|
||||
caches are retained; never share a patched source tree across models blindly.
|
||||
- Keep final local releases under `release/`, task logs/status under
|
||||
`out/build-logs/` and `out/build-state/`, and package staging under the fixed
|
||||
workspace `package-work/mu300-release/<series>/`. Investigations belong under
|
||||
`work/` or `dumps/`; they are not production build inputs unless registered.
|
||||
- Separate native Windows/macOS installer builds, kernel/APK compilation, and
|
||||
package assembly. Check source fingerprints and matching Image/modules before
|
||||
reuse. Do not rebuild unchanged inputs merely because packaging is requested,
|
||||
or bypass a stale-input rejection to avoid compiling a changed dependency.
|
||||
- Use only the model's tracked build/prepare scripts. Do not use `git reset`,
|
||||
`git clean`, archive extraction over a prepared tree, or an arbitrary cache
|
||||
substitution to switch profiles. Stop and describe missing/invalid registered
|
||||
inputs instead of silently choosing another tree or an old package.
|
||||
- Successful assembly removes only its owned staging, after archive verification.
|
||||
Failed staging is retained for diagnosis and requires `clean-staging` before
|
||||
reuse. Never automatically delete source/object/download caches, device dumps,
|
||||
installation backups, or previous releases. Do not run `docker system prune`
|
||||
or remove volumes as routine build cleanup.
|
||||
@@ -1,5 +1,7 @@
|
||||
# Linux on the ZTE F50 / MU300 and U30 Air
|
||||
|
||||
Local builds and packaging: [workspace and release workflow](docs/LOCAL-BUILD.zh-CN.md).
|
||||
|
||||
Maintainer notes: [stock behavior and new-device adaptation checklist](docs/NEW-DEVICE-STOCK-ADAPTATION.zh-CN.md),
|
||||
[U30 Air charge/power/recovery evidence](docs/U30AIR-STOCK-CHARGE-20261016.zh-CN.md).
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//<script>
|
||||
/*
|
||||
* OpenWrt system switch v4 — Minikano
|
||||
* Android web-panel plugin; E5/T551M/VIPME M8 and MU300/F50/V50/U30Air.
|
||||
* OpenWrt system switch v5 — Minikano
|
||||
* Android web-panel plugin; all supported E5-family and MU300-family models.
|
||||
* Select the installed OpenWrt for the next boot, preserving default policy.
|
||||
* Write only misc[2048:2080]. No root mount, boot flash or boot-chain sync.
|
||||
* Shared with mu300-linux/android/magisk/webui-plugins/mu300-system-switch.js.
|
||||
@@ -85,8 +85,7 @@
|
||||
const probe = async () => {
|
||||
const result = await run('set -e; [ "$(id -u)" = 0 ]; [ -n "$(getprop ro.build.version.release)" ]; ' +
|
||||
'echo SLOT=$(getprop ro.boot.slot_suffix); echo MODEL=$(getprop ro.product.model); ' +
|
||||
'echo DEVICE=$(getprop ro.product.device); echo PLATFORM=$(getprop ro.board.platform); ' +
|
||||
'echo UNLOCKED=$(getprop ro.boot.verifiedbootstate)');
|
||||
'echo DEVICE=$(getprop ro.product.device); echo PLATFORM=$(getprop ro.board.platform)');
|
||||
if (!result.ok) throw new Error('请在 Android 中打开插件,并授予网页管理面板 root 权限');
|
||||
const values = {};
|
||||
for (const line of result.text.split(/\r?\n/)) {
|
||||
@@ -96,13 +95,12 @@
|
||||
if (!/^_[ab]$/.test(values.SLOT || '')) throw new Error('无法确定当前 Android 槽位,已取消;不会使用 misc 猜测');
|
||||
const slot = values.SLOT.slice(1), names = [values.MODEL || '', values.DEVICE || ''].map(name => name.toUpperCase());
|
||||
let family;
|
||||
if (['E5', 'T551M', 'VIPME M8'].includes(values.MODEL)) family = 'e5';
|
||||
if (['E5', 'T551M', 'VIPME M8', 'T512N', 'ZTE 7546N', 'ANGELCARE K1'].some(model => names.includes(model))) family = 'e5';
|
||||
else if (names.includes('V50') || names.includes('MU3351')) {
|
||||
if (!names.includes('V50') || !names.includes('MU3351') || values.PLATFORM !== 'ums9620') throw new Error('V50 的型号或平台信息不匹配');
|
||||
family = 'mu300';
|
||||
} else if (/U30.?AIR|MU300|F50/i.test(names.join('\n'))) family = 'mu300';
|
||||
else throw new Error('此机型不在两个项目支持范围内,未切换');
|
||||
if (family === 'e5' && (slot !== 'a' || values.UNLOCKED !== 'orange')) throw new Error('E5 系列要求已解锁且 Android 运行在 A 槽');
|
||||
const live = await readHex(MISC, 2048, 32);
|
||||
control(live, slot);
|
||||
const other = slot === 'a' ? 'b' : 'a', target = '/dev/block/by-name/boot_' + other;
|
||||
|
||||
@@ -26,7 +26,7 @@ import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
PAGE = 4096
|
||||
@@ -70,6 +70,9 @@ def lz4_legacy(data):
|
||||
|
||||
|
||||
def cpio_archive(dirs, files):
|
||||
dirs = set(dirs)
|
||||
for name in list(files) + list(dirs):
|
||||
dirs.update(str(p) for p in PurePosixPath(name).parents if str(p) != '.')
|
||||
cpio = bytearray()
|
||||
ino = 1
|
||||
for d in sorted(dirs, key=lambda x: (x.count('/'), x)):
|
||||
|
||||
@@ -156,7 +156,9 @@ detect_linux_slot() {
|
||||
linux_slot=$(tr '\000' ' ' < "$src" | sed -n 's/.*androidboot.slot_suffix=_\([ab]\).*/\1/p')
|
||||
case $linux_slot in a|b) return ;; esac
|
||||
done
|
||||
case $linux_slot in a|b) ;; *) linux_slot=b; log 'stage=slot-unknown (legacy b fallback)' ;; esac
|
||||
linux_slot=
|
||||
log 'stage=slot-unknown boot-partition-writes-disabled'
|
||||
return 1
|
||||
}
|
||||
find_partitions() {
|
||||
for n in $(seq 1 20); do
|
||||
@@ -168,7 +170,7 @@ find_partitions() {
|
||||
mdev -s
|
||||
done
|
||||
[ -b "$misc" ] || misc=
|
||||
detect_linux_slot
|
||||
detect_linux_slot || { bootdev=; return 1; }
|
||||
for u in /sys/class/block/mmcblk*p*/uevent; do
|
||||
grep -qx "PARTNAME=boot_$linux_slot" "$u" 2>/dev/null && bootdev=/dev/$(basename "$(dirname "$u")")
|
||||
done
|
||||
@@ -187,6 +189,7 @@ write_misc_bc() { # write_misc_bc FILE STAGE
|
||||
if cmp -s /run/bc-check.bin "$1"; then log "stage=$2 dev=$misc"; else log "stage=$2-MISMATCH dev=$misc"; return 1; fi
|
||||
}
|
||||
restore_android() {
|
||||
case "$linux_slot" in a|b) ;; *) log 'stage=slot-unknown misc-unchanged'; return 1 ;; esac
|
||||
if [ "$linux_slot" = a ]; then
|
||||
write_misc_bc /etc/misc-bc-slot-b.bin misc-restored
|
||||
else
|
||||
@@ -347,6 +350,12 @@ EOF
|
||||
# server starts right after switch_root), the more reliably the host gets an address.
|
||||
load_vendor_modules
|
||||
find_partitions
|
||||
case "$linux_slot" in
|
||||
a|b) ;;
|
||||
*) setup_usb_gadget
|
||||
log 'stage=slot-unknown rescue-only (no root or radio handoff)'
|
||||
while :; do sleep 1; done ;;
|
||||
esac
|
||||
# Read the optional LuCI package's USB policy before configfs enumeration.
|
||||
# Use the already-mounted TF root: a separate ro,noload peek can miss a new
|
||||
# setting still in the ext4 journal, even after the block device appears.
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
# 本地构建与打包规范
|
||||
|
||||
本仓库维护分支为 `clean-tf-7.2`。不变更上游、分支及提交历史。
|
||||
本地任务统一走受版本控制的 `tools/build-release.py`;不得复制/执行旧的
|
||||
`work/` 日期 worker,或通过字符串替换拼接另一份发布流程。
|
||||
|
||||
## 固定目录
|
||||
|
||||
| 内容 | 位置 |
|
||||
| --- | --- |
|
||||
| Linux 构建工作区 | 本机既有 `/home/kano/openwrt-build`,不迁移 C 盘 |
|
||||
| 内核/SDK 编译缓存 | 原有 WSL 目录或 Docker volume,不新建重复源码树 |
|
||||
| 输入登记 | `tools/build-layout.json`,另一台机器用 `--config` 显式指定 |
|
||||
| 打包 staging | 工作区 `package-work/mu300-release/<series>/assembly` |
|
||||
| 正式发布 | 仓库 `release/<task>/` |
|
||||
| 任务日志/状态 | `out/build-logs/<task>/`、`out/build-state/latest.json` |
|
||||
| 临时文件 | 工作区 `tmp/mu300-release-*`,单步结束自动删除 |
|
||||
| Windows/macOS 安装器 | `installer/artifacts/windows-x64`、`installer/artifacts/macos-arm64` |
|
||||
|
||||
登记表显式引用当前已经存在的输入,包括相邻 `mu300-linux/work` 的固件/工具,
|
||||
以及本仓库旧安装包中的维护工具。它们尚未迁移,所以不能当成垃圾删除。
|
||||
路径记录不意味着另复制一份;缺失时报错,不会随机寻找旧包替代。
|
||||
|
||||
## 使用方式
|
||||
|
||||
在 WSL 内进入当前仓库,使用当前 Linux 用户的 `~/openwrt-build`;sudo 时必须
|
||||
明确 `--workspace /home/kano/openwrt-build`。当前支持两条内核发行线:
|
||||
`mu300-7.2`、`mu300-6.18`;共享固件继续在运行时区分 MU300/F50/V50/U30 Air,
|
||||
不为每台机器重复构建同一份镜像。
|
||||
|
||||
```sh
|
||||
python3 tools/build-release.py plan --profiles all
|
||||
python3 tools/build-release.py check --profiles all
|
||||
python3 tools/build-release.py package --profiles all
|
||||
python3 tools/build-release.py status
|
||||
```
|
||||
|
||||
`plan/check` 只读,验证固件/工具入口、内核与完整模块配套、Wi-Fi/block-mount
|
||||
缓存,以及 Windows/macOS 安装器源码指纹。输入过期即停止,不启动编译或复制 root。
|
||||
内核产物配套校验不能证明当前内核源码已经被编译;仍需核对变更范围。
|
||||
|
||||
编译有变更的依赖或内核时,使用固定日志与互斥入口,显式设置原构建器参数:
|
||||
|
||||
```sh
|
||||
python3 tools/build-release.py run --label wifi -- sh openwrt/build-hostapd.sh
|
||||
python3 tools/build-release.py run --label block -- sh openwrt/build-block-mount.sh
|
||||
# 内核:run --label mu300-kernel -- <现有构建命令>
|
||||
```
|
||||
|
||||
内核继续复用现有 Docker volume 和 `upstream/build.sh` / `build-modules.sh`,
|
||||
禁止临时克隆或导出另一份内核树。Windows 和 Apple Silicon 安装器在对应原生
|
||||
平台运行 `python installer/build.py`,各编译一次供两条内核发行线共用。
|
||||
|
||||
## 组装与清理边界
|
||||
|
||||
组装复用原 `tools/build-openwrt-tf-magisk.sh`,不改 Magisk/桌面安装流程。
|
||||
新增的 `MU300_PACKAGE_WORK` 和 `MU300_ROOTFS_OUT_DIR` 仅控制中间文件位置;
|
||||
未设置时保留原脚本默认行为。现在 rootfs、boot、ramdisk、release JSON、
|
||||
解压 staging 均能放入固定任务目录,成功后一起清理,不散落根目录。
|
||||
|
||||
原 rootfs 构建仍需安装软件包、编译少量辅助程序;不重新编译内核或 GUI。
|
||||
Wi-Fi/block-mount 先验证缓存,现有构建器命中缓存即复用。
|
||||
完成 ZIP CRC、原 manifest 文件校验、单份 boot/rootfs 校验及复制 SHA-256
|
||||
核对后,清理本机型 staging。全部发行线通过且源码未变,才把隐藏的
|
||||
`.building-<task>` 目录改名为正式目录,写入 `BUILD-RUN.json`。
|
||||
|
||||
失败保留现场,状态为 failed;隐藏目录不是发布包。确认不再需要现场后:
|
||||
|
||||
```sh
|
||||
python3 tools/build-release.py clean-staging --profiles mu300-7.2
|
||||
```
|
||||
|
||||
只删除固定目录内带匹配所有权标记的 staging,拒绝符号链接、越界和仍有挂载
|
||||
的目录。源码、对象、下载缓存、设备备份、当前安装器和旧发布包不自动清理。
|
||||
历史遗留缓存应单独盘点处理,禁止例行 `docker system prune` 或删除 volume。
|
||||
|
||||
E5 与 MU300 工具共用工作区 `locks/openwrt-release.lock`,防止同时读写共享
|
||||
SDK/源码缓存;staging 与日志按仓库分开。旧脚本直接执行无法受此锁保护,
|
||||
所以本地构建必须经过固定入口。CI 的独立 runner 不受本规范改变。
|
||||
@@ -0,0 +1,40 @@
|
||||
# 差异包生成器与统一更新入口
|
||||
|
||||
## 已确认的产品范围
|
||||
|
||||
- 独立 Tauri 工具,复用现有安装器的界面组件和设计。
|
||||
- 输入旧版包、新版包,分析后展示差异、兼容范围与体积,再导出差异包。
|
||||
- 同一份差异包支持 OpenWrt 网页导入,以及解压后通过内置电脑更新器更新。
|
||||
- OTA 插件完成后默认内置到 E5、T551M、M8、T512N、远航 41S、K1,以及
|
||||
MU300/F50/V50/U30 Air 对应发行包,用户无需另装。
|
||||
- 两仓库使用一致的差异包协议,各自保留机型和内核兼容校验。
|
||||
- 对系统文件生成差异,不直接比较压缩包字节;只更新差异覆盖范围,保留
|
||||
用户额外插件、配置、流量记录及其他数据。冲突必须明确显示。
|
||||
- 内核变更时携带完整 boot 与配套模块;不重复放置多份 boot/rootfs。
|
||||
- 旧版匹配、文件哈希、空间检查、持久化事务与失败恢复在实际实现时一起完成。
|
||||
|
||||
## 本轮已经落地:屏蔽 OpenWrt 原生刷固件
|
||||
|
||||
两仓库保留系统配置备份、还原及重启,移除 LuCI 原生固件刷写区和对应 ACL。
|
||||
原“Backup / Flash Firmware”菜单改为“Backup”;不移除整个配置备份页面。
|
||||
自动升级组件原有的移除规则保留,不影响用户通过 APK 安装或管理普通插件。
|
||||
|
||||
公共 ucode 策略应用到根文件系统构建、E5 六机型公共组包、LuCI 包安装和首次
|
||||
启动路径。策略是一次性应用,不增加后台轮询,不改基带/AT/回放/USB 启动顺序。
|
||||
匹配基于当前 OpenWrt 25.12 已安装的 LuCI 视图结构,未知新结构明确失败,
|
||||
不盲目删除备份控件。标准 LuCI 的 Backup 文本继续使用原有翻译。
|
||||
|
||||
两仓库 sysupgrade 防护只允许明确的配置备份、还原和列表操作;拒绝固件参数及
|
||||
混合操作。特别补上原先不能经 LuCI 执行的配置还原,不把原生刷写能力重新打开。
|
||||
|
||||
## 验证范围与尚未完成
|
||||
|
||||
- 防护脚本的合法备份/还原和固件拒绝、菜单/权限保留、重复应用及未知视图不写入
|
||||
已通过离线测试;使用已有 OpenWrt 容器运行实际 ucode,未构建新镜像。
|
||||
- 已实现首版 Tauri 分析/导出与电脑应用界面、E5 ext4 / MU300 tar 读取、统一
|
||||
文件差异协议、设备事务引擎、网页导入/回退,以及公共构建默认内置。
|
||||
- 当前只允许相同内核和基础依赖的文件热补丁;boot/内核/模块变化仍阻止导出,
|
||||
后续需单独完成动态槽位绑定及离线内核事务。详细限制见
|
||||
[使用与实现说明](OTA-DIFF-USAGE.zh-CN.md)。
|
||||
- 离线测试覆盖校验、冲突、保留用户数据、回退、模拟进程中断恢复和真实小 ext4
|
||||
解析;没有实机 OTA 写入或真实断电验证,不能把它们称为实机通过。
|
||||
@@ -0,0 +1,129 @@
|
||||
# 文件差异更新:开发首版
|
||||
|
||||
这套功能在 E5 与 MU300 仓库使用相同协议、生成器、网页插件和设备端引擎。
|
||||
当前交付范围是**相同内核、相同基础软件依赖的系统文件热补丁**。
|
||||
首次迁移到带 OTA 插件的发行版,需要使用完整安装器更新一次;旧系统没有可信
|
||||
的内置引擎时,电脑更新器会明确停止,不自动上传脚本并以 root 执行。
|
||||
|
||||
## 用户使用
|
||||
|
||||
1. 打开 `OpenWrt-Diff-Studio.exe`(Apple Silicon 原生构建对应 `.app`),选择
|
||||
旧版与新版完整发行 ZIP,也可通过 Python 命令行选择已解压目录。
|
||||
2. 点击“分析差异”,检查机型、版本、文件增删与阻止原因。工具按文件内容和
|
||||
权限/所有者/扩展属性比较;不比较 ZIP 二进制,不修改输入包。
|
||||
3. 导出 `.zip` 会生成可完整解压的电脑更新包,里面包含**一份** `update.ota`、
|
||||
原生更新器和 Python 入口。原生运行库复用生成器自身已校验的构建,不重复
|
||||
携带完整 rootfs、boot。选择 `.ota` 则只生成网页可导入的载荷。
|
||||
4. 网页:系统 → 系统补丁,导入 `update.ota`,核对检查结果后应用。
|
||||
5. 电脑:完整解压差异 ZIP,运行 `OpenWrt-Updater.exe` / `.app`,填写管理地址
|
||||
与 SSH 密码,先“连接并检查”,再确认应用。程序不依赖 SFTP,也不改变电脑
|
||||
路由。初次 SSH 连接的信任方式与现有安装器相同,本次检查到提交之间会核对
|
||||
设备公钥,避免把确认结果用于另一台设备。
|
||||
6. 完成后重启设备,使所有服务加载新文件。网页可撤销最近一次补丁,恢复前会
|
||||
再次检查目标文件,用户随后手动修改过的文件不会被强行覆盖。
|
||||
|
||||
**只导入可信发布者提供的文件。SHA-256 用于完整性和版本匹配,不是发布者签名。**
|
||||
本版没有公网自动下载、自动更新或发布者签名/密钥分发功能。
|
||||
|
||||
## 保留与冲突策略
|
||||
|
||||
- `/etc/config`、账号密钥、用户数据、流量记录、NV、固件、包管理数据库不会
|
||||
作为差异覆盖目标;用户额外安装的插件也不会被清理。
|
||||
- LuCI 的 `www/` 页面、样式和脚本属于可更新系统文件;首次启动默认配置脚本
|
||||
不会借热补丁重新执行。核心启动运行库和更新器自身的变化要求完整安装器。
|
||||
- OTA 自身的引擎和恢复入口不通过本版 OTA 自我替换。
|
||||
- APK 基础软件集合、ABI/依赖变化要求完整安装器;自有看板的同依赖版本变更
|
||||
可以作为文件补丁,APK 数据库保留原包版本,实际生效版本另记 OTA 台账。
|
||||
之后用 APK 重装相应包可能覆盖热补丁,后续 OTA 会将这种情况报告为冲突。
|
||||
- 设备版本、机型族、内核、受影响文件的原始哈希、权限、所有者和扩展属性全部
|
||||
匹配才允许写入。不会提供“忽略冲突强刷”按钮。
|
||||
- 普通目录删除会保留空目录,避免删除用户插件产生的内容;文件类型变化拒绝
|
||||
导出。软链接父路径、路径穿越、重复归档条目与包内脚本均会拒绝。
|
||||
- 更改仅应用于本版清单,不承诺整机与新版完整镜像逐字节相同;被保留的用户
|
||||
配置不会因版本号改变而恢复出厂值。
|
||||
|
||||
## 事务与资源
|
||||
|
||||
- 写入前将原文件及不可变计划写到 `/etc/unisoc-ota/backup-<编号>/`,刷盘后才
|
||||
提交精简的事务进度。完整文件清单只写一次,避免随文件数产生平方级写放大。
|
||||
- 每个文件使用同目录临时文件、校验、重命名;持久化进度先于相应文件修改。
|
||||
- 网页与电脑共用已安装引擎。设备端工作进程脱离网页/SSH 会话,断开电脑不会
|
||||
主动终止写入;异常会尝试回退。重启时的早期服务仅在发现未完成事务时执行
|
||||
恢复,没有常驻守护、定时器或空闲轮询。
|
||||
- 同时持有本功能事务锁和原有整包升级锁,已排队的 E5 整包升级会阻止 OTA。
|
||||
- 保留最近一次手动回退副本;新事务成功刷盘之后才清理本工具的更早副本。
|
||||
- E5 ext4 由桌面进程只读解析,不挂载、不依赖用户机器的 WSL;临时展开镜像
|
||||
放在输入包所在目录,一次只保留一个镜像,退出立即清理。MU300 tar 直接流式
|
||||
读取。WSL 仅用于开发测试创建小 ext4 样本,不是用户运行依赖。
|
||||
- E5 已有 Python;MU300 新包会增加 Python 运行依赖以共用引擎。
|
||||
|
||||
## 尚未放行
|
||||
|
||||
**包含内核、模块或 initramfs/boot 变化的差异包暂不导出。** 当前不会刷 boot、
|
||||
不修改 misc、槽位、分区表或系统容量。后续需要实现完整 boot 与模块配套的离线
|
||||
事务,并验证实际 A/B 绑定及断电恢复,不能把简单覆盖 boot 宣称为可靠内核 OTA。
|
||||
这种更新继续使用完整安装器。
|
||||
|
||||
没有实机 OTA 写入验证、实际断电验证或 macOS 原生运行验证;离线故障注入不能
|
||||
替代这些验证。原生固件更新入口已屏蔽,但配置备份/还原仍保留。
|
||||
|
||||
## 开发与原生构建
|
||||
|
||||
```powershell
|
||||
py -3.12 -m pip install -r installer/ota-requirements.txt
|
||||
py -3.12 -m unittest discover -s installer/tests -p "test_ota*.py"
|
||||
# Linux 中执行同一测试,可覆盖文件系统写入、进程退出和回退测试。
|
||||
|
||||
# 复用现有 installer/ui/node_modules 和 src-tauri/target,不复制第二份编译树。
|
||||
cd installer/ui
|
||||
npm run tauri -- build --no-bundle
|
||||
cd ../..
|
||||
py -3.12 installer/build.py --skip-ui
|
||||
py -3.12 installer/build-ota.py --output out/tools/OpenWrt-Diff-Studio
|
||||
```
|
||||
|
||||
Apple Silicon 同样使用 `installer/build.py` 和 `installer/build-ota.py` 的原生路径;
|
||||
不能在 Windows 上伪造 Mac 构建。生成器自身会携带对应平台的更新器。
|
||||
|
||||
命令行:
|
||||
|
||||
```sh
|
||||
python installer/ota-tool.py analyze OLD.zip NEW.zip
|
||||
python installer/ota-tool.py generate OLD.zip NEW.zip update.ota
|
||||
python installer/ota-tool.py update update.ota --host 192.168.9.1
|
||||
```
|
||||
|
||||
公共根文件系统构建器和 E5 六机型组包器均调用 `installer/stage-ota.py`,不依赖
|
||||
某一个机型的私有 stage,不会增加对 AT 命令、开机回放、充电或 USB 的操作。
|
||||
|
||||
## 2026-10-20 开发构建结果
|
||||
|
||||
- Windows 工具:`out/tools/OpenWrt-Diff-Studio-20261020/`,打开其中的
|
||||
`OpenWrt-Diff-Studio.exe`;必须保留同目录的 `tools/` 和其他附属文件。
|
||||
这份工具同时读取两个仓库的包,只有一份 Windows 原生构建。
|
||||
- 使用实际 E5 发行 ZIP 解析了 6115 个文件、376 个基础软件包;实际 MU300 包
|
||||
解析了 2409 个文件、174 个基础软件包。只读输入,没有写入设备。
|
||||
- 已测试封装后后端的分析与导出,以及原生 EXE 启动。测试生成的桌面差异 ZIP
|
||||
约 16.6 MB,其中实际 OTA 为 647 字节,其余是共用 GUI/Python 运行库。
|
||||
没有 boot/rootfs 副本。这里只是小型测试差异,不能据此推算实际更新大小。
|
||||
- 浏览器回归覆盖分析/导出、应用完成与冲突拒绝,另外通过真实小 ext4 样本验证
|
||||
Windows 下的只读解析。Linux 测试覆盖写入中途进程退出、恢复和手动回退。
|
||||
- 固件包尚未重新组装,实机尚未安装 OTA 插件或试刷补丁;Mac 仅接入原生构建
|
||||
路径,本轮未在 Mac 上构建或运行。
|
||||
|
||||
## 2026-10-21 Windows 启动与间距修正
|
||||
|
||||
- 已复现的闪退原因:Tauri 的 setup 阶段窗口 URL 仍可能是 `about:blank`,
|
||||
对它执行相对地址拼接会返回错误,引发 setup panic,Windows 退出码为
|
||||
`0xc0000409`。原先只等约三秒的启动检查不足以发现这个问题。
|
||||
- 两仓库共用入口改为在创建窗口前指定 `WebviewUrl::App` 和标题,移除 setup
|
||||
导航。生成器、普通安装器和补丁更新器分别打开对应页面;Mac 导出的更新器
|
||||
以 `.app` 名称识别,避免被内部仍带 diff 字样的可执行文件名误判。
|
||||
- 卡片下方与说明分隔线之间增加 24 px 留白;生成器与更新器共用,桌面及
|
||||
窄窗口的浏览器实际布局检查通过。
|
||||
- Windows 重新编译并原地更新 `out/tools/OpenWrt-Diff-Studio-20261020/`。
|
||||
两项 Rust 路由测试通过;通过 Windows UI Automation 检查真实前端,生成器
|
||||
与实际导出 ZIP 中的更新器均连续运行 30 秒并正常关闭。更新器成功读取内置
|
||||
补丁版本;封装后后端的分析、真实 E5 ZIP 解析和桌面/网页合包导出也通过。
|
||||
- 原生启动回归使用 `installer/tests/ota_frozen_smoke.py --native`,不修改
|
||||
发布程序的调试选项,不依赖开放调试端口。没有新增实机 OTA 或 Mac 验证。
|
||||
@@ -0,0 +1,7 @@
|
||||
# 扩展 SIM 就绪通知兼容
|
||||
|
||||
E5 系列的 angelcare K1 实机在插卡时先报告 `+ECIND: 3,100`(此时 CPIN 仍为 SIM busy),随后报告 `+ECIND: 3,0,0,1`;旧解析器因多出的数值字段丢弃了后一个通知。原厂 RIL 的 onSimStatusChanged 根据 type/value/cause 通知状态变化,不要求在 cause 后结束。K1 的实际通知是该复现的设备证据,不表示 MU300 所有型号都已物理验证。
|
||||
|
||||
MU300 的共享 registration.sh 也有相同字段数量限制。现在允许尾随数值元数据,并拒绝负数、溢出、非数字、空字段和尾随逗号。事件值、原因筛选和槽位范围保持原有规则;通知仍只是交给现有 AT owner 的状态重查提示,不直接写入 SIM 缓存,也不从尾字段推断卡槽或卡状态。不增加轮询、无线复位或额外 AT owner。
|
||||
|
||||
Linux 下 tests/test_sim_events.py 的 5 项测试通过,包含扩展事件和无效字段,以及原有 CPIN 缓存隔离、未知回复与无卡短信行为。没有对 MU300 设备部署、重启或进行物理插卡测试,也没有生成发布包。
|
||||
@@ -0,0 +1,56 @@
|
||||
"""One payload for web import plus the existing native desktop runtime."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import json
|
||||
import hashlib
|
||||
import zipfile
|
||||
|
||||
|
||||
def export_bundle(patch, output, runtime):
|
||||
"""Use the generator's own fingerprinted runtime, including offline exports."""
|
||||
runtime = Path(runtime)
|
||||
build = json.loads((runtime / 'diff-tool.json').read_text())
|
||||
if build.get('protocol') != 1 or not build.get('files'):
|
||||
raise ValueError('Missing Diff Studio runtime manifest; run installer/build-ota.py')
|
||||
for name, expected in build['files'].items():
|
||||
source = (runtime / name).resolve()
|
||||
if not source.is_relative_to(runtime.resolve()) or not source.is_file():
|
||||
raise ValueError('Missing or unsafe native runtime file')
|
||||
with source.open('rb') as stream:
|
||||
from .ota_engine import digest
|
||||
if digest(stream) != expected:
|
||||
raise ValueError('Native runtime checksum mismatch: ' + name)
|
||||
output = Path(output)
|
||||
if output.exists():
|
||||
raise ValueError('Output already exists')
|
||||
tmp = output.with_suffix(output.suffix + '.building')
|
||||
if tmp.exists():
|
||||
raise ValueError('Output staging exists')
|
||||
try:
|
||||
with zipfile.ZipFile(tmp, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=6) as z:
|
||||
z.write(patch, 'update.ota')
|
||||
for name in build['files']:
|
||||
if name == 'OpenWrt-Diff-Studio.exe':
|
||||
dest = 'OpenWrt-Updater.exe'
|
||||
elif name.startswith('OpenWrt-Diff-Studio.app/'):
|
||||
dest = name.replace('OpenWrt-Diff-Studio.app/', 'OpenWrt-Updater.app/', 1)
|
||||
elif name == 'OpenWrt-Diff-Studio.py':
|
||||
dest = 'OpenWrt-Updater.py'
|
||||
elif name.startswith(('tools/', 'backend/')):
|
||||
dest = name
|
||||
else:
|
||||
continue
|
||||
z.write(runtime / name, dest)
|
||||
z.writestr('README.md', '# OpenWrt file hotfix\n\n'
|
||||
'Web: import update.ota in System > System patches.\n'
|
||||
'Desktop: extract the complete folder and open OpenWrt-Updater.exe / .app.\n'
|
||||
'Python: python OpenWrt-Updater.py update update.ota --host DEVICE_IP '
|
||||
'(requires paramiko).\n\n'
|
||||
'网页:系统 → 系统补丁,导入 update.ota。\n'
|
||||
'电脑:完整解压后打开 OpenWrt-Updater.exe。\n'
|
||||
'仅使用可信补丁;先核对目标版本、机型和冲突检查。\n'
|
||||
'更新后请重启;网页支持撤销上次补丁。\n')
|
||||
os.rename(tmp, output)
|
||||
finally:
|
||||
if tmp.exists():
|
||||
tmp.unlink()
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Diff generator and SSH updater shared by the portable Tauri frontend."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shlex
|
||||
import tempfile
|
||||
import time
|
||||
import zipfile
|
||||
|
||||
from .ota_engine import Patch, digest
|
||||
from .ota_package import analyze
|
||||
|
||||
|
||||
def execute(client, command, timeout=1800):
|
||||
channel = client.get_transport().open_session(timeout=20)
|
||||
channel.exec_command(command)
|
||||
out, err = bytearray(), bytearray()
|
||||
deadline = time.monotonic() + timeout
|
||||
while not channel.exit_status_ready() or channel.recv_ready() or channel.recv_stderr_ready():
|
||||
if channel.recv_ready():
|
||||
out.extend(channel.recv(65536))
|
||||
if channel.recv_stderr_ready():
|
||||
err.extend(channel.recv_stderr(65536))
|
||||
if len(out) + len(err) > 32 << 20:
|
||||
channel.close()
|
||||
raise ValueError('Device response exceeded limit')
|
||||
if time.monotonic() > deadline:
|
||||
channel.close()
|
||||
raise TimeoutError('Device update is still running; reconnect and check status')
|
||||
time.sleep(.02)
|
||||
code = channel.recv_exit_status()
|
||||
if code:
|
||||
raise RuntimeError(out.decode('utf-8', 'replace') + err.decode('utf-8', 'replace'))
|
||||
return out.decode('utf-8', 'replace')
|
||||
|
||||
|
||||
def connect(host, password):
|
||||
import paramiko
|
||||
if not isinstance(host, str) or not host or len(host) > 253 or any(c.isspace() for c in host):
|
||||
raise ValueError('Enter the device management address')
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
try:
|
||||
client.connect(host, username='root', password=password, look_for_keys=False, allow_agent=False,
|
||||
timeout=15, banner_timeout=15, auth_timeout=15)
|
||||
except BaseException:
|
||||
client.close()
|
||||
raise
|
||||
return client
|
||||
|
||||
|
||||
def remote_inspect(client, archive, emit=lambda *_: None):
|
||||
with Patch(archive) as patch:
|
||||
# Only the installed engine runs with root privileges. The package may
|
||||
# contain data, never its own update program. Bootstrap older releases
|
||||
# through a full installer rather than executing uploaded arbitrary code.
|
||||
execute(client, 'test -f /usr/lib/unisoc-ota/engine.py && command -v python3 >/dev/null')
|
||||
destination = '/etc/unisoc-ota/upload-' + patch.id + '.ota'
|
||||
total = Path(archive).stat().st_size
|
||||
free = int(execute(client, "df -Pk /etc | awk 'END {print $4}'").strip()) * 1024
|
||||
if total + (32 << 20) > free:
|
||||
raise ValueError('Insufficient device staging space')
|
||||
execute(client, 'umask 077; mkdir -p /etc/unisoc-ota')
|
||||
channel = client.get_transport().open_session(timeout=20)
|
||||
channel.exec_command('umask 077; cat > ' + shlex.quote(destination + '.new'))
|
||||
sent = 0
|
||||
with Path(archive).open('rb') as stream:
|
||||
expected = digest(stream)
|
||||
stream.seek(0)
|
||||
for block in iter(lambda: stream.read(128 << 10), b''):
|
||||
channel.sendall(block)
|
||||
sent += len(block)
|
||||
emit('ota_progress', dict(stage='upload', done=sent, total=total))
|
||||
channel.shutdown_write()
|
||||
if channel.recv_exit_status() != 0:
|
||||
raise ValueError('Device upload failed')
|
||||
got = execute(client, 'sha256sum ' + shlex.quote(destination + '.new')).split()[0]
|
||||
if got != expected:
|
||||
raise ValueError('Device upload checksum mismatch')
|
||||
execute(client, 'mv ' + shlex.quote(destination + '.new') + ' ' + shlex.quote(destination))
|
||||
result = json.loads(execute(client, 'python3 /usr/lib/unisoc-ota/engine.py inspect ' + shlex.quote(destination)))
|
||||
return dict(path=destination, check=result)
|
||||
|
||||
|
||||
class Desktop:
|
||||
def __init__(self, root, emit):
|
||||
self.root = Path(root)
|
||||
self.emit = emit
|
||||
self.analysis = None
|
||||
self.review = None
|
||||
self.last_event = 0
|
||||
|
||||
def progress(self, stage, path):
|
||||
if time.monotonic() - self.last_event >= .4:
|
||||
self.last_event = time.monotonic()
|
||||
self.emit('ota_progress', dict(stage=stage, path=path))
|
||||
|
||||
def dispatch(self, command, p):
|
||||
self.emit('ota_activity', {'busy': True})
|
||||
try:
|
||||
if command in ('ota_analyze', 'ota_export'):
|
||||
if command == 'ota_analyze':
|
||||
self.analysis = dict(old=p['old'], new=p['new'])
|
||||
if not self.analysis:
|
||||
raise ValueError('Analyze the old and new release first')
|
||||
if command == 'ota_export' and p.get('output', '').lower().endswith('.zip'):
|
||||
with tempfile.TemporaryDirectory(prefix='openwrt-ota-') as directory:
|
||||
patch = Path(directory) / 'update.ota'
|
||||
result = analyze(self.analysis['old'], self.analysis['new'], patch, self.progress)
|
||||
from .ota_bundle import export_bundle
|
||||
export_bundle(patch, p['output'], self.root)
|
||||
result['output'] = p['output']
|
||||
return result
|
||||
result = analyze(self.analysis['old'], self.analysis['new'],
|
||||
p.get('output') if command == 'ota_export' else None, self.progress)
|
||||
return result
|
||||
if command == 'ota_package':
|
||||
archive = Path(p.get('path') or self.root / 'update.ota')
|
||||
with Patch(archive) as patch:
|
||||
return dict(path=str(archive), id=patch.id, manifest=patch.manifest)
|
||||
if command == 'ota_probe':
|
||||
archive = Path(p.get('path') or self.root / 'update.ota')
|
||||
with connect(p['host'], p['password']) as client:
|
||||
result = remote_inspect(client, archive, self.emit)
|
||||
key = hashlib.sha256(client.get_transport().get_remote_server_key().asbytes()).hexdigest()
|
||||
token = secrets.token_hex(24)
|
||||
self.review = dict(host=p['host'], key=key, token=token, **result)
|
||||
return dict(token=token, **result)
|
||||
if command == 'ota_apply':
|
||||
r = self.review
|
||||
if not r or p.get('token') != r['token'] or p['host'] != r['host']:
|
||||
raise ValueError('Review this device and patch before applying')
|
||||
with connect(p['host'], p['password']) as client:
|
||||
key = hashlib.sha256(client.get_transport().get_remote_server_key().asbytes()).hexdigest()
|
||||
if key != r['key']:
|
||||
raise ValueError('Device SSH identity changed since review')
|
||||
# Installed runner owns the detached transaction. Losing the
|
||||
# PC connection does not kill an in-progress filesystem write.
|
||||
result = execute(client, 'python3 /usr/lib/unisoc-ota/rpc.py start ' + shlex.quote(r['path']))
|
||||
self.review = None
|
||||
return json.loads(result)
|
||||
if command == 'ota_status':
|
||||
with connect(p['host'], p['password']) as client:
|
||||
return json.loads(execute(client, 'python3 /usr/lib/unisoc-ota/rpc.py status'))
|
||||
raise ValueError('Unknown OTA command')
|
||||
finally:
|
||||
self.emit('ota_activity', {'busy': False})
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Load the exact engine shipped by the LuCI package, not another implementation."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
if getattr(sys, 'frozen', False):
|
||||
_path = Path(sys._MEIPASS) / 'engine.py'
|
||||
else:
|
||||
_path = Path(__file__).resolve().parents[2] / 'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota/engine.py'
|
||||
_spec = importlib.util.spec_from_file_location('unisoc_ota_engine', _path)
|
||||
_module = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(_module)
|
||||
globals().update({k:v for k,v in vars(_module).items() if not k.startswith('__')})
|
||||
@@ -0,0 +1,307 @@
|
||||
"""Read full E5/MU300 releases without mounting or unpacking a root tree."""
|
||||
import base64
|
||||
from contextlib import ExitStack
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import stat
|
||||
import tarfile
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
from .ota_engine import FORMAT, MAX_BYTES, OFFLINE_ONLY, canonical, digest, package_versions, protected, safe_name, validate_manifest
|
||||
|
||||
|
||||
class Release:
|
||||
def __init__(self, source, progress=lambda *_: None):
|
||||
self.source = Path(source)
|
||||
self.progress = progress
|
||||
self.stack = ExitStack()
|
||||
self.entries = {}
|
||||
self.packages = {}
|
||||
|
||||
def __enter__(self):
|
||||
try:
|
||||
self.load()
|
||||
return self
|
||||
except BaseException:
|
||||
self.stack.close()
|
||||
raise
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.stack.close()
|
||||
|
||||
def load(self):
|
||||
if self.source.is_dir():
|
||||
self.prefix = ''
|
||||
self.files = None
|
||||
else:
|
||||
self.files = self.stack.enter_context(zipfile.ZipFile(self.source))
|
||||
names = self.files.namelist()
|
||||
if len(names) != len(set(names)):
|
||||
raise ValueError('Duplicate files in full package')
|
||||
matches = [n[:-len('files/device-profile.json')] for n in names if n.endswith('files/device-profile.json')]
|
||||
matches += [n[:-len('desktop/manifest.json')] for n in names if n.endswith('desktop/manifest.json')]
|
||||
if len(matches) != 1:
|
||||
raise ValueError('Select a single complete release ZIP')
|
||||
self.prefix = matches[0]
|
||||
if self.exists('desktop/manifest.json'):
|
||||
self.family = 'mu300'
|
||||
self.meta = self.json('desktop/release.json')
|
||||
self.package = self.json('desktop/manifest.json')
|
||||
mapping = self.package.get('magisk_layout', {})
|
||||
rootfs = mapping.get('mu300-openwrt.tar.gz', 'mu300-openwrt.tar.gz')
|
||||
self.boot_name = mapping.get('boot-linux.img', 'boot-linux.img')
|
||||
checks = {**self.package['magisk'], **self.package['desktop']}
|
||||
self.check(rootfs, checks[rootfs])
|
||||
self.check(self.boot_name, checks[self.boot_name])
|
||||
if 'desktop/release.json' in checks:
|
||||
self.check('desktop/release.json', checks['desktop/release.json'])
|
||||
source = self.stack.enter_context(self.open(rootfs))
|
||||
tar = self.stack.enter_context(tarfile.open(fileobj=source, mode='r|gz'))
|
||||
# Sequential tar reading avoids extracting a root tree or retaining a
|
||||
# second compressed copy. Only metadata and hashes stay in memory.
|
||||
for node in tar:
|
||||
name = node.name.removeprefix('./').rstrip('/')
|
||||
if name in ('', '.'):
|
||||
continue
|
||||
safe_name(name)
|
||||
if name in self.entries:
|
||||
raise ValueError('Duplicate rootfs path: ' + name)
|
||||
d = dict(mode=node.mode, uid=node.uid, gid=node.gid, xattrs={})
|
||||
for k, v in node.pax_headers.items():
|
||||
if k.startswith('SCHILY.xattr.'):
|
||||
d['xattrs'][k[13:]] = base64.b64encode(v.encode('utf-8', 'surrogateescape')).decode()
|
||||
if node.isdir():
|
||||
d.update(kind='dir')
|
||||
elif node.issym():
|
||||
d.update(kind='symlink', target=node.linkname)
|
||||
elif node.isfile():
|
||||
stream = tar.extractfile(node)
|
||||
if name == 'lib/apk/db/installed':
|
||||
raw = stream.read(32 << 20)
|
||||
if len(raw) != node.size:
|
||||
raise ValueError('Oversized package database')
|
||||
self.packages = package_versions(raw)
|
||||
d.update(kind='file', size=node.size, sha256=hashlib.sha256(raw).hexdigest())
|
||||
else:
|
||||
d.update(kind='file', size=node.size, sha256=digest(stream))
|
||||
elif node.islnk():
|
||||
target = node.linkname.removeprefix('./')
|
||||
if target not in self.entries or self.entries[target]['kind'] != 'file':
|
||||
raise ValueError('Unsupported forward tar hardlink: ' + name)
|
||||
d = dict(self.entries[target])
|
||||
else:
|
||||
continue
|
||||
self.entries[name] = d
|
||||
self.progress('index', name)
|
||||
self.rootfs_name = rootfs
|
||||
else:
|
||||
self.family = 'e5'
|
||||
self.meta = self.json('files/RELEASE.json')
|
||||
self.package = self.json('files/device-profile.json')
|
||||
checks = {}
|
||||
with self.open('files/SHA256SUMS') as stream:
|
||||
for line in stream.read().decode().splitlines():
|
||||
h, n = line.split(None, 1)
|
||||
checks[n.strip().removeprefix('*')] = h
|
||||
self.boot_name = 'files/boot.img'
|
||||
self.rootfs_name = 'files/openwrt.ext4.gz'
|
||||
self.check(self.rootfs_name, checks[self.rootfs_name])
|
||||
self.check(self.boot_name, checks[self.boot_name])
|
||||
for name in ('files/RELEASE.json', 'files/device-profile.json'):
|
||||
if name in checks:
|
||||
self.check(name, checks[name])
|
||||
# One temporary decompressed image, closed/unlinked on every exit.
|
||||
# This is read-only userspace parsing, not a loop mount or WSL copy.
|
||||
scratch = self.source if self.source.is_dir() else self.source.parent
|
||||
image = self.stack.enter_context(tempfile.TemporaryFile(dir=scratch))
|
||||
with self.open(self.rootfs_name) as compressed, gzip.GzipFile(fileobj=compressed) as stream:
|
||||
total = 0
|
||||
for block in iter(lambda: stream.read(4 << 20), b''):
|
||||
total += len(block)
|
||||
if total > 16 << 30:
|
||||
raise ValueError('Root image exceeds 16 GiB')
|
||||
if shutil.disk_usage(scratch).free < len(block) + (64 << 20):
|
||||
raise ValueError('Insufficient temporary disk space')
|
||||
image.write(block)
|
||||
image.seek(0)
|
||||
from dissect.extfs import ExtFS
|
||||
self.extfs = ExtFS(image)
|
||||
seen = set()
|
||||
|
||||
def walk(node, prefix=''):
|
||||
if node.inum in seen:
|
||||
raise ValueError('Cyclic ext4 directory')
|
||||
seen.add(node.inum)
|
||||
for child in node.iterdir():
|
||||
if child.filename in ('.', '..'):
|
||||
continue
|
||||
name = safe_name(prefix + child.filename)
|
||||
d = dict(mode=int(stat.S_IMODE(child.inode.i_mode)), uid=int(child.inode.i_uid),
|
||||
gid=int(child.inode.i_gid),
|
||||
xattrs={a.name: base64.b64encode(a.value).decode() for a in child.xattr})
|
||||
if child.filetype == stat.S_IFDIR:
|
||||
d.update(kind='dir')
|
||||
elif child.filetype == stat.S_IFLNK:
|
||||
d.update(kind='symlink', target=child.link)
|
||||
elif child.filetype == stat.S_IFREG:
|
||||
with child.open() as f:
|
||||
d.update(kind='file', size=child.size, sha256=digest(f))
|
||||
if name == 'lib/apk/db/installed':
|
||||
f.seek(0)
|
||||
self.packages = package_versions(f.read(32 << 20))
|
||||
else:
|
||||
continue
|
||||
self.entries[name] = d
|
||||
self.progress('index', name)
|
||||
if d['kind'] == 'dir':
|
||||
walk(child, name + '/')
|
||||
seen.remove(node.inum)
|
||||
walk(self.extfs.root)
|
||||
for k in ('image_version', 'profile', 'kernel_release', 'openwrt'):
|
||||
if not isinstance(self.meta.get(k), str):
|
||||
raise ValueError('Full release has no versioned ' + k)
|
||||
# Hash the meaningful boot as a whole; any initramfs change needs the
|
||||
# full installer until a bound, offline kernel transaction is supported.
|
||||
with self.open(self.boot_name) as f:
|
||||
self.boot_hash = digest(f)
|
||||
|
||||
def exists(self, name):
|
||||
return self.prefix + name in self.files.namelist() if self.files else (self.source / name).is_file()
|
||||
|
||||
def open(self, name):
|
||||
safe_name(name)
|
||||
if self.files:
|
||||
return self.files.open(self.prefix + name)
|
||||
path = (self.source / name).resolve()
|
||||
if not path.is_relative_to(self.source.resolve()):
|
||||
raise ValueError('Package path escapes root')
|
||||
return path.open('rb')
|
||||
|
||||
def json(self, name):
|
||||
with self.open(name) as f:
|
||||
return json.load(f)
|
||||
|
||||
def check(self, name, wanted):
|
||||
with self.open(name) as stream:
|
||||
if digest(stream) != wanted:
|
||||
raise ValueError('Full package checksum mismatch: ' + name)
|
||||
|
||||
def write_blobs(self, archive, wanted):
|
||||
pending = set(wanted)
|
||||
if hasattr(self, 'extfs'):
|
||||
for name, d in self.entries.items():
|
||||
if d.get('sha256') in pending:
|
||||
with self.extfs.get(name).open() as source, archive.open('blobs/' + d['sha256'], 'w') as dest:
|
||||
shutil.copyfileobj(source, dest, 1 << 20)
|
||||
pending.remove(d['sha256'])
|
||||
else:
|
||||
with self.open(self.rootfs_name) as source, tarfile.open(fileobj=source, mode='r|gz') as tar:
|
||||
for node in tar:
|
||||
name = node.name.removeprefix('./').rstrip('/')
|
||||
d = self.entries.get(name, {})
|
||||
if d.get('sha256') not in pending or not node.isfile():
|
||||
continue
|
||||
with tar.extractfile(node) as stream, archive.open('blobs/' + d['sha256'], 'w') as dest:
|
||||
shutil.copyfileobj(stream, dest, 1 << 20)
|
||||
pending.remove(d['sha256'])
|
||||
if pending:
|
||||
raise ValueError('Cannot find payload content: ' + ', '.join(pending))
|
||||
|
||||
|
||||
def compare(old, new):
|
||||
for name in ('family',):
|
||||
if getattr(old, name) != getattr(new, name):
|
||||
raise ValueError('Packages belong to different device families')
|
||||
for k in ('profile', 'openwrt'):
|
||||
if old.meta[k] != new.meta[k]:
|
||||
raise ValueError('Incompatible full releases: ' + k)
|
||||
operations, preserved, blockers = [], [], []
|
||||
if old.meta['kernel_release'] != new.meta['kernel_release'] or old.boot_hash != new.boot_hash:
|
||||
blockers.append('Kernel/boot changed: use the full installer for this release')
|
||||
for name in sorted(set(old.entries) | set(new.entries)):
|
||||
before, after = old.entries.get(name), new.entries.get(name)
|
||||
if before == after:
|
||||
continue
|
||||
if any(name == p or name.startswith(p + '/') for p in OFFLINE_ONLY):
|
||||
blockers.append('Core runtime/module/updater changed; use the full installer: ' + name)
|
||||
continue
|
||||
if protected(name):
|
||||
preserved.append(name)
|
||||
continue
|
||||
if before and before['kind'] == 'dir' and not after:
|
||||
# Keeping an unused directory preserves user-installed contents.
|
||||
preserved.append(name)
|
||||
continue
|
||||
operations.append(dict(path=name, before=before, after=after))
|
||||
# Do not silently install files of new/removed APK packages without running
|
||||
# package ownership/dependency/script handling. Same package set hotfixes are
|
||||
# explicitly tracked as file overrides, leaving user packages untouched.
|
||||
for name in ('lib/apk/db/installed', 'usr/lib/opkg/status'):
|
||||
a, b = old.entries.get(name), new.entries.get(name)
|
||||
if (a is None) != (b is None):
|
||||
blockers.append('Package database format changed')
|
||||
owned = {'luci-app-t551m', 'luci-app-mu300'}
|
||||
if set(old.packages) != set(new.packages):
|
||||
blockers.append('Installed package set changed; use the full installer')
|
||||
for name in sorted(set(old.packages) & set(new.packages)):
|
||||
a, b = old.packages[name], new.packages[name]
|
||||
if name in owned:
|
||||
a = dict(a, V=b['V'])
|
||||
if a != b:
|
||||
blockers.append('Package ABI/dependencies changed: ' + name)
|
||||
m = dict(format=FORMAT, family=new.family, profile=new.meta['profile'],
|
||||
base_version=old.meta['image_version'], target_version=new.meta['image_version'],
|
||||
kernel_release=new.meta['kernel_release'], operations=operations,
|
||||
preserved=preserved, mode='file-hotfix', base_packages=old.packages)
|
||||
if operations:
|
||||
try:
|
||||
validate_manifest(m)
|
||||
except ValueError as e:
|
||||
blockers.append(str(e))
|
||||
else:
|
||||
blockers.append('No hotfixable system files changed')
|
||||
blobs = {o['after']['sha256']: o['after']['size'] for o in operations
|
||||
if o['after'] and o['after']['kind'] == 'file'}
|
||||
return dict(manifest=m, blockers=blockers, can_export=not blockers,
|
||||
payload_bytes=sum(blobs.values()), files=len(operations),
|
||||
added=sum(o['before'] is None for o in operations),
|
||||
removed=sum(o['after'] is None for o in operations))
|
||||
|
||||
|
||||
def analyze(old_path, new_path, output=None, progress=lambda *_: None):
|
||||
# Old image is released before decompressing the new one. Only the previous
|
||||
# index survives; no pair of multi-GiB roots is retained.
|
||||
with Release(old_path, progress) as old:
|
||||
pass
|
||||
with Release(new_path, progress) as new:
|
||||
result = compare(old, new)
|
||||
if output:
|
||||
if result['blockers']:
|
||||
raise ValueError('; '.join(result['blockers'][:12]))
|
||||
output = Path(output)
|
||||
if output.exists():
|
||||
raise ValueError('Output already exists; select a new filename')
|
||||
tmp = output.with_suffix(output.suffix + '.building')
|
||||
if tmp.exists():
|
||||
raise ValueError('Output staging exists')
|
||||
try:
|
||||
with zipfile.ZipFile(tmp, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
|
||||
archive.writestr('manifest.json', canonical(result['manifest']))
|
||||
wanted = {o['after']['sha256'] for o in result['manifest']['operations']
|
||||
if o['after'] and o['after']['kind'] == 'file'}
|
||||
new.write_blobs(archive, wanted)
|
||||
from .ota_engine import Patch
|
||||
with Patch(tmp):
|
||||
pass
|
||||
os.rename(tmp, output)
|
||||
result['output'] = str(output)
|
||||
result['archive_bytes'] = output.stat().st_size
|
||||
finally:
|
||||
if tmp.exists():
|
||||
tmp.unlink()
|
||||
return result
|
||||
@@ -101,6 +101,8 @@ class Service:
|
||||
self.verification_lock = threading.Lock()
|
||||
self.verification_request = None
|
||||
self.verification_wake = threading.Event()
|
||||
from .ota_desktop import Desktop
|
||||
self.ota = Desktop(self.package_root, self.emit)
|
||||
|
||||
def emit(self, kind, data, request_id=None):
|
||||
event = {'protocol': 1, 'type': kind, 'data': data}
|
||||
@@ -129,6 +131,10 @@ class Service:
|
||||
command, p = request.get('command'), request.get('params', {})
|
||||
if not isinstance(p, dict):
|
||||
raise ValueError('Parameters must be an object')
|
||||
if command.startswith('ota_'):
|
||||
if self.worker and self.worker.is_alive():
|
||||
raise ValueError('Another installer task is running')
|
||||
return self.ota.dispatch(command, p)
|
||||
if command == 'hello':
|
||||
return {'protocol': 1, 'app_data': str(self.store.base), 'package_path': self.package_root,
|
||||
'transactions': [self.public(r) for r in self.store.list()]}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Assemble standalone Diff Studio using the existing fingerprinted Tauri build.
|
||||
|
||||
Compile installer/build.py once on the native platform, then run this tool.
|
||||
No second npm install, Rust target tree or Python runtime copy is built here.
|
||||
"""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import json
|
||||
from package_gui import digest
|
||||
from package_gui import sources, validate_artifact
|
||||
from build import native_platform
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--artifact', type=Path)
|
||||
p.add_argument('--output', type=Path, required=True)
|
||||
p.add_argument('--refresh', action='store_true', help='refresh an unchanged owned Windows tool directory')
|
||||
a = p.parse_args()
|
||||
installer = Path(__file__).resolve().parent
|
||||
platform = native_platform()
|
||||
mac = platform == 'macos-arm64'
|
||||
artifact = a.artifact or installer / ('artifacts/macos-arm64' if mac else 'artifacts/windows')
|
||||
validate_artifact(artifact, platform, sources())
|
||||
if a.output.exists():
|
||||
if not a.refresh or mac:
|
||||
raise ValueError('Select a new output directory (Windows --refresh requires an unchanged owned directory)')
|
||||
recorded=json.loads((a.output/'diff-tool.json').read_text(encoding='utf-8'))
|
||||
expected={'OpenWrt-Diff-Studio.exe','OpenWrt-Diff-Studio.py'}
|
||||
expected.update('backend/'+n for n in ('__init__.py','ota_engine.py','ota_package.py','ota_desktop.py','ota_bundle.py'))
|
||||
expected.update(path.relative_to(artifact).as_posix() for path in (artifact/'tools/backend').rglob('*') if path.is_file())
|
||||
actual={path.relative_to(a.output).as_posix() for path in a.output.rglob('*') if path.is_file() and path.name!='diff-tool.json'}
|
||||
if recorded.get('protocol')!=1 or set(recorded.get('files',{}))!=expected or actual!=expected:
|
||||
raise ValueError('Tool file layout changed; use a new directory')
|
||||
for name,want in recorded['files'].items():
|
||||
source=(a.output/name).resolve()
|
||||
if not source.is_relative_to(a.output.resolve()) or digest(source)!=want:
|
||||
raise ValueError('Tool directory has local changes; use a new directory')
|
||||
else:
|
||||
a.output.mkdir(parents=True)
|
||||
try:
|
||||
if mac:
|
||||
import plistlib
|
||||
import subprocess
|
||||
app = a.output / 'OpenWrt-Diff-Studio.app'
|
||||
shutil.copytree(artifact / 'OpenWrt-Installer.app', app)
|
||||
old = app / 'Contents/MacOS/openwrt-installer'
|
||||
old.rename(old.with_name('openwrt-diff-studio'))
|
||||
info = app / 'Contents/Info.plist'
|
||||
metadata = plistlib.loads(info.read_bytes())
|
||||
metadata.update(CFBundleExecutable='openwrt-diff-studio', CFBundleName='OpenWrt Diff Studio',
|
||||
CFBundleDisplayName='OpenWrt Diff Studio', CFBundleIdentifier='org.openwrt.diff-studio')
|
||||
info.write_bytes(plistlib.dumps(metadata))
|
||||
subprocess.run(['codesign', '--force', '--deep', '--sign', '-', str(app)], check=True)
|
||||
dest = a.output / 'tools/macos/backend'
|
||||
shutil.copytree(artifact / 'tools/macos/backend', dest)
|
||||
else:
|
||||
shutil.copy2(artifact / 'OpenWrt-Installer.exe', a.output / 'OpenWrt-Diff-Studio.exe')
|
||||
shutil.copytree(artifact / 'tools/backend', a.output / 'tools/backend', dirs_exist_ok=a.refresh)
|
||||
shutil.copy2(installer / 'ota-tool.py', a.output / 'OpenWrt-Diff-Studio.py')
|
||||
(a.output / 'backend').mkdir(exist_ok=a.refresh)
|
||||
for name in ('__init__.py', 'ota_engine.py', 'ota_package.py', 'ota_desktop.py', 'ota_bundle.py'):
|
||||
source = installer.parent/'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota/engine.py' if name=='ota_engine.py' else installer/'backend'/name
|
||||
shutil.copy2(source, a.output / 'backend' / name)
|
||||
files = {path.relative_to(a.output).as_posix(): digest(path)
|
||||
for path in a.output.rglob('*') if path.is_file() and path.name!='diff-tool.json'}
|
||||
(a.output / 'diff-tool.json').write_text(json.dumps(dict(protocol=1, platform=platform, files=files,
|
||||
source=sources()), indent=2) + '\n')
|
||||
except BaseException:
|
||||
# Retain failed output for inspection, never recursively clean user paths.
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+2
-1
@@ -50,7 +50,8 @@ def main():
|
||||
'--hidden-import','lz4.block','--hidden-import','xml.etree.ElementTree','--hidden-import','xml.parsers.expat',
|
||||
'--hidden-import','tarfile','--hidden-import','gzip','--hidden-import','zlib','--hidden-import','lzma',
|
||||
'--hidden-import','bz2','--hidden-import','http.server','--hidden-import','decimal',
|
||||
'--collect-all','paramiko',HERE/'backend_entry.py')
|
||||
'--add-data', str(HERE.parent/'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota/engine.py')+os.pathsep+'.',
|
||||
'--collect-all','paramiko','--collect-all','dissect.extfs',HERE/'backend_entry.py')
|
||||
artifact = HERE/('artifacts/macos-arm64' if mac else 'artifacts/windows')
|
||||
artifact.mkdir(parents=True,exist_ok=True)
|
||||
tools = artifact/('tools/macos' if mac else 'tools')
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Desktop read-only ext4 parser, never installed on the OpenWrt device.
|
||||
dissect.extfs==3.15
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Portable command line companion to OpenWrt Diff Studio / OTA updater."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
from backend.ota_package import analyze
|
||||
from backend.ota_desktop import Desktop
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
sub = p.add_subparsers(dest='command', required=True)
|
||||
for name in ('analyze', 'generate'):
|
||||
q = sub.add_parser(name)
|
||||
q.add_argument('old')
|
||||
q.add_argument('new')
|
||||
if name == 'generate':
|
||||
q.add_argument('output')
|
||||
q = sub.add_parser('update')
|
||||
q.add_argument('package')
|
||||
q.add_argument('--host', required=True)
|
||||
args = p.parse_args()
|
||||
if args.command != 'update':
|
||||
result = analyze(args.old, args.new, getattr(args, 'output', None))
|
||||
else:
|
||||
import getpass
|
||||
d = Desktop(Path(__file__).parent, lambda *_: None)
|
||||
params = dict(host=args.host, password=getpass.getpass('SSH root password: '), path=args.package)
|
||||
result = d.dispatch('ota_probe', params)
|
||||
print(json.dumps(result['check'], indent=2))
|
||||
if not result['check']['applicable']:
|
||||
raise ValueError('Device files conflict or lack space')
|
||||
if input('Apply this file hotfix and retain rollback? Type yes: ') != 'yes':
|
||||
return
|
||||
result = d.dispatch('ota_apply', dict(params, token=result['token']))
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -17,14 +17,15 @@ def digest(path):
|
||||
|
||||
|
||||
def sources():
|
||||
paths = [HERE/n for n in ('backend_entry.py','build.py','package_gui.py','platform-tools.json','platform-tools-macos.json','GUIDE.md')]
|
||||
paths = [HERE/n for n in ('backend_entry.py','build.py','package_gui.py','platform-tools.json','platform-tools-macos.json','GUIDE.md','ota-tool.py','stage-ota.py','build-ota.py','ota-requirements.txt')]
|
||||
paths += list((HERE/'backend').glob('*.py'))
|
||||
paths += [HERE.parent/'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota/engine.py']
|
||||
paths += [p for p in (HERE/'ui/src').rglob('*') if p.is_file()]
|
||||
paths += [HERE/'ui'/n for n in ('package.json','package-lock.json','vite.config.ts','tailwind.config.js','postcss.config.js','tsconfig.json','index.html','rust-toolchain.toml')]
|
||||
paths += [HERE/'ui'/n for n in ('package.json','package-lock.json','vite.config.ts','tailwind.config.js','postcss.config.js','tsconfig.json','index.html','diff.html','ota.html','rust-toolchain.toml')]
|
||||
paths += [HERE/'ui/src-tauri'/n for n in ('Cargo.toml','Cargo.lock','build.rs','tauri.conf.json','src/main.rs','capabilities/default.json','icons/icon.ico','icons/icon.icns','icons/icon.png')]
|
||||
# Native Windows and macOS checkouts must identify the same source revision.
|
||||
text = {'.py','.ts','.tsx','.json','.toml','.rs','.js','.html','.md','.css','.lock'}
|
||||
return {p.relative_to(HERE).as_posix(): hashlib.sha256(p.read_bytes().replace(b'\r\n', b'\n')).hexdigest()
|
||||
text = {'.py','.ts','.tsx','.json','.toml','.rs','.js','.html','.md','.css','.lock','.txt'}
|
||||
return {os.path.relpath(p,HERE).replace('\\','/'): hashlib.sha256(p.read_bytes().replace(b'\r\n', b'\n')).hexdigest()
|
||||
if p.suffix in text else digest(p) for p in sorted(paths)}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stage the shared OTA plugin into a release root. No downloads or device I/O."""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
TOP = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def stage(root):
|
||||
root = Path(root)
|
||||
source = TOP / 'openwrt/luci-app-unisoc-ota'
|
||||
for folder, destination in (('root', ''), ('htdocs', 'www')):
|
||||
for path in (source / folder).rglob('*'):
|
||||
if not path.is_file() or '__pycache__' in path.parts:
|
||||
continue
|
||||
name = (Path(destination) / path.relative_to(source / folder)).as_posix()
|
||||
target = root / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if target.is_symlink():
|
||||
target.unlink()
|
||||
target.write_bytes(path.read_bytes().replace(b'\r\n', b'\n'))
|
||||
target.chmod(0o755 if name.startswith(('etc/init.d/', 'usr/libexec/')) else 0o644)
|
||||
(root / 'etc/unisoc-ota').mkdir(mode=0o700, exist_ok=True)
|
||||
rc = root / 'etc/rc.d/S06unisoc-ota'
|
||||
rc.parent.mkdir(parents=True, exist_ok=True)
|
||||
if rc.is_symlink():
|
||||
rc.unlink()
|
||||
rc.symlink_to('../init.d/unisoc-ota')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--root', required=True)
|
||||
stage(p.parse_args().root)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Exercise real Tauri frontend views with an offline bridge (no device writes)."""
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
BRIDGE = r'''
|
||||
let picked=0;
|
||||
const manifest={family:'e5',profile:'t551m',base_version:'t551m-r20261019.170725',target_version:'t551m-r20261020.180000',kernel_release:'6.18.54-t551m-otg10',operations:[{path:'usr/libexec/unisoc-modem/action',before:{},after:{}}],preserved:['etc/config/wireless']};
|
||||
window.__TAURI_INTERNALS__={transformCallback:()=>1,unregisterCallback:()=>{},invoke:async(cmd,args)=>{
|
||||
if(cmd==='plugin:event|listen')return 1;
|
||||
if(cmd==='pick_ota_input')return ++picked===1?'D:/Releases/old.zip':'D:/Releases/new.zip';
|
||||
if(cmd==='save_ota')return 'D:/Releases/update.ota';
|
||||
const command=args?.command;
|
||||
if(command==='ota_package')return {path:'D:/Releases/update.ota',manifest};
|
||||
if(command==='ota_analyze')return {manifest,blockers:[],can_export:true,payload_bytes:53720,files:1,added:0,removed:0};
|
||||
if(command==='ota_export')return {output:'D:/Releases/update.ota'};
|
||||
if(command==='ota_probe')return {token:'reviewed',check:{applicable:!window.testConflict,conflicts:window.testConflict?['usr/libexec/unisoc-modem/action']:[],package_conflicts:[],required_bytes:20000000,free_bytes:1000000000}};
|
||||
if(command==='ota_apply')return {status:'running'};
|
||||
if(command==='ota_status')return {identity:{version:manifest.target_version},job:{status:'complete'},transaction:{started:1,total:1}};
|
||||
return null;
|
||||
}};
|
||||
'''
|
||||
|
||||
|
||||
async def check_footer_spacing(page):
|
||||
await page.locator('.ota-footer').wait_for()
|
||||
gap = await page.evaluate('''() => document.querySelector('.ota-footer').getBoundingClientRect().top
|
||||
- Math.max(...Array.from(document.querySelectorAll('.ota-card'), el => el.getBoundingClientRect().bottom))''')
|
||||
assert gap >= 20, f'Footer separator touches cards: {gap}px'
|
||||
|
||||
|
||||
async def main():
|
||||
async with async_playwright() as p:
|
||||
browser=await p.chromium.launch(headless=True)
|
||||
page=await browser.new_page(viewport={'width':1120,'height':860})
|
||||
await page.add_init_script(BRIDGE)
|
||||
errors=[]
|
||||
page.on('pageerror',lambda e:errors.append(str(e)))
|
||||
await page.goto('http://127.0.0.1:1425/diff.html')
|
||||
await check_footer_spacing(page)
|
||||
choices=page.get_by_role('button',name='选择 ZIP 文件')
|
||||
await choices.nth(0).click();await choices.nth(0).click()
|
||||
await page.get_by_role('button',name='分析差异').click()
|
||||
await page.get_by_role('button',name='导出差异包').wait_for()
|
||||
await page.get_by_role('button',name='导出差异包').click()
|
||||
await page.get_by_role('status').wait_for()
|
||||
output=Path(__file__).resolve().parents[2]/'work/ota-ui-preview.png'
|
||||
await page.screenshot(path=str(output),full_page=True)
|
||||
await page.goto('http://127.0.0.1:1425/ota.html')
|
||||
await check_footer_spacing(page)
|
||||
await page.get_by_role('button',name='连接并检查').click()
|
||||
await page.get_by_role('button',name='确认应用此补丁').click()
|
||||
await page.get_by_text('更新完成,请在网页系统补丁页重启设备。').wait_for(timeout=10000)
|
||||
await page.evaluate('window.testConflict=true')
|
||||
await page.get_by_role('button',name='连接并检查').click()
|
||||
assert await page.get_by_role('button',name='确认应用此补丁').is_disabled()
|
||||
await page.set_viewport_size({'width':800,'height':650})
|
||||
await check_footer_spacing(page)
|
||||
assert await page.evaluate('document.documentElement.scrollWidth<=innerWidth')
|
||||
assert not errors,errors
|
||||
await browser.close()
|
||||
print('OTA browser workflows passed:',output)
|
||||
|
||||
|
||||
if __name__=='__main__':asyncio.run(main())
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Check the shipped backend, ext4 parser and combined desktop/web export."""
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parent))
|
||||
from test_ota import mu_release
|
||||
from backend.ota_engine import Patch
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('runtime',type=Path)
|
||||
p.add_argument('--e5-release',type=Path)
|
||||
p.add_argument('--native',action='store_true',help='Also launch the Windows GUI and exported updater for 30 seconds each')
|
||||
a=p.parse_args()
|
||||
exe=a.runtime/'tools/backend/openwrt-backend.exe'
|
||||
repo=Path(__file__).resolve().parents[2]
|
||||
with tempfile.TemporaryDirectory(prefix='ota-frozen-',dir=repo/'work') as directory:
|
||||
d=Path(directory)
|
||||
mu_release(d/'old','mu300-r1')
|
||||
mu_release(d/'new','mu300-r2',{'usr/lib/test':b'new'})
|
||||
requests=[dict(protocol=1,id=1,command='ota_analyze',params={'old':str(d/'old'),'new':str(d/'new')}),
|
||||
dict(protocol=1,id=2,command='ota_export',params={'output':str(d/'patch.zip')})]
|
||||
if a.e5_release:
|
||||
requests.append(dict(protocol=1,id=3,command='ota_analyze',params={'old':str(a.e5_release),'new':str(a.e5_release)}))
|
||||
result=subprocess.run([str(exe),'--package-root',str(a.runtime),'--data-dir',str(d/'state')],
|
||||
input=''.join(json.dumps(r)+'\n' for r in requests),encoding='utf-8',
|
||||
capture_output=True,timeout=120,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
|
||||
assert result.returncode==0,result.stderr
|
||||
replies={v['id']:v['data'] for line in result.stdout.splitlines() if (v:=json.loads(line)).get('type')=='response'}
|
||||
assert replies[1]['ok'] and replies[1]['result']['can_export'],replies
|
||||
assert replies[2]['ok'],replies
|
||||
with zipfile.ZipFile(d/'patch.zip') as z:
|
||||
names=z.namelist()
|
||||
assert names.count('update.ota')==1
|
||||
assert 'OpenWrt-Updater.exe' in names and 'OpenWrt-Updater.py' in names
|
||||
assert not any(n.endswith(('boot.img','boot-linux.img','rootfs.tar.gz','openwrt.ext4.gz')) for n in names)
|
||||
with Patch(io.BytesIO(z.read('update.ota'))) as patch:
|
||||
assert patch.manifest['target_version']=='mu300-r2'
|
||||
if a.e5_release:
|
||||
assert replies[3]['ok'],replies[3]
|
||||
assert replies[3]['result']['manifest']['family']=='e5'
|
||||
if a.native:
|
||||
from ota_native_smoke import check_launch
|
||||
check_launch(a.runtime/'OpenWrt-Diff-Studio.exe')
|
||||
with zipfile.ZipFile(d/'patch.zip') as z:
|
||||
z.extractall(d/'desktop')
|
||||
check_launch(d/'desktop/OpenWrt-Updater.exe','ota.html')
|
||||
print(json.dumps({'ok':True,'combined_zip_bytes':(d/'patch.zip').stat().st_size,
|
||||
'raw_hotfix_bytes':len(zipfile.ZipFile(d/'patch.zip').read('update.ota')),
|
||||
'full_e5_parser':bool(a.e5_release)}))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Check the shipped Windows app's real accessibility tree and sustained liveness.
|
||||
|
||||
Uses Windows UI Automation without a mocked bridge, debug build or open debugging
|
||||
port. No device access or writes. The updater must load its exported manifest.
|
||||
"""
|
||||
import argparse
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
|
||||
def window_handle(pid, title):
|
||||
user = ctypes.windll.user32
|
||||
found = []
|
||||
callback_type = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
||||
user.EnumWindows.argtypes = [callback_type, wintypes.LPARAM]
|
||||
user.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
|
||||
user.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
|
||||
|
||||
@callback_type
|
||||
def visit(window, _):
|
||||
owner = wintypes.DWORD()
|
||||
user.GetWindowThreadProcessId(window, ctypes.byref(owner))
|
||||
text = ctypes.create_unicode_buffer(256)
|
||||
user.GetWindowTextW(window, text, len(text))
|
||||
if owner.value == pid and text.value == title:
|
||||
found.append(window)
|
||||
return True
|
||||
|
||||
user.EnumWindows(visit, 0)
|
||||
assert len(found) <= 1, f'Multiple native windows titled {title}'
|
||||
return found[0] if found else None
|
||||
|
||||
|
||||
def window_text(window):
|
||||
# Only a numeric, locally obtained HWND enters this fixed PowerShell query.
|
||||
script = f"""
|
||||
[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false)
|
||||
Add-Type -AssemblyName UIAutomationClient
|
||||
Add-Type -AssemblyName UIAutomationTypes
|
||||
$root=[System.Windows.Automation.AutomationElement]::FromHandle([IntPtr]{int(window)})
|
||||
$nodes=$root.FindAll([System.Windows.Automation.TreeScope]::Descendants,[System.Windows.Automation.Condition]::TrueCondition)
|
||||
ConvertTo-Json -Compress -InputObject @($nodes | ForEach-Object {{$_.Current.Name}})
|
||||
"""
|
||||
result = subprocess.run(['pwsh', '-NoProfile', '-NonInteractive', '-Command', script],
|
||||
encoding='utf-8', errors='replace', capture_output=True,
|
||||
timeout=15, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
assert result.returncode == 0, result.stderr
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def check_launch(executable, page_name='diff.html', seconds=30):
|
||||
executable = Path(executable).resolve()
|
||||
title = 'OpenWrt Diff Studio' if page_name == 'diff.html' else 'OpenWrt Patch Updater'
|
||||
startup = subprocess.STARTUPINFO()
|
||||
startup.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
||||
startup.wShowWindow = 4 # Render the real interactive window without stealing focus.
|
||||
with tempfile.TemporaryFile() as errors, tempfile.TemporaryFile() as output:
|
||||
process = subprocess.Popen([str(executable)], cwd=executable.parent,
|
||||
env=dict(os.environ, RUST_BACKTRACE='1'),
|
||||
startupinfo=startup, stderr=errors, stdout=output)
|
||||
window = None
|
||||
try:
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
assert process.poll() is None, f'Exited at startup: {process.returncode}'
|
||||
window = window_handle(process.pid, title)
|
||||
if window:
|
||||
names = window_text(window)
|
||||
if page_name == 'diff.html':
|
||||
ready = names.count('选择 ZIP 文件') == 2 or names.count('Select ZIP file') == 2
|
||||
else:
|
||||
ready = any('mu300-r2' in text for text in names)
|
||||
if ready:
|
||||
break
|
||||
if time.monotonic() > deadline:
|
||||
raise AssertionError(f'Expected page never rendered: {title}; accessibility={names if window else []}')
|
||||
time.sleep(.5)
|
||||
print(f'Loaded {title}: real frontend' + (' and backend manifest' if page_name == 'ota.html' else ''), flush=True)
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
assert process.poll() is None, f'Window crashed: {process.returncode}'
|
||||
time.sleep(.5)
|
||||
assert title in window_text(window), 'Rendered frontend disappeared'
|
||||
user = ctypes.windll.user32
|
||||
user.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
|
||||
assert user.PostMessageW(window, 0x0010, 0, 0), 'WM_CLOSE failed'
|
||||
process.wait(timeout=10)
|
||||
assert process.returncode == 0, f'Abnormal close: {process.returncode}'
|
||||
print(f'PASS {executable.name}: alive {seconds}s, clean close', flush=True)
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
if window:
|
||||
ctypes.windll.user32.PostMessageW(window, 0x0010, 0, 0)
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.terminate()
|
||||
else:
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
errors.seek(0)
|
||||
stderr = errors.read().decode('utf-8', 'replace')
|
||||
assert 'panicked' not in stderr, stderr
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('executable', type=Path)
|
||||
parser.add_argument('--page', default='diff.html', choices=['diff.html', 'ota.html'])
|
||||
parser.add_argument('--seconds', type=int, default=30)
|
||||
args = parser.parse_args()
|
||||
check_launch(args.executable, args.page, args.seconds)
|
||||
@@ -0,0 +1,388 @@
|
||||
"""OTA correctness/security tests. Real filesystem mutations run only in temp roots."""
|
||||
from contextlib import contextmanager
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
import importlib.util
|
||||
from unittest.mock import patch as mock
|
||||
import zipfile
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from backend.ota_engine import FORMAT, Engine, Patch, canonical, descriptor, protected, validate_manifest
|
||||
from backend.ota_package import analyze, Release
|
||||
|
||||
|
||||
def file(data=b'old', mode=0o644):
|
||||
return dict(kind='file', mode=mode, uid=0, gid=0, size=len(data),
|
||||
sha256=hashlib.sha256(data).hexdigest(), xattrs={})
|
||||
|
||||
|
||||
def manifest(ops=None):
|
||||
return dict(format=FORMAT, family='e5', profile='e5', base_version='e5-r1', target_version='e5-r2',
|
||||
kernel_release='6.18.54-e5-test', operations=ops or [dict(path='usr/lib/test', before=file(), after=file(b'new'))])
|
||||
|
||||
|
||||
def package(path, m=None, blobs=None, extra=None):
|
||||
m = m or manifest()
|
||||
blobs = blobs or {hashlib.sha256(b'new').hexdigest(): b'new'}
|
||||
with zipfile.ZipFile(path, 'w', compression=zipfile.ZIP_DEFLATED) as z:
|
||||
z.writestr('manifest.json', canonical(m))
|
||||
for h, data in blobs.items():
|
||||
z.writestr('blobs/' + h, data)
|
||||
for name, data in (extra or {}).items():
|
||||
z.writestr(name, data)
|
||||
return path
|
||||
|
||||
|
||||
def mu_release(root, version, files=None, boot=b'boot'):
|
||||
(root / 'desktop').mkdir(parents=True)
|
||||
(root / 'payload').mkdir()
|
||||
files = files or {'usr/lib/test': b'old'}
|
||||
with tarfile.open(root / 'payload/mu300-openwrt.tar.gz', 'w:gz') as tar:
|
||||
for name in ('usr', 'usr/lib', 'etc', 'etc/config'):
|
||||
t = tarfile.TarInfo(name); t.type=tarfile.DIRTYPE; t.mode=0o755
|
||||
tar.addfile(t)
|
||||
for name, data in files.items():
|
||||
t = tarfile.TarInfo(name);t.size=len(data);t.mode=0o644
|
||||
tar.addfile(t, io.BytesIO(data))
|
||||
(root / 'payload/boot-linux.img').write_bytes(boot)
|
||||
names = ('payload/boot-linux.img', 'payload/mu300-openwrt.tar.gz')
|
||||
checks = {n:hashlib.sha256((root / n).read_bytes()).hexdigest() for n in names}
|
||||
(root / 'desktop/manifest.json').write_text(json.dumps(dict(magisk=checks, desktop={}, magisk_layout={
|
||||
'boot-linux.img':names[0], 'mu300-openwrt.tar.gz':names[1]})))
|
||||
(root / 'desktop/release.json').write_text(json.dumps(dict(image_version=version, profile='mu300',
|
||||
kernel_release='7.2.8', openwrt='25.12.5')))
|
||||
|
||||
|
||||
class FormatTests(unittest.TestCase):
|
||||
def test_protected_state(self):
|
||||
for path in ('etc/config/wireless','etc/shadow','lib/firmware/modem.bin','etc/e5/release.json',
|
||||
'var/traffic.db','root/file','lib/apk/db/installed','usr/lib/unisoc-ota/engine.py'):
|
||||
self.assertTrue(protected(path), path)
|
||||
self.assertFalse(protected('usr/libexec/unisoc-modem/action'))
|
||||
self.assertFalse(protected('etc/init.d/e5-modemd'))
|
||||
self.assertFalse(protected('www/luci-static/resources/view/mu300/locks.js'))
|
||||
self.assertTrue(protected('lib/modules/current/wifi.ko'))
|
||||
|
||||
def test_path_traversal(self):
|
||||
for name in ('../etc/shadow','/etc/shadow','usr//lib/x','usr/./a','usr/a/../x','usr\\lib\\x','usr/x\0y'):
|
||||
m=manifest();m['operations'][0]['path']=name
|
||||
with self.assertRaises(ValueError):validate_manifest(m)
|
||||
|
||||
def test_duplicate_operation(self):
|
||||
m=manifest();m['operations']*=2
|
||||
with self.assertRaises(ValueError):validate_manifest(m)
|
||||
|
||||
def test_type_change(self):
|
||||
m=manifest();m['operations'][0]['after']=dict(kind='symlink',mode=0o777,uid=0,gid=0,target='/tmp',xattrs={})
|
||||
with self.assertRaises(ValueError):validate_manifest(m)
|
||||
|
||||
def test_directory_removal(self):
|
||||
m=manifest();m['operations'][0].update(before=dict(kind='dir',mode=0o755,uid=0,gid=0,xattrs={}),after=None)
|
||||
with self.assertRaises(ValueError):validate_manifest(m)
|
||||
|
||||
def test_extra_archive_program_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p=package(Path(d)/'p.ota',extra={'install.sh':b'rm -rf /'})
|
||||
with self.assertRaises(ValueError):Patch(p)
|
||||
|
||||
def test_checksum_mismatch(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p=package(Path(d)/'p.ota',blobs={file(b'new')['sha256']:b'bad'})
|
||||
with self.assertRaises(ValueError):Patch(p)
|
||||
|
||||
def test_trailing_duplicate_zip_entry(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p=package(Path(d)/'p.ota')
|
||||
with zipfile.ZipFile(p,'a') as z:z.writestr('manifest.json',canonical(manifest()))
|
||||
with self.assertRaises(ValueError):Patch(p)
|
||||
|
||||
def test_partial_kernel_update_rejected(self):
|
||||
m=manifest();m['boot']={'sha256':'a'*64}
|
||||
with self.assertRaises(ValueError):validate_manifest(m)
|
||||
|
||||
|
||||
class GenerationTests(unittest.TestCase):
|
||||
@unittest.skipUnless(os.name=='posix','Linux release staging permissions')
|
||||
def test_stage_built_in_plugin_and_preserve_state(self):
|
||||
import runpy
|
||||
repo=Path(__file__).resolve().parents[2]
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
root=Path(d);(root/'etc/unisoc-ota').mkdir(parents=True)
|
||||
(root/'etc/unisoc-ota/current.json').write_text('preserve existing state')
|
||||
runpy.run_path(str(repo/'installer/stage-ota.py'))['stage'](root)
|
||||
self.assertEqual((root/'etc/unisoc-ota/current.json').read_text(),'preserve existing state')
|
||||
source=repo/'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota/engine.py'
|
||||
self.assertEqual((root/'usr/lib/unisoc-ota/engine.py').read_bytes(),source.read_bytes().replace(b'\r\n',b'\n'))
|
||||
self.assertTrue((root/'etc/rc.d/S06unisoc-ota').is_symlink())
|
||||
self.assertTrue((root/'etc/init.d/unisoc-ota').stat().st_mode & stat.S_IXUSR)
|
||||
acl=json.loads((root/'usr/share/rpcd/acl.d/unisoc-ota.json').read_text())
|
||||
self.assertNotIn('exec',acl['luci-app-unisoc-ota']['write']['ubus'])
|
||||
|
||||
def test_web_assets_are_hotfixable_but_core_runtime_is_not(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
d=Path(d)
|
||||
mu_release(d/'a','mu300-r1',{'www/style.css':b'old'})
|
||||
mu_release(d/'b','mu300-r2',{'www/style.css':b'new'})
|
||||
result=analyze(d/'a',d/'b')
|
||||
self.assertTrue(result['can_export'])
|
||||
self.assertEqual(result['manifest']['operations'][0]['path'],'www/style.css')
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
d=Path(d)
|
||||
mu_release(d/'a','mu300-r1',{'bin/busybox':b'old'})
|
||||
mu_release(d/'b','mu300-r2',{'bin/busybox':b'new'})
|
||||
result=analyze(d/'a',d/'b')
|
||||
self.assertFalse(result['can_export'])
|
||||
def test_native_tool_refresh_verifies_owned_files(self):
|
||||
installer=Path(__file__).resolve().parents[1]
|
||||
spec=importlib.util.spec_from_file_location('ota_builder_test',installer/'build-ota.py')
|
||||
builder=importlib.util.module_from_spec(spec);spec.loader.exec_module(builder)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
d=Path(d);artifact=d/'artifact';(artifact/'tools/backend').mkdir(parents=True)
|
||||
(artifact/'tools/backend/openwrt-backend.exe').write_bytes(b'backend')
|
||||
(artifact/'OpenWrt-Installer.exe').write_bytes(b'gui')
|
||||
output=d/'tool'
|
||||
argv=['build-ota.py','--artifact',str(artifact),'--output',str(output)]
|
||||
with mock.object(builder,'native_platform',return_value='windows-x64'),mock.object(builder,'validate_artifact'),mock.object(builder,'sources',return_value={'fixture':'hash'}):
|
||||
with mock.object(sys,'argv',argv):builder.main()
|
||||
m=json.loads((output/'diff-tool.json').read_text())
|
||||
self.assertNotIn('diff-tool.json',m['files'])
|
||||
with mock.object(sys,'argv',argv+['--refresh']):builder.main()
|
||||
m=json.loads((output/'diff-tool.json').read_text())
|
||||
self.assertNotIn('diff-tool.json',m['files'])
|
||||
(output/'personal.txt').write_text('keep me')
|
||||
with mock.object(sys,'argv',argv+['--refresh']):
|
||||
with self.assertRaises(ValueError):builder.main()
|
||||
self.assertEqual((output/'personal.txt').read_text(),'keep me')
|
||||
|
||||
def test_package_abi_change_blocks_export(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
d=Path(d)
|
||||
for n in (1,2):
|
||||
db=f'P:libc\nV:{n}\nA:aarch64\nD:\n\n'.encode()
|
||||
mu_release(d/str(n),'mu300-r'+str(n),{'usr/lib/test':str(n).encode(),'lib/apk/db/installed':db})
|
||||
result=analyze(d/'1',d/'2')
|
||||
self.assertFalse(result['can_export'])
|
||||
self.assertTrue(any('ABI' in b for b in result['blockers']))
|
||||
|
||||
def test_generate_tar_release_preserves_configs_deduplicates(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
d=Path(d);a=d/'old';b=d/'new'
|
||||
mu_release(a,'mu300-r1', {'usr/lib/test':b'old','etc/config/wireless':b'old'})
|
||||
mu_release(b,'mu300-r2', {'usr/lib/test':b'new','usr/lib/alias':b'new','etc/config/wireless':b'new'})
|
||||
p=d/'p.ota';result=analyze(a,b,p)
|
||||
self.assertTrue(result['can_export'])
|
||||
self.assertEqual(result['files'],2)
|
||||
self.assertEqual(result['payload_bytes'],3)
|
||||
self.assertIn('etc/config/wireless',result['manifest']['preserved'])
|
||||
with Patch(p) as patch:self.assertEqual(len(patch.archive.namelist()),2)
|
||||
|
||||
def test_zip_inputs_supported(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
d=Path(d);archives=[]
|
||||
for i in (1,2):
|
||||
root=d/str(i);mu_release(root,'mu300-r'+str(i),{'usr/lib/test':str(i).encode()})
|
||||
z=d/(str(i)+'.zip');archives.append(z)
|
||||
with zipfile.ZipFile(z,'w') as out:
|
||||
for p in root.rglob('*'):
|
||||
if p.is_file():out.write(p,'release/'+p.relative_to(root).as_posix())
|
||||
self.assertTrue(analyze(*archives)['can_export'])
|
||||
|
||||
def test_kernel_change_blocks_export(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
d=Path(d);mu_release(d/'a','mu300-r1');mu_release(d/'b','mu300-r2',{'usr/lib/test':b'new'},boot=b'newboot')
|
||||
result=analyze(d/'a',d/'b')
|
||||
self.assertFalse(result['can_export'])
|
||||
with self.assertRaises(ValueError):analyze(d/'a',d/'b',d/'p.ota')
|
||||
self.assertFalse((d/'p.ota').exists())
|
||||
|
||||
def test_corrupt_full_release_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
d=Path(d);mu_release(d/'a','mu300-r1');(d/'a/payload/boot-linux.img').write_bytes(b'bad')
|
||||
with self.assertRaises(ValueError):
|
||||
with Release(d/'a'):pass
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == 'linux', 'Device engine requires Linux permissions, xattrs and durable rename semantics')
|
||||
class EngineTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
|
||||
self.root=Path(self.tmp.name);(self.root/'usr/lib').mkdir(parents=True)
|
||||
(self.root/'usr/lib/test').write_bytes(b'old')
|
||||
(self.root/'usr/lib/test').chmod(0o644)
|
||||
(self.root/'etc/e5').mkdir(parents=True)
|
||||
(self.root/'etc/e5/release.json').write_text(json.dumps(dict(profile='e5',image_version='e5-r1',kernel_release='6.18.54-e5-test')))
|
||||
self.e=Engine(self.root)
|
||||
self.m=manifest();self.m['operations'][0]['before']=descriptor(self.root/'usr/lib/test')
|
||||
self.m['operations'][0]['after'].update(uid=os.getuid(),gid=os.getgid())
|
||||
self.p=package(self.root/'p.ota',self.m)
|
||||
|
||||
def test_apply_preserves_plugins_and_user_data(self):
|
||||
(self.root/'usr/lib/extra-plugin').write_bytes(b'keep')
|
||||
(self.root/'etc/config').mkdir();(self.root/'etc/config/network').write_bytes(b'user')
|
||||
with Patch(self.p) as patch:result=self.e.apply(patch)
|
||||
self.assertEqual(result['status'],'complete')
|
||||
self.assertEqual((self.root/'usr/lib/test').read_bytes(),b'new')
|
||||
self.assertEqual((self.root/'usr/lib/extra-plugin').read_bytes(),b'keep')
|
||||
self.assertEqual((self.root/'etc/config/network').read_bytes(),b'user')
|
||||
self.assertEqual(self.e.identity()['version'],'e5-r2')
|
||||
|
||||
def test_conflict_does_not_mutate(self):
|
||||
(self.root/'usr/lib/test').write_bytes(b'custom')
|
||||
with Patch(self.p) as patch:
|
||||
self.assertFalse(self.e.inspect(patch)['applicable'])
|
||||
with self.assertRaises(ValueError):self.e.apply(patch)
|
||||
self.assertEqual((self.root/'usr/lib/test').read_bytes(),b'custom')
|
||||
self.assertFalse((self.e.state/'journal.json').exists())
|
||||
|
||||
def test_wrong_device_base(self):
|
||||
self.m['profile']='m8';package(self.p,self.m)
|
||||
with Patch(self.p) as patch:
|
||||
with self.assertRaises(ValueError):self.e.inspect(patch)
|
||||
|
||||
def test_package_dependency_mismatch_no_write(self):
|
||||
self.m['base_packages']={'libc':{'V':'1','A':'aarch64','D':''}}
|
||||
package(self.p,self.m)
|
||||
with Patch(self.p) as patch:
|
||||
self.assertEqual(self.e.inspect(patch)['package_conflicts'],['libc'])
|
||||
with self.assertRaises(ValueError):self.e.apply(patch)
|
||||
self.assertEqual((self.root/'usr/lib/test').read_bytes(),b'old')
|
||||
|
||||
def test_manual_rollback(self):
|
||||
with Patch(self.p) as patch:self.e.apply(patch)
|
||||
engine=Path(__file__).resolve().parents[2]/'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota/engine.py'
|
||||
result=subprocess.run([sys.executable,str(engine),'rollback','--root',str(self.root)],capture_output=True,text=True)
|
||||
self.assertEqual(result.returncode,0,result.stdout+result.stderr)
|
||||
self.assertEqual((self.root/'usr/lib/test').read_bytes(),b'old')
|
||||
self.assertEqual(self.e.identity()['version'],'e5-r1')
|
||||
|
||||
def test_rollback_conflict_does_not_clobber_local_changes(self):
|
||||
with Patch(self.p) as patch:self.e.apply(patch)
|
||||
(self.root/'usr/lib/test').write_bytes(b'local edit')
|
||||
engine=Path(__file__).resolve().parents[2]/'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota/engine.py'
|
||||
result=subprocess.run([sys.executable,str(engine),'rollback','--root',str(self.root)],capture_output=True,text=True)
|
||||
self.assertNotEqual(result.returncode,0)
|
||||
self.assertEqual((self.root/'usr/lib/test').read_bytes(),b'local edit')
|
||||
|
||||
def test_rpc_upload_lock_and_arbitrary_paths(self):
|
||||
import importlib.util
|
||||
import fcntl
|
||||
directory=Path(__file__).resolve().parents[2]/'openwrt/luci-app-unisoc-ota/root/usr/lib/unisoc-ota'
|
||||
sys.path.insert(0,str(directory));self.addCleanup(lambda:sys.path.remove(str(directory)))
|
||||
spec=importlib.util.spec_from_file_location('ota_test_rpc',directory/'rpc.py')
|
||||
rpc=importlib.util.module_from_spec(spec);spec.loader.exec_module(rpc)
|
||||
self.e.state.mkdir(parents=True)
|
||||
rpc.STATE=self.e.state;rpc.UPLOAD=self.e.state/'upload.ota';rpc.JOB=self.e.state/'job.json';rpc.Engine=lambda:self.e
|
||||
rpc.UPLOAD.write_bytes(self.p.read_bytes())
|
||||
with Patch(self.p) as patch:review_id=patch.id
|
||||
with self.assertRaises(ValueError):rpc.dispatch('start','/tmp/other.ota')
|
||||
with (self.e.state/'job.lock').open('a') as lock:
|
||||
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
with self.assertRaises(BlockingIOError):rpc.dispatch('start',review_id=review_id)
|
||||
self.assertTrue(rpc.UPLOAD.exists())
|
||||
with mock.object(rpc.subprocess,'Popen') as launch:
|
||||
self.assertEqual(rpc.dispatch('start',review_id=review_id)['status'],'running')
|
||||
self.assertTrue(launch.call_args.kwargs['start_new_session'])
|
||||
self.assertTrue(launch.call_args.kwargs['pass_fds'])
|
||||
self.assertFalse(rpc.UPLOAD.exists())
|
||||
other=copy.deepcopy(self.m);other['target_version']='e5-r3'
|
||||
package(rpc.UPLOAD,other)
|
||||
with mock.object(rpc.subprocess,'Popen') as launch:
|
||||
with self.assertRaisesRegex(ValueError,'reviewed'):
|
||||
rpc.dispatch('start',review_id=review_id)
|
||||
launch.assert_not_called()
|
||||
self.assertTrue(rpc.UPLOAD.exists())
|
||||
|
||||
def test_recovery_cleans_partial_temp_file(self):
|
||||
with Patch(self.p) as patch:
|
||||
def failure(*args):
|
||||
(self.root/'usr/lib/.test.unisoc-ota-new').write_bytes(b'partial')
|
||||
raise RuntimeError('write failed')
|
||||
original=self.e.install_descriptor
|
||||
count=0
|
||||
def once(*args,**kwargs):
|
||||
nonlocal count
|
||||
count+=1
|
||||
return failure(*args) if count==1 else original(*args,**kwargs)
|
||||
self.e.install_descriptor=once
|
||||
with self.assertRaises(RuntimeError):self.e.apply(patch)
|
||||
self.assertFalse((self.root/'usr/lib/.test.unisoc-ota-new').exists())
|
||||
self.assertEqual((self.root/'usr/lib/test').read_bytes(),b'old')
|
||||
|
||||
def test_deleted_file_can_be_restored(self):
|
||||
self.m['operations'][0]['after']=None;package(self.p,self.m,blobs={})
|
||||
# No blobs are expected for a deletion-only hotfix.
|
||||
with zipfile.ZipFile(self.p,'w') as z:z.writestr('manifest.json',canonical(self.m))
|
||||
with Patch(self.p) as patch:self.e.apply(patch)
|
||||
self.assertFalse((self.root/'usr/lib/test').exists())
|
||||
data=json.loads((self.e.state/'journal.json').read_text());data['status']='rolling_back'
|
||||
from backend.ota_engine import atomic_json
|
||||
atomic_json(self.e.state/'journal.json',data)
|
||||
with self.e.lock():self.e.recover()
|
||||
self.assertEqual((self.root/'usr/lib/test').read_bytes(),b'old')
|
||||
|
||||
def test_symlink_parent_refused(self):
|
||||
(self.root/'usr/alias').symlink_to('lib')
|
||||
self.m['operations'][0]['path']='usr/alias/test';package(self.p,self.m)
|
||||
with Patch(self.p) as patch:
|
||||
with self.assertRaises(ValueError):self.e.inspect(patch)
|
||||
|
||||
def test_apply_failure_rolls_back(self):
|
||||
def fail(*args):raise RuntimeError('simulated service failure')
|
||||
with Patch(self.p) as patch:
|
||||
with self.assertRaises(RuntimeError):self.e.apply(patch,fail)
|
||||
self.assertEqual((self.root/'usr/lib/test').read_bytes(),b'old')
|
||||
self.assertEqual(self.e.identity()['version'],'e5-r1')
|
||||
self.assertEqual(self.e.status()['transaction']['status'],'rolled_back')
|
||||
|
||||
def test_interrupted_write_recovers_on_new_process(self):
|
||||
with Patch(self.p) as patch:
|
||||
original=self.e.install_descriptor
|
||||
def powercut(*args,**kwargs):
|
||||
original(*args,**kwargs)
|
||||
os._exit(77)
|
||||
pid=os.fork()
|
||||
if pid==0:
|
||||
self.e.install_descriptor=powercut
|
||||
self.e.apply(patch)
|
||||
os._exit(0)
|
||||
_,s=os.waitpid(pid,0);self.assertEqual(os.waitstatus_to_exitcode(s),77)
|
||||
self.assertEqual((self.root/'usr/lib/test').read_bytes(),b'new')
|
||||
with self.e.lock():self.e.recover()
|
||||
self.assertEqual((self.root/'usr/lib/test').read_bytes(),b'old')
|
||||
self.assertEqual(self.e.identity()['version'],'e5-r1')
|
||||
|
||||
def test_duplicate_apply_rejected(self):
|
||||
with Patch(self.p) as patch:
|
||||
self.e.apply(patch)
|
||||
with self.assertRaises(ValueError):self.e.apply(patch)
|
||||
|
||||
def test_no_space_no_writes(self):
|
||||
class Disk:free=0
|
||||
with mock('backend.ota_engine.shutil.disk_usage',return_value=Disk()),Patch(self.p) as patch:
|
||||
with self.assertRaises(ValueError):self.e.apply(patch)
|
||||
self.assertEqual((self.root/'usr/lib/test').read_bytes(),b'old')
|
||||
|
||||
def test_new_directories_removed_on_rollback(self):
|
||||
directory=dict(kind='dir',mode=0o755,uid=os.getuid(),gid=os.getgid(),xattrs={})
|
||||
self.m['operations'].insert(0,dict(path='usr/new',before=None,after=directory))
|
||||
self.m['operations'].append(dict(path='usr/new/x',before=None,after=file(b'new')))
|
||||
for o in self.m['operations']:
|
||||
if o['after']:o['after'].update(uid=os.getuid(),gid=os.getgid())
|
||||
package(self.p,self.m)
|
||||
with Patch(self.p) as patch:
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.e.apply(patch,lambda a,b,c: (_ for _ in ()).throw(RuntimeError('failure')) if a==3 else None)
|
||||
self.assertFalse((self.root/'usr/new').exists())
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Use a real small ext4 image; no device, root mounts or full rootfs copies."""
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
from backend.ota_package import analyze
|
||||
from backend.ota_engine import Patch
|
||||
|
||||
|
||||
class Ext4Tests(unittest.TestCase):
|
||||
def test_e5_ext4_and_symlink_reader(self):
|
||||
if os.name == 'nt':
|
||||
try:
|
||||
available = subprocess.run(['wsl', '-d', 'Ubuntu-22.04', '--', 'true'],
|
||||
capture_output=True, timeout=10).returncode == 0
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
available = False
|
||||
if not available:
|
||||
self.skipTest('Creating the Windows ext4 test fixture requires Ubuntu-22.04 in WSL')
|
||||
elif not shutil.which('mke2fs'):
|
||||
self.skipTest('Creating the ext4 test fixture requires mke2fs')
|
||||
repo=Path(__file__).resolve().parents[2]
|
||||
(repo/'work').mkdir(exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='ota-test-',dir=repo/'work') as d:
|
||||
d=Path(d)
|
||||
for i in (1,2):
|
||||
release=d/str(i);source=release/'root';(source/'usr/lib').mkdir(parents=True)
|
||||
(source/'etc/config').mkdir(parents=True)
|
||||
(source/'usr/lib/example').write_bytes(('version '+str(i)).encode())
|
||||
(source/'etc/config/network').write_bytes(('user '+str(i)).encode())
|
||||
image=release/'root.ext4'
|
||||
linux=lambda p:'/mnt/'+p.drive[0].lower()+p.as_posix()[2:]
|
||||
if os.name == 'nt':
|
||||
subprocess.run(['wsl','-d','Ubuntu-22.04','--','ln','-s','example',linux(source/'usr/lib/link')],check=True,capture_output=True)
|
||||
command = ['wsl','-d','Ubuntu-22.04','--','mke2fs','-q','-t','ext4','-F','-d',linux(source),linux(image),'16M']
|
||||
else:
|
||||
(source/'usr/lib/link').symlink_to('example')
|
||||
command = ['mke2fs','-q','-t','ext4','-F','-d',str(source),str(image),'16M']
|
||||
subprocess.run(command,check=True,capture_output=True)
|
||||
files=release/'files';files.mkdir()
|
||||
with image.open('rb') as src,gzip.open(files/'openwrt.ext4.gz','wb') as dest:shutil.copyfileobj(src,dest)
|
||||
image.unlink()
|
||||
(files/'boot.img').write_bytes(b'same boot')
|
||||
(files/'device-profile.json').write_text(json.dumps({'profile':'e5'}))
|
||||
(files/'RELEASE.json').write_text(json.dumps(dict(profile='e5',image_version='e5-r'+str(i),kernel_release='6.18.54-e5-test',openwrt='25.12.5')))
|
||||
(files/'SHA256SUMS').write_text(''.join(hashlib.sha256((files/n).read_bytes()).hexdigest()+' files/'+n+'\n' for n in ('boot.img','openwrt.ext4.gz')))
|
||||
out=d/'patch.ota';result=analyze(d/'1',d/'2',out)
|
||||
self.assertTrue(result['can_export'],result['blockers'])
|
||||
self.assertEqual([o['path'] for o in result['manifest']['operations']],['usr/lib/example'])
|
||||
with Patch(out) as patch:
|
||||
h=result['manifest']['operations'][0]['after']['sha256']
|
||||
self.assertEqual(patch.archive.read('blobs/'+h),b'version 2')
|
||||
self.assertFalse(any(p.name.startswith('tmp') for p in d.rglob('*')))
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>OpenWrt Diff Studio</title></head><body><div id="root"></div><script type="module" src="/src/ota.tsx"></script></body></html>
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>OpenWrt Patch Updater</title></head><body><div id="root"></div><script type="module" src="/src/ota.tsx"></script></body></html>
|
||||
@@ -6,7 +6,7 @@ use std::{collections::HashMap, io::{BufRead, BufReader, Write}, path::PathBuf,
|
||||
use tauri::{Emitter, Manager, State};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
const COMMANDS: &[&str] = &["hello","snapshot","list","package","devices","adb_connect","adb_disconnect","probe","probe_update","plan","start","resume","retry","cancel","can_close","export","import","diagnostics","verify_openwrt"];
|
||||
const COMMANDS: &[&str] = &["hello","snapshot","list","package","devices","adb_connect","adb_disconnect","probe","probe_update","plan","start","resume","retry","cancel","can_close","export","import","diagnostics","verify_openwrt","ota_analyze","ota_export","ota_package","ota_probe","ota_apply","ota_status"];
|
||||
struct Bridge {
|
||||
input: Mutex<Option<ChildStdin>>,
|
||||
pending: Mutex<HashMap<u64, oneshot::Sender<Result<Value, String>>>>,
|
||||
@@ -40,6 +40,14 @@ async fn pick_package() -> Option<String> {
|
||||
tauri::async_runtime::spawn_blocking(|| rfd::FileDialog::new().set_title("OpenWrt package / 安装包目录").pick_folder().map(|p|p.to_string_lossy().to_string())).await.ok().flatten()
|
||||
}
|
||||
#[tauri::command]
|
||||
async fn pick_ota_input() -> Option<String> {
|
||||
tauri::async_runtime::spawn_blocking(|| rfd::FileDialog::new().set_title("Select release ZIP or OTA / 选择发行包或差异包").add_filter("OpenWrt packages", &["zip","ota"]).pick_file().map(|p|p.to_string_lossy().to_string())).await.ok().flatten()
|
||||
}
|
||||
#[tauri::command]
|
||||
async fn save_ota() -> Option<String> {
|
||||
tauri::async_runtime::spawn_blocking(|| rfd::FileDialog::new().set_file_name("OpenWrt-patch.zip").add_filter("Desktop + Web", &["zip"]).add_filter("Web OTA only", &["ota"]).save_file().map(|p|p.to_string_lossy().to_string())).await.ok().flatten()
|
||||
}
|
||||
#[tauri::command]
|
||||
async fn pick_recovery() -> Option<String> {
|
||||
tauri::async_runtime::spawn_blocking(|| rfd::FileDialog::new().set_title("Recovery folder / 完整事务与备份目录").pick_folder().map(|p|p.to_string_lossy().to_string())).await.ok().flatten()
|
||||
}
|
||||
@@ -99,7 +107,8 @@ fn distribution_root(executable: &std::path::Path) -> Result<PathBuf, String> {
|
||||
if ancestor.extension().is_some_and(|ext| ext == "app") {
|
||||
let root = ancestor.parent().ok_or("Application has no parent directory")?;
|
||||
if root.join("OpenWrt-Installer.py").is_file()
|
||||
&& (root.join("desktop/manifest.json").is_file() || root.join("files/device-profile.json").is_file()) {
|
||||
&& (root.join("desktop/manifest.json").is_file() || root.join("files/device-profile.json").is_file())
|
||||
|| root.join("OpenWrt-Diff-Studio.py").is_file() || root.join("update.ota").is_file() {
|
||||
return Ok(root.to_path_buf());
|
||||
}
|
||||
// Finder may translocate quarantined applications. Ask for the
|
||||
@@ -111,15 +120,43 @@ fn distribution_root(executable: &std::path::Path) -> Result<PathBuf, String> {
|
||||
executable.parent().map(|p|p.to_path_buf()).ok_or_else(|| "Executable has no directory".into())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
fn entry_page(executable: &std::path::Path, has_patch: bool) -> (&'static str, &'static str) {
|
||||
// Exported macOS updaters retain the studio's internal executable name.
|
||||
// Their enclosing app bundle is the public entry point instead.
|
||||
let entry = executable.ancestors().find(|p| p.extension().is_some_and(|ext| ext == "app"))
|
||||
.unwrap_or(executable).file_stem().unwrap_or_default().to_string_lossy().to_lowercase();
|
||||
if entry.contains("updater") {
|
||||
("ota.html", "OpenWrt Patch Updater")
|
||||
} else if entry.contains("diff") {
|
||||
("diff.html", "OpenWrt Diff Studio")
|
||||
} else if has_patch {
|
||||
("ota.html", "OpenWrt Patch Updater")
|
||||
} else {
|
||||
("index.html", "OpenWrt Installer")
|
||||
}
|
||||
}
|
||||
|
||||
fn configure_entry(config: &mut tauri::Config, executable: &std::path::Path, has_patch: bool) {
|
||||
let (page, title) = entry_page(executable, has_patch);
|
||||
if let Some(window) = config.app.windows.iter_mut().find(|window| window.label == "main") {
|
||||
// Choose the asset before webview creation. During setup the webview
|
||||
// can still be about:blank, which cannot resolve relative URLs.
|
||||
window.url = tauri::WebviewUrl::App(PathBuf::from(page));
|
||||
window.title = title.into();
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let executable = std::env::current_exe()?;
|
||||
let root = distribution_root(&executable).map_err(std::io::Error::other)?;
|
||||
let mut context = tauri::generate_context!();
|
||||
configure_entry(context.config_mut(), &executable, root.join("update.ota").is_file());
|
||||
let directory = data_directory();
|
||||
let bridge = Arc::new(Bridge {input:Mutex::new(None),pending:Mutex::new(HashMap::new()),sequence:AtomicU64::new(1),busy:AtomicBool::new(false),directory,export_log:Mutex::new(None)});
|
||||
let setup_state = bridge.clone();
|
||||
let app = tauri::Builder::default().manage(bridge.clone())
|
||||
.invoke_handler(tauri::generate_handler![backend_request,pick_package,pick_recovery,save_backup,save_log,write_log,open_data,open_repository])
|
||||
.invoke_handler(tauri::generate_handler![backend_request,pick_package,pick_ota_input,save_ota,pick_recovery,save_backup,save_log,write_log,open_data,open_repository])
|
||||
.setup(move |app| {
|
||||
let executable = std::env::current_exe()?;
|
||||
let root = distribution_root(&executable).map_err(std::io::Error::other)?;
|
||||
#[cfg(target_os = "macos")]
|
||||
let backend = "tools/macos/backend/openwrt-backend";
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
@@ -146,6 +183,9 @@ fn main() {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if event["type"] == "ota_activity" {
|
||||
state.busy.store(event["data"]["busy"].as_bool().unwrap_or(false), Ordering::SeqCst);
|
||||
}
|
||||
if event["type"] == "transaction" {
|
||||
let status = event["data"]["status"].as_str().unwrap_or("");
|
||||
state.busy.store(matches!(status,"running"|"waiting_user"|"waiting_device"),Ordering::SeqCst);
|
||||
@@ -173,17 +213,52 @@ fn main() {
|
||||
let _ = window.emit("backend",json!({"type":"close_blocked","data":{}}));
|
||||
}
|
||||
}
|
||||
}).build(tauri::generate_context!());
|
||||
match app {
|
||||
Ok(app) => app.run(move |_, event| {
|
||||
if matches!(event,tauri::RunEvent::Exit) {bridge.input.lock().unwrap().take();}
|
||||
}),
|
||||
Err(error) => {
|
||||
}).build(context)?;
|
||||
app.run(move |_, event| {
|
||||
if matches!(event,tauri::RunEvent::Exit) {bridge.input.lock().unwrap().take();}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = run() {
|
||||
#[cfg(target_os = "macos")]
|
||||
let message = format!("Cannot start OpenWrt Installer. Keep the app beside tools and files in the extracted package.\n无法启动安装器,请将 app 与 tools、files 一起保留在完整解压目录。\n\n{error}");
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let message = format!("Cannot start the system WebView2. Install Microsoft Edge WebView2 Evergreen Runtime and reopen the installer.\n无法启动系统 WebView2。请安装 Microsoft Edge WebView2 Evergreen Runtime 后重试。\nhttps://developer.microsoft.com/microsoft-edge/webview2/\n\n{error}");
|
||||
let message = format!("Cannot start OpenWrt Installer. Keep the complete extracted package together and check that Microsoft Edge WebView2 Runtime is installed.\n无法启动程序。请保留完整解压目录,并检查是否已安装 Microsoft Edge WebView2 Runtime。\n\n{error}");
|
||||
rfd::MessageDialog::new().set_title("OpenWrt Installer").set_description(message).set_level(rfd::MessageLevel::Error).show();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn public_entry_selects_page() {
|
||||
for (path, patch, expected) in [
|
||||
("/tools/OpenWrt-Installer.exe", false, "index.html"),
|
||||
("/tools/OpenWrt-Installer.exe", true, "ota.html"),
|
||||
("/tools/OpenWrt-Diff-Studio.exe", false, "diff.html"),
|
||||
("/tools/OpenWrt-Diff-Studio.exe", true, "diff.html"),
|
||||
("/tools/OpenWrt-Updater.exe", false, "ota.html"),
|
||||
("/tools/OpenWrt-Updater.app/Contents/MacOS/openwrt-diff-studio", false, "ota.html"),
|
||||
("/tools/OpenWrt-Diff-Studio.app/Contents/MacOS/openwrt-installer", false, "diff.html"),
|
||||
] {
|
||||
assert_eq!(entry_page(Path::new(path), patch).0, expected, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_window_uses_app_asset_without_navigation() {
|
||||
let mut config = tauri::Config::default();
|
||||
let mut window = tauri::utils::config::WindowConfig::default();
|
||||
window.label = "main".into();
|
||||
config.app.windows.push(window);
|
||||
configure_entry(&mut config, Path::new("OpenWrt-Diff-Studio.exe"), false);
|
||||
assert!(matches!(&config.app.windows[0].url,
|
||||
tauri::WebviewUrl::App(path) if path == Path::new("diff.html")));
|
||||
assert_eq!(config.app.windows[0].title, "OpenWrt Diff Studio");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
.ota-shell{min-height:100dvh;background:hsl(var(--background));}.ota-main{max-width:1120px;margin:0 auto;padding:34px 32px 20px;overflow:visible}.ota-intro{max-width:780px;margin-bottom:28px}.ota-intro p{color:hsl(var(--muted-foreground));margin-top:12px}.ota-eyebrow{font-size:11px;letter-spacing:.14em;color:hsl(var(--primary));font-weight:700}.ota-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.1fr);gap:24px;align-items:start}.ota-card{background:hsl(var(--card));border:1px solid hsl(var(--border));border-radius:16px;padding:24px;box-shadow:0 6px 22px #00000004}.ota-card h2{display:flex;align-items:center;gap:10px;margin-bottom:24px;font-size:16px}.ota-number{display:grid;place-items:center;background:hsl(var(--primary)/.1);color:hsl(var(--primary));border-radius:8px;width:28px;height:28px}.ota-label{display:block;font-size:12px;color:hsl(var(--muted-foreground));margin:18px 0 8px}.ota-picker{display:flex;align-items:center;gap:12px;width:100%;padding:18px;text-align:left;border:1px dashed hsl(var(--border));border-radius:10px;background:hsl(var(--background));transition:border-color .15s,background .15s}.ota-picker:hover:enabled{border-color:hsl(var(--primary));background:hsl(var(--primary)/.035)}.ota-picker>svg{flex-shrink:0;color:hsl(var(--primary))}.ota-picker span{flex:1;overflow-wrap:anywhere;min-width:0;line-height:1.6}.ota-arrow{height:20px;display:flex;align-items:center;justify-content:center;color:hsl(var(--muted-foreground));margin-top:14px}.ota-card input{width:100%}.ota-wide{width:100%;margin-top:22px}.ota-empty{display:flex;align-items:center;justify-content:center;flex-direction:column;min-height:240px;text-align:center;color:hsl(var(--muted-foreground));gap:16px}.ota-empty p{max-width:260px}.ota-empty svg{color:hsl(var(--primary)/.45)}.ota-release{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap}.ota-release strong{font-size:22px}.ota-release small:last-child{width:100%;font-family:monospace}.ota-versions{display:flex;flex-direction:column;align-items:flex-start;gap:8px;font-size:12px;overflow-wrap:anywhere;margin:20px 0}.ota-stats{display:grid;grid-template-columns:repeat(3,1fr);border-top:1px solid hsl(var(--border));border-bottom:1px solid hsl(var(--border));padding:18px 0;margin:20px 0;gap:12px}.ota-stats strong{font-size:20px;display:block}.ota-stats small{font-size:11px;display:block;margin-top:6px}.ota-files{font-size:12px;color:hsl(var(--muted-foreground));overflow-wrap:anywhere}.ota-files summary{cursor:pointer;margin:16px 0}.ota-files[open]{max-height:200px;overflow:auto}.ota-files div{padding:5px 0;font-family:monospace}.ota-notice,.ota-error{margin-top:20px;padding:16px 18px;border-radius:10px;display:flex;gap:12px;align-items:flex-start;overflow-wrap:anywhere;white-space:pre-wrap}.ota-notice{background:hsl(var(--primary)/.07);color:hsl(var(--primary))}.ota-notice>svg,.ota-error>svg{flex-shrink:0;margin-top:2px}.ota-notice small{display:block;margin-top:6px;font-size:12px;overflow-wrap:anywhere}.ota-error{background:hsl(var(--destructive)/.07);color:hsl(var(--destructive));display:block}.ota-error p{margin:4px 0}.ota-footer{margin-top:24px;display:flex;justify-content:flex-start;gap:10px;color:hsl(var(--muted-foreground));font-size:12px;line-height:1.7;padding:24px 0}.ota-footer svg{flex-shrink:0;margin-top:2px}@media(max-width:850px){.ota-main{padding:24px 18px}.ota-grid{grid-template-columns:1fr}.ota-shell header{padding:0 18px}.ota-card{padding:20px}.ota-intro h1{font-size:25px}}
|
||||
@@ -0,0 +1,94 @@
|
||||
import React, {useEffect, useState} from 'react';
|
||||
import {createRoot} from 'react-dom/client';
|
||||
import {ArrowRight, CheckCircle2, CircleAlert, FileArchive, FolderOpen, GitCompareArrows, LoaderCircle, Moon, PackageCheck, ShieldCheck, Sun, Upload} from 'lucide-react';
|
||||
import {Button} from './components/ui/button';
|
||||
import {native, request, subscribe} from './protocol';
|
||||
import './style.css';
|
||||
import './ota.css';
|
||||
|
||||
interface Operation {path:string; before:unknown; after:unknown}
|
||||
interface Manifest {family:string;profile:string;base_version:string;target_version:string;kernel_release:string;operations:Operation[];preserved:string[]}
|
||||
interface Analysis {manifest:Manifest;blockers:string[];can_export:boolean;payload_bytes:number;files:number;added:number;removed:number;output?:string}
|
||||
interface Review {token:string;check:{applicable:boolean;conflicts:string[];package_conflicts:string[];required_bytes:number;free_bytes:number}}
|
||||
interface Status {identity:{version:string};transaction?:{started:number;total:number};job?:{status:string;result?:{error?:string}}}
|
||||
const size = (n:number) => n >= 1048576 ? (n / 1048576).toFixed(1) + ' MiB' : (n / 1024).toFixed(1) + ' KiB';
|
||||
|
||||
function Studio() {
|
||||
const generator = location.pathname.endsWith('diff.html');
|
||||
const [en,setEn] = useState(localStorage.getItem('language') === 'en');
|
||||
const [dark,setDark] = useState(matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
const tr = (zh:string,english:string) => en ? english : zh;
|
||||
const [old,setOld] = useState(''), [next,setNext] = useState('');
|
||||
const [analysis,setAnalysis] = useState<Analysis>();
|
||||
const [patch,setPatch] = useState(''), [manifest,setManifest] = useState<Manifest>();
|
||||
const [host,setHost] = useState('192.168.9.1'), [password,setPassword] = useState('');
|
||||
const [busy,setBusy] = useState(false), [progress,setProgress] = useState('');
|
||||
const [error,setError] = useState(''), [success,setSuccess] = useState('');
|
||||
const [review,setReview] = useState<Review>(), [running,setRunning] = useState(false);
|
||||
useEffect(() => { document.documentElement.classList.toggle('dark',dark); }, [dark]);
|
||||
useEffect(() => {
|
||||
if (!generator) void request<{path:string;manifest:Manifest}>('ota_package').then(p=>{
|
||||
setPatch(p.path);setManifest(p.manifest);if(p.manifest.family==='mu300')setHost('192.168.77.1');
|
||||
}).catch(()=>{});
|
||||
},[]);
|
||||
useEffect(() => {
|
||||
const stop = subscribe(e => {
|
||||
if (e.type === 'ota_progress') {
|
||||
const d = e.data as {stage:string;path?:string;done?:number;total?:number};
|
||||
setProgress(d.stage === 'upload' ? `↑ ${size(d.done || 0)} / ${size(d.total || 0)}` : d.path || d.stage);
|
||||
}
|
||||
});
|
||||
return () => { void stop.then(f => f()); };
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!running) return;
|
||||
let alive = true;
|
||||
const timer = setInterval(() => {
|
||||
void request<Status>('ota_status',{host,password}).then(s => {
|
||||
if (!alive) return;
|
||||
if(s.transaction)setProgress(`${s.transaction.started} / ${s.transaction.total}`);
|
||||
if (s.job?.status !== 'running') {
|
||||
setRunning(false);
|
||||
if (s.job?.status === 'complete') setSuccess(tr('更新完成,请在网页系统补丁页重启设备。','Update complete. Reboot from the device System patches page.'));
|
||||
else setError(s.job?.result?.error || tr('更新未完成,请检查设备事务状态。','Update incomplete. Review device transaction status.'));
|
||||
}
|
||||
}).catch(e => {if (alive) setProgress(tr('连接中断;设备继续处理,可稍后重新检查状态。','Connection interrupted. The device continues processing; check status again later.') + ' ' + String(e));});
|
||||
},2000);
|
||||
return () => {alive=false;clearInterval(timer);};
|
||||
},[running,host,password,en]);
|
||||
async function work<T>(fn:()=>Promise<T>):Promise<T|undefined> {
|
||||
setBusy(true);setError('');setSuccess('');setProgress('');
|
||||
try { return await fn(); } catch(e) {setError(String(e));return undefined;}
|
||||
finally {setBusy(false);}
|
||||
}
|
||||
async function pick(which:'old'|'new'|'patch') {
|
||||
const path = await native('pick_ota_input');
|
||||
if (!path) return;
|
||||
setReview(undefined);setAnalysis(undefined);setSuccess('');
|
||||
if (which === 'old') setOld(path);
|
||||
else if (which === 'new') setNext(path);
|
||||
else { setPatch(path); const r=await work(()=>request<{manifest:Manifest}>('ota_package',{path})); if(r){setManifest(r.manifest);if(host==='192.168.9.1'||host==='192.168.77.1')setHost(r.manifest.family==='mu300'?'192.168.77.1':'192.168.9.1');} }
|
||||
}
|
||||
const blocked = busy || running;
|
||||
return <div className="ota-shell">
|
||||
<header><div className="brand"><div className="brand-icon">{generator?<GitCompareArrows size={24}/>:<PackageCheck size={24}/>}</div><div><strong>{generator?'OpenWrt Diff Studio':'OpenWrt Patch Updater'}</strong><small>{tr('保留数据 · 只更新变更文件','Keep your data · Update changed files')}</small></div></div>
|
||||
<div className="preferences"><Button variant="ghost" disabled={blocked} onClick={()=>{setEn(!en);localStorage.setItem('language',en?'zh':'en');}}>{en?'中文':'English'}</Button><Button variant="ghost" onClick={()=>setDark(!dark)} aria-label="Theme">{dark?<Sun size={18}/>:<Moon size={18}/>}</Button></div></header>
|
||||
<main className="ota-main"><div className="ota-intro"><span className="ota-eyebrow">{generator?'RELEASE TO PATCH':'VERIFIED FILE UPDATE'}</span><h1>{generator?tr('把两版发行包,变成一次轻量更新','Two releases. One compact update.'):tr('更新系统,留下你的设置','Update the system. Keep your setup.')}</h1><p>{generator?tr('选择旧版和新版完整 ZIP。工具会解析系统文件,展示兼容性与差异;相同内容只保存一份。','Select the old and new full ZIPs. Review file changes and compatibility; identical content is stored once.'):tr('导入可信差异包,连接正在运行 OpenWrt 的设备,先检查再应用。','Import a trusted patch and connect to a running OpenWrt device. Review before applying.')}</p></div>
|
||||
<div className="ota-grid"><section className="ota-card"><h2><span className="ota-number">1</span>{generator?tr('选择发行版本','Select releases'):tr('选择补丁与设备','Select patch and device')}</h2>
|
||||
{generator?<><label className="ota-label">{tr('旧版完整包','Old full release')}</label><button className="ota-picker" disabled={blocked} onClick={()=>void pick('old')}><FileArchive/><span>{old || tr('选择 ZIP 文件','Select ZIP file')}</span><FolderOpen size={18}/></button><div className="ota-arrow"><ArrowRight size={18}/></div><label className="ota-label">{tr('新版完整包','New full release')}</label><button className="ota-picker" disabled={blocked} onClick={()=>void pick('new')}><FileArchive/><span>{next || tr('选择 ZIP 文件','Select ZIP file')}</span><FolderOpen size={18}/></button>
|
||||
<Button className="ota-wide" disabled={blocked || !old || !next} onClick={()=>void work(async()=>{const r=await request<Analysis>('ota_analyze',{old,new:next});setAnalysis(r);})}>{busy?<LoaderCircle className="animate-spin" size={18}/>:<GitCompareArrows size={18}/>} {tr('分析差异','Analyze changes')}</Button></>
|
||||
:<><button className="ota-picker" disabled={blocked} onClick={()=>void pick('patch')}><FileArchive/><span>{patch || tr('选择 .ota 差异包','Select .ota patch')}</span><FolderOpen size={18}/></button><label className="ota-label">{tr('设备管理地址','Device management address')}</label><input value={host} disabled={blocked} onChange={e=>{setHost(e.target.value);setReview(undefined);}}/><label className="ota-label">SSH root {tr('密码','password')}</label><input type="password" value={password} disabled={blocked} onChange={e=>{setPassword(e.target.value);setReview(undefined);}} autoComplete="off"/>
|
||||
<Button className="ota-wide" disabled={blocked || !patch || !host} onClick={()=>void work(async()=>{setReview(await request<Review>('ota_probe',{host,password,path:patch}));})}><ShieldCheck size={18}/>{tr('连接并检查','Connect and review')}</Button><Button variant="ghost" className="ota-wide" disabled={busy || !host} onClick={()=>void work(async()=>{const s=await request<Status>('ota_status',{host,password});setRunning(s.job?.status==='running');setSuccess(JSON.stringify(s));})}>{tr('重新检查设备状态','Check device status')}</Button></>}
|
||||
</section><section className="ota-card"><h2><span className="ota-number">2</span>{tr('检查并继续','Review and continue')}</h2>
|
||||
{analysis || manifest?<><div className="ota-release"><small>{tr('目标设备','Target profile')}</small><strong>{(analysis?.manifest || manifest)!.profile}</strong><small>{(analysis?.manifest || manifest)!.kernel_release}</small></div><p className="ota-versions">{(analysis?.manifest || manifest)!.base_version}<ArrowRight size={16}/>{(analysis?.manifest || manifest)!.target_version}</p></>:<div className="ota-empty"><ShieldCheck size={42}/><p>{tr('选择文件后,在这里查看版本与兼容检查结果。','Select files to review versions and compatibility here.')}</p></div>}
|
||||
{analysis && <><div className="ota-stats"><div><strong>{analysis.files}</strong><small>{tr('文件变更','Changed files')}</small></div><div><strong>{size(analysis.payload_bytes)}</strong><small>{tr('未压缩载荷','Uncompressed payload')}</small></div><div><strong>{analysis.added} / {analysis.removed}</strong><small>{tr('新增 / 删除','Added / removed')}</small></div></div>
|
||||
{!!analysis.blockers.length && <div className="ota-error">{analysis.blockers.map((b,i)=><p key={i}>{b}</p>)}</div>}<details className="ota-files"><summary>{tr('查看文件清单','View file list')}</summary>{analysis.manifest.operations.map(o=><div key={o.path}>{o.before?(o.after?'~':'−'):'+'} {o.path}</div>)}</details>
|
||||
<Button className="ota-wide" disabled={blocked || !analysis.can_export} onClick={()=>void work(async()=>{const output=await native('save_ota');if(!output)return;const r=await request<Analysis>('ota_export',{output});setSuccess(tr('已生成差异包:','Patch saved: ')+r.output);})}><Upload size={18}/>{tr('导出差异包','Export patch')}</Button></>}
|
||||
{review && <><p>{tr('所需空间 / 可用空间:','Required / available: ')}{size(review.check.required_bytes)} / {size(review.check.free_bytes)}</p>{!![...review.check.conflicts,...review.check.package_conflicts].length && <div className="ota-error">{tr('本地文件或依赖冲突,未写入:','Local file or dependency conflicts; nothing written: ')}{[...review.check.conflicts,...review.check.package_conflicts].join(', ')}</div>}<Button className="ota-wide" disabled={blocked || !review.check.applicable} onClick={()=>void work(async()=>{await request('ota_apply',{host,password,token:review.token});setRunning(true);setReview(undefined);})}><PackageCheck size={18}/>{tr('确认应用此补丁','Apply reviewed patch')}</Button></>}
|
||||
</section></div>
|
||||
{(busy || running) && <div className="ota-notice"><LoaderCircle className="animate-spin" size={18}/><span>{running?tr('设备正在写入,关闭电脑更新器不会终止设备事务。','Device is writing. Closing this app does not cancel its transaction.'):tr('正在处理,请稍候…','Processing…')}<small>{progress}</small></span></div>}
|
||||
{error && <div className="ota-error" role="alert"><CircleAlert size={18}/>{error}</div>}{success && <div className="ota-notice" role="status"><CheckCircle2 size={18}/><span>{success}</span></div>}
|
||||
<footer className="ota-footer"><ShieldCheck size={16}/>{tr('保留配置、额外插件和用户数据。检测到本地冲突时停止,写入前保留恢复副本。仅导入可信来源的补丁。','Settings, extra packages and user data are retained. Local conflicts stop the update. Recovery copies precede writes. Import trusted patches only.')}</footer>
|
||||
</main></div>;
|
||||
}
|
||||
createRoot(document.getElementById('root')!).render(<Studio/>);
|
||||
@@ -1,3 +1,4 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
export default defineConfig({plugins: [react()], server: {port: 1420, strictPort: true}, clearScreen: false});
|
||||
export default defineConfig({plugins: [react()], server: {port: 1420, strictPort: true}, clearScreen: false,
|
||||
build: {rollupOptions: {input: {installer:'index.html', diff:'diff.html', ota:'ota.html'}}}});
|
||||
+16
-4
@@ -19,6 +19,9 @@ esac
|
||||
KREL=5.4.254-gb50db5b6224c
|
||||
OUT=${1:-mu300-$FLAVOUR-$VER-rootfs.tar.gz}
|
||||
TOP=$(cd "$(dirname "$0")/.." && pwd)
|
||||
ROOTFS_DIR=${MU300_ROOTFS_OUT_DIR:-$TOP/openwrt}
|
||||
mkdir -p "$ROOTFS_DIR"
|
||||
ROOTFS_DIR=$(cd "$ROOTFS_DIR" && pwd)
|
||||
# build inputs (out/, firmware/, android-subset/, tools binaries, busybox) may live outside the checkout
|
||||
IN=${MU300_INPUTS:-$TOP}
|
||||
MAINLINE=${MU300_MAINLINE_OUT:-$IN/upstream/out}
|
||||
@@ -134,12 +137,15 @@ docker run --rm --platform linux/arm64 \
|
||||
$(opt out/modules.builtin modules.builtin) $(opt out/modules.builtin.modinfo modules.builtin.modinfo) \
|
||||
$(opt firmware firmware) $(opt android-subset android-subset) $(opt android-gpu-subset android-gpu-subset) \
|
||||
$(opt tools/logdw/logdw logdw) $(opt tools/bt-init/mu300-bt-init bt-init) $(opt tools/keys/mu300-keys keys) $(opt tools/gpu/cltest cltest) \
|
||||
$(opt busybox busybox) $(mainline_opt modules mainline-modules) $(plugin_opt) -v "$TOP/openwrt":/out -v "$REGDB":/in/regdb:ro \
|
||||
$(opt busybox busybox) $(mainline_opt modules mainline-modules) $(plugin_opt) -v "$ROOTFS_DIR":/out -v "$REGDB":/in/regdb:ro \
|
||||
$(mainline_opt modules.builtin mainline-modules.builtin) $(mainline_opt modules.builtin.modinfo mainline-modules.builtin.modinfo) \
|
||||
-v "$THEME_APK":/in/luci-theme-aurora.apk:ro \
|
||||
-v "$BLOCK_APK":/in/block-mount-mu300.apk:ro \
|
||||
-v "$BLOCK_APK.build-id":/in/block-mount.build-id:ro \
|
||||
-v "$WIFI_APKS":/in/wifi-sae:ro \
|
||||
-v "$TOP/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/disable-stock-upgrade":/in/stock-upgrade-policy:ro \
|
||||
-v "$TOP/installer":/in/ota-source/installer:ro \
|
||||
-v "$TOP/openwrt/luci-app-unisoc-ota":/in/ota-source/openwrt/luci-app-unisoc-ota:ro \
|
||||
-v "$TOP/work/luci-app-aurora-config-1.2.5-r20260920.apk":/in/luci-app-aurora-config.apk:ro \
|
||||
-v "$TOP/work/luci-i18n-aurora-config-zh-cn-26.262.58276.362887a.apk":/in/aurora-config-zh-cn.apk:ro \
|
||||
-v "$TOP/work/luci-i18n-aurora-config-tr-26.262.58276.362887a.apk":/in/aurora-config-tr.apk:ro \
|
||||
@@ -159,7 +165,7 @@ apk_retry update >/dev/null
|
||||
apk_retry add --allow-untrusted /in/wifi-sae/*.apk >/dev/null
|
||||
# The cipher capability helper needs the section omitted by reduced iw builds.
|
||||
apk_retry add iwinfo wireless-regdb iw-full bash ip-full coreutils-stty openssl-util curl ca-bundle msmtp ucode ucode-mod-fs ucode-mod-ubus ucode-mod-uci ucode-mod-uloop ucode-mod-socket \
|
||||
i2c-tools gpiod-tools flock ttyd luci-app-ttyd luci-i18n-ttyd-zh-cn luci-i18n-ttyd-tr >/dev/null
|
||||
i2c-tools gpiod-tools flock ttyd luci-app-ttyd luci-i18n-ttyd-zh-cn luci-i18n-ttyd-tr python3 >/dev/null
|
||||
apk_retry add --allow-untrusted /in/block-mount-mu300.apk >/dev/null
|
||||
apk_retry add --allow-untrusted /in/luci-theme-aurora.apk >/dev/null
|
||||
apk_retry add --allow-untrusted /in/luci-app-aurora-config.apk /in/aurora-config-zh-cn.apk /in/aurora-config-tr.apk >/dev/null
|
||||
@@ -236,6 +242,7 @@ if [ -d /in/luci-plugin ]; then
|
||||
ucode $R/usr/libexec/unisoc-modem/filter-wifi-ciphers $R
|
||||
chmod 0755 $R/etc/init.d/unisoc-cpu $R/etc/init.d/unisoc-cpu-cores $R/usr/libexec/rpcd/unisoc-cpu-cores
|
||||
chmod 0600 $R/etc/config/unisoc_apn
|
||||
chmod 0755 $R/etc/uci-defaults/97-unisoc-upgrade-policy
|
||||
chmod 0755 $R/etc/init.d/unisoc-modem-ui $R/etc/init.d/unisoc-sms-forward $R/etc/init.d/unisoc-traffic $R/etc/hotplug.d/net/90-unisoc-usb-host $R/etc/hotplug.d/iface/90-unisoc-usb-host $R/usr/libexec/rpcd/mu300dash $R/usr/libexec/unisoc-modem/*
|
||||
mkdir -p $R/usr/lib/lua/luci/i18n
|
||||
cp -a /in/luci-plugin/lmo/. $R/usr/lib/lua/luci/i18n/
|
||||
@@ -324,11 +331,16 @@ if ls /in/mainline-modules/*.ko >/dev/null 2>&1; then
|
||||
[ ! -f /in/mainline-$f ] || cp /in/mainline-$f $R/lib/modules/$krel/$f
|
||||
done
|
||||
fi
|
||||
mkdir -p $R/usr/libexec/unisoc-modem
|
||||
cp /in/stock-upgrade-policy $R/usr/libexec/unisoc-modem/disable-stock-upgrade
|
||||
chmod 0755 $R/usr/libexec/unisoc-modem/disable-stock-upgrade
|
||||
ucode $R/usr/libexec/unisoc-modem/disable-stock-upgrade $R
|
||||
python3 /in/ota-source/installer/stage-ota.py --root $R
|
||||
cd $R && tar -czf /out/$OUT .
|
||||
ls -la /out/$OUT'
|
||||
# Remove optional VPN helpers and reject accidentally inherited VPN packages.
|
||||
python3 "$TOP/openwrt/no-vpn-payload.py" "$TOP/openwrt/$(basename "$OUT")"
|
||||
python3 "$TOP/openwrt/no-vpn-payload.py" "$ROOTFS_DIR/$(basename "$OUT")"
|
||||
if [ -d "$MAINLINE/modules" ]; then
|
||||
python3 "$TOP/upstream/check-container-support.py" "$MAINLINE" --rootfs "$TOP/openwrt/$(basename "$OUT")"
|
||||
python3 "$TOP/upstream/check-container-support.py" "$MAINLINE" --rootfs "$ROOTFS_DIR/$(basename "$OUT")"
|
||||
fi
|
||||
rm -rf "$REGDB"
|
||||
@@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=luci-app-mu300
|
||||
PKG_VERSION:=1.2.0
|
||||
PKG_RELEASE:=19
|
||||
PKG_RELEASE:=20
|
||||
PKG_LICENSE:=MIT
|
||||
PKG_MAINTAINER:=MU300 Linux contributors
|
||||
PKGARCH:=all
|
||||
@@ -42,6 +42,7 @@ define Package/luci-app-mu300/install
|
||||
$(CP) ./root/. $(1)/
|
||||
chmod 0755 $(1)/etc/init.d/unisoc-cpu-cores $(1)/usr/libexec/rpcd/unisoc-cpu-cores $(1)/usr/libexec/unisoc-modem/cpu-cores
|
||||
chmod 0600 $(1)/etc/config/unisoc_apn
|
||||
chmod 0755 $(1)/etc/uci-defaults/97-unisoc-upgrade-policy
|
||||
chmod 0600 $(1)/etc/config/mu300-charge
|
||||
chmod 0755 $(1)/etc/init.d/mu300-charge $(1)/etc/hotplug.d/power_supply/75-mu300-charge $(1)/usr/libexec/rpcd/mu300-charge
|
||||
chmod 0755 $(1)/etc/init.d/unisoc-cpu
|
||||
@@ -63,6 +64,7 @@ define Package/luci-app-mu300/postinst
|
||||
cp -a "$$old"/. "$$state"/
|
||||
fi
|
||||
ucode /usr/libexec/unisoc-modem/disable-channel-analysis || exit 1
|
||||
ucode /usr/libexec/unisoc-modem/disable-stock-upgrade || exit 1
|
||||
ucode /usr/libexec/unisoc-modem/filter-wifi-ciphers || exit 1
|
||||
rm -f /tmp/luci-indexcache /tmp/luci-modulecache/* 2>/dev/null
|
||||
uci -q get luci.languages.tr >/dev/null || uci set luci.languages.tr='Türkçe'
|
||||
|
||||
@@ -783,6 +783,20 @@ var DASH_I18N = {
|
||||
'Wi-Fi 热点': ['Wi-Fi hotspot', 'Wi-Fi erişim noktası'],
|
||||
'重启调制解调器': ['Restart modem', 'Modemi yeniden başlat'],
|
||||
'重启设备': ['Restart device', 'Cihazı yeniden başlat'],
|
||||
"手动输入小区": ["Enter a cell manually", "Hücreyi elle gir"],
|
||||
"制式": ["Radio technology", "Radyo teknolojisi"],
|
||||
"频点(EARFCN / NR-ARFCN)": ["Channel number (EARFCN / NR-ARFCN)", "Kanal numarası (EARFCN / NR-ARFCN)"],
|
||||
"锁定指定小区": ["Lock specified cell", "Belirtilen hücreyi kilitle"],
|
||||
"LTE:EARFCN 0–262143,PCI 0–503;NR:NR-ARFCN 1–3279165,PCI 0–1007。": ["LTE: EARFCN 0–262143, PCI 0–503; NR: NR-ARFCN 1–3279165, PCI 0–1007.", "LTE: EARFCN 0–262143, PCI 0–503; NR: NR-ARFCN 1–3279165, PCI 0–1007."],
|
||||
"应用于当前查看的 SIM,无需小区出现在邻区列表中。请输入频点编号,不是 MHz 频率。": ["Applies to the SIM being viewed; the cell need not appear in the neighbor list. Enter the channel number, not a frequency in MHz.", "Görüntülenen SIM için uygulanır; hücrenin komşu listesinde olması gerekmez. MHz frekansı değil, kanal numarasını girin."],
|
||||
"请输入范围内的十进制频点和 PCI": ["Enter a decimal channel number and PCI within the listed ranges", "Listelenen aralıklarda ondalık kanal numarası ve PCI girin"],
|
||||
"手动锁定小区": ["Manual cell lock", "Elle hücre kilitleme"],
|
||||
"关机或重启": ["Power off or restart", "Kapat veya yeniden başlat"],
|
||||
"请选择关机或重启,执行后所有连接都会断开。": ["Choose power off or restart. All connections will be disconnected.", "Kapatmayı veya yeniden başlatmayı seçin. Tüm bağlantılar kesilecektir."],
|
||||
"关机": ["Power off", "Kapat"],
|
||||
"重启": ["Restart", "Yeniden başlat"],
|
||||
"正在关机…": ["Powering off…", "Kapatılıyor…"],
|
||||
"正在重启…": ["Restarting…", "Yeniden başlatılıyor…"],
|
||||
'切换到 Android': ['Switch to Android', 'Android’e geç'],
|
||||
'邻区': ['Neighbor cells', 'Komşu hücreler'],
|
||||
'制式/频段': ['RAT/Band', 'Teknoloji/Bant'],
|
||||
@@ -1412,6 +1426,14 @@ html.mud-bootstrap-theme{--surface:var(--background-color-high);--surface-sunken
|
||||
.mud-meter i{display:block;height:100%;border-radius:3px}
|
||||
.mud-freq{display:flex;align-items:center;font-size:.76rem;font-variant-numeric:tabular-nums;padding:1px 0}
|
||||
.mud-freq .mud-k{flex:0 0 2.4em}
|
||||
.mud-manual-cell{margin:12px 0;max-width:720px;min-width:0}
|
||||
.mud-manual-cell summary{cursor:pointer;padding:8px 0;font-size:.85rem;font-weight:600}
|
||||
.mud-manual-cell form{margin:4px 0 12px}
|
||||
.mud-manual-cell-fields{display:flex;flex-wrap:wrap;align-items:end;gap:12px}
|
||||
.mud-manual-cell-fields label{display:flex;flex:1 1 140px;flex-direction:column;gap:6px;margin:0;min-width:0;font-size:.82rem}
|
||||
.mud-manual-cell-fields input,.mud-manual-cell-fields select{box-sizing:border-box;width:100%;max-width:100%;min-width:0;min-height:38px;margin:0;padding:8px 10px;border:1px solid var(--hairline,var(--border,#ccc));border-radius:var(--radius-base,.5rem);background:var(--surface,var(--background,#fff));color:var(--text,#222);font:inherit}
|
||||
.mud-manual-cell-fields button{min-height:38px;margin:0;white-space:normal}
|
||||
.mud-manual-cell-fields input:focus,.mud-manual-cell-fields select:focus{outline:2px solid var(--brand,var(--primary,#37a));outline-offset:1px}
|
||||
.mud-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:7px 12px;border:1px solid var(--hairline,var(--border,#ccc));border-radius:var(--radius-base,.5rem);background:var(--surface,var(--background,#fff));color:var(--text,#222);font-size:.82rem;cursor:pointer;user-select:none}
|
||||
.mud-btn:active{transform:scale(.97)}
|
||||
.mud-voice-row{align-items:center;gap:12px;padding:8px 0}
|
||||
|
||||
@@ -245,7 +245,7 @@ return view.extend({
|
||||
<button class="mud-btn" id="mud-btn-radio">蜂窝射频</button>
|
||||
<button class="mud-btn" id="mud-btn-wifi">Wi-Fi 热点</button>
|
||||
<button class="mud-btn warn" id="mud-btn-modem">重启调制解调器</button>
|
||||
<button class="mud-btn warn" id="mud-btn-reboot">重启设备</button>
|
||||
<button class="mud-btn warn" id="mud-btn-reboot">关机或重启</button>
|
||||
<button class="mud-btn warn" id="mud-btn-android">切换到 Android</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -329,8 +329,17 @@ return view.extend({
|
||||
{ danger: true }, 'modem-reset', null);
|
||||
};
|
||||
q('btn-reboot').onclick = function() {
|
||||
return confirmAction(this, '重启整个设备', '所有连接会断开。',
|
||||
{ danger: true }, 'reboot', null);
|
||||
var btn = this;
|
||||
if (self._disposed || self._quickPending || btn.disabled) return;
|
||||
self._quickPending = true;
|
||||
return M.choiceBox('关机或重启', '请选择关机或重启,执行后所有连接都会断开。', [
|
||||
{ label: '取消', value: undefined },
|
||||
{ label: '关机', value: 'poweroff', danger: true },
|
||||
{ label: '重启', value: 'reboot', danger: true }
|
||||
]).then(function(op) {
|
||||
if ((op !== 'poweroff' && op !== 'reboot') || self._disposed || !root.isConnected) return;
|
||||
return act(op, null, op === 'poweroff' ? '正在关机…' : '正在重启…', btn);
|
||||
}).finally(function() { self._quickPending = false; });
|
||||
};
|
||||
q('btn-default').onclick = function() {
|
||||
return confirmAction(this, '设为默认启动',
|
||||
|
||||
@@ -99,6 +99,19 @@ return view.extend({
|
||||
<button class="mud-btn" id="mud-lock-cell">锁定当前服务小区</button>
|
||||
<button class="mud-btn warn" id="mud-lock-cell-off">解除小区锁定</button>
|
||||
</div>
|
||||
<details class="mud-manual-cell">
|
||||
<summary>手动输入小区</summary>
|
||||
<form id="mud-lock-manual-form" novalidate>
|
||||
<div class="mud-manual-cell-fields">
|
||||
<label><span>制式</span><select id="mud-lock-manual-rat"><option value="lte">LTE (4G)</option><option value="nr">NR (5G)</option></select></label>
|
||||
<label><span>频点(EARFCN / NR-ARFCN)</span><input id="mud-lock-manual-frequency" type="text" inputmode="numeric" autocomplete="off" required></label>
|
||||
<label><span>PCI</span><input id="mud-lock-manual-pci" type="text" inputmode="numeric" autocomplete="off" required></label>
|
||||
<button type="submit" class="mud-btn" id="mud-lock-manual-apply">锁定指定小区</button>
|
||||
</div>
|
||||
<div class="mud-note">LTE:EARFCN 0–262143,PCI 0–503;NR:NR-ARFCN 1–3279165,PCI 0–1007。</div>
|
||||
<div class="mud-note">应用于当前查看的 SIM,无需小区出现在邻区列表中。请输入频点编号,不是 MHz 频率。</div>
|
||||
</form>
|
||||
</details>
|
||||
<div class="mud-scroll">
|
||||
<table class="mud-table"><thead><tr><th>制式/频段</th><th>PCI</th><th>频点</th><th>RSRP</th><th>RSRQ</th><th>SINR</th><th></th></tr></thead>
|
||||
<tbody id="mud-neigh"><tr><td colspan="7" style="color:var(--text-muted,var(--text-light,#777))">--</td></tr></tbody></table>
|
||||
@@ -131,11 +144,11 @@ return view.extend({
|
||||
opts = opts || {};
|
||||
var slot = M.selectedSlot();
|
||||
opts.slot = slot;
|
||||
M.confirmBox(opts.title || ('应用「' + what + '」?'),
|
||||
return M.confirmBox(opts.title || ('应用「' + what + '」?'),
|
||||
opts.message || (opts.noSfun ? '' : '协议栈会重启(SFUN),蜂窝断开约半分钟。'),
|
||||
{ danger: !opts.noSfun, okText: opts.okText || '应用' })
|
||||
.then(function(go) {
|
||||
if (self._disposed || !go) return;
|
||||
if (self._disposed || !go || !root.isConnected) return;
|
||||
if (M.selectedSlot() !== slot) { self.note('查看卡槽已改变,请重新确认操作', 'info'); return; }
|
||||
applyNow(kind, val, what, opts); });
|
||||
};
|
||||
@@ -273,6 +286,27 @@ return view.extend({
|
||||
};
|
||||
this.Q('lock-cell').onclick = function() { apply('cell', 'auto', '锁定当前服务小区', { btn: this }); };
|
||||
this.Q('lock-cell-off').onclick = function() { apply('cell', 'off', '解除小区锁定', { btn: this }); };
|
||||
|
||||
this.Q('lock-manual-form').onsubmit = function(ev) {
|
||||
ev.preventDefault();
|
||||
if (self._disposed || self._applying || self._manualConfirm) return;
|
||||
var rat = self.Q('lock-manual-rat').value;
|
||||
var frequency = self.Q('lock-manual-frequency').value.trim();
|
||||
var pci = self.Q('lock-manual-pci').value.trim();
|
||||
var nr = rat === 'nr';
|
||||
if ((rat !== 'lte' && !nr) || !/^[0-9]{1,7}$/.test(frequency) || !/^[0-9]{1,4}$/.test(pci) ||
|
||||
Number(frequency) < (nr ? 1 : 0) || Number(frequency) > (nr ? 3279165 : 262143) ||
|
||||
Number(pci) > (nr ? 1007 : 503)) {
|
||||
self.note('请输入范围内的十进制频点和 PCI', 'error');
|
||||
return;
|
||||
}
|
||||
var value = rat + ':' + Number(frequency) + ',' + Number(pci);
|
||||
self._manualConfirm = true;
|
||||
return apply('cell', value, M.translate('手动锁定小区') + ' ' + (nr ? 'NR' : 'LTE') +
|
||||
' / ' + Number(frequency) + ' / PCI ' + Number(pci), {btn:self.Q('lock-manual-apply')})
|
||||
.finally(function() { self._manualConfirm = false; });
|
||||
};
|
||||
|
||||
this.Q('lock-reset').onclick = function() {
|
||||
apply('reset', 'auto', '清除当前 SIM 全部锁定', {
|
||||
btn: this, okText: '确认清除',
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
# Keep backup/restore while removing whole-disk firmware flashing.
|
||||
exec ucode /usr/libexec/unisoc-modem/disable-stock-upgrade /
|
||||
@@ -169,7 +169,7 @@ m_act() {
|
||||
case "$arg" in on) enabled=1;; off) enabled=0;; *) printf '{"ok":0,"error":"Invalid radio request"}\n'; return;; esac
|
||||
"$DASH/data-sim" start "radio-${MU300_SIM_SLOT:-0}-$enabled"
|
||||
;;
|
||||
modem-reset|reboot|vpn)
|
||||
modem-reset|reboot|poweroff|vpn)
|
||||
setsid "$DASH/action" "$op" "$arg" >/dev/null 2>&1 &
|
||||
printf '{"ok":1,"started":1,"op":"%s"}\n' "$op$arg"
|
||||
;;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
# mu300-dash-act wifi on|off uci wireless disabled flag + wifi up/down
|
||||
# mu300-dash-act modem-reset the SFUN 5/3/2/4 sequence mobile-data uses for sim-reset
|
||||
# mu300-dash-act vpn start|stop /etc/init.d/mu300-vpn
|
||||
# mu300-dash-act reboot the whole box, after a 3 s grace for the HTTP reply
|
||||
# mu300-dash-act reboot|poweroff orderly restart/shutdown, after a 3 s grace for the HTTP reply
|
||||
#
|
||||
# Every op prints one JSON line on stdout. The rpcd backend (/usr/libexec/rpcd/mu300dash)
|
||||
# runs the slow ones via setsid and returns immediately: LuCI's /admin/ubus endpoint
|
||||
@@ -61,9 +61,9 @@ case "${1:-}:${2:-}" in
|
||||
fail "vpn $2" "VPN integration is not provided by this platform"
|
||||
fi
|
||||
;;
|
||||
reboot:)
|
||||
reboot:|poweroff:)
|
||||
sleep 3 # the reply has to make it out first
|
||||
reboot
|
||||
"$1" # procd stops services and unmounts normally; never force
|
||||
;;
|
||||
os:linux-default)
|
||||
if [ ! -x /opt/mu300/bin/mu300-next-boot ]; then
|
||||
@@ -95,7 +95,7 @@ case "${1:-}:${2:-}" in
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
echo "usage: $0 radio on|off | data up|down | wifi on|off | modem-reset | vpn start|stop | reboot | os android" >&2
|
||||
echo "usage: $0 radio on|off | data up|down | wifi on|off | modem-reset | vpn start|stop | reboot | poweroff | os android" >&2
|
||||
printf '{"ok":0,"error":"unknown op"}\n'
|
||||
exit 2
|
||||
;;
|
||||
|
||||
@@ -145,7 +145,8 @@ MODEL=$(rd /tmp/sysinfo/model 2>/dev/null)
|
||||
[ -n "$MODEL" ] || MODEL=$(cat /proc/device-tree/model 2>/dev/null | tr -d '\0')
|
||||
FW=$(sed -n "s/^DISTRIB_DESCRIPTION='\(.*\)'$/\1/p" /etc/openwrt_release 2>/dev/null)
|
||||
[ -n "$FW" ] || FW=$(uname -sr)
|
||||
PRIVATE_FW=$(rd /etc/mu300/image-version 2>/dev/null)
|
||||
PRIVATE_FW=$(jval "$(rd /etc/unisoc-ota/current.json 2>/dev/null)" version)
|
||||
[ -n "$PRIVATE_FW" ] || PRIVATE_FW=$(rd /etc/mu300/image-version 2>/dev/null)
|
||||
[ -z "$PRIVATE_FW" ] || FW="$PRIVATE_FW ($FW)"
|
||||
|
||||
# /proc/stat first line: cpu user nice system idle iowait irq softirq steal ...
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/ucode
|
||||
// Stock whole-disk flashing is unsupported; keep configuration backup/restore.
|
||||
import { glob, readfile, writefile, rename, unlink } from 'fs';
|
||||
let root = ARGV[0] || '';
|
||||
let changes = [];
|
||||
let marker = '/* unisoc: configuration backups only */';
|
||||
let view = root + '/www/luci-static/resources/view/system/flash.js';
|
||||
let text = readfile(view);
|
||||
if (text != null && index(text, marker) < 0) {
|
||||
// OpenWrt 25.12's installed, minified LuCI view. A changed upstream
|
||||
// layout must be reviewed rather than removing unknown backup controls.
|
||||
let begin = index(text, "o=s.option(form.SectionValue,'actions',form.NamedSection,'actions','actions',_('Flash new firmware image')");
|
||||
if (begin < 0)
|
||||
die('Unknown LuCI flash view; inspect before changing update policy\n');
|
||||
let tail = substr(text, begin);
|
||||
let end = index(tail, "s=m.section(form.NamedSection,'config'");
|
||||
if (end < 0)
|
||||
die('Missing LuCI backup configuration boundary\n');
|
||||
text = substr(text, 0, begin) + marker + '\n' + substr(tail, end);
|
||||
text = replace(text, "_('Flash operations')", "_('Backup')");
|
||||
push(changes, [ view, text ]);
|
||||
}
|
||||
for (let path in glob(root + '/usr/share/luci/menu.d/*.json')) {
|
||||
let data = json(readfile(path));
|
||||
if (type(data) != 'object') die('Invalid menu: ' + path + '\n');
|
||||
let changed = false;
|
||||
for (let key in keys(data)) {
|
||||
let route = data[key];
|
||||
if (key == 'admin/system/flash' && route.action?.path == 'system/flash') {
|
||||
if (route.title != 'Backup') { route.title = 'Backup'; changed = true; }
|
||||
}
|
||||
else if (key == 'admin/system/attendedsysupgrade' || route.action?.path == 'system/attendedsysupgrade' || (key == 'admin/system/upgrade' && route.action?.path in [ 'system/upgrade', 'system/flash' ])) {
|
||||
delete data[key]; changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) push(changes, [ path, sprintf('%J\n', data) ]);
|
||||
}
|
||||
let backup = {
|
||||
'/sbin/sysupgrade --list-backup': true,
|
||||
'/sbin/sysupgrade -l': true,
|
||||
'/sbin/sysupgrade --restore-backup /tmp/backup.tar.gz': true
|
||||
};
|
||||
for (let path in glob(root + '/usr/share/rpcd/acl.d/*.json')) {
|
||||
let data = json(readfile(path));
|
||||
if (type(data) != 'object') die('Invalid ACL: ' + path + '\n');
|
||||
let changed = false;
|
||||
for (let group in keys(data)) {
|
||||
if (group in [ 'luci-app-attendedsysupgrade', 'luci-mod-system-attendedsysupgrade' ]) {
|
||||
delete data[group]; changed = true; continue;
|
||||
}
|
||||
if (group != 'luci-mod-system-flash') continue;
|
||||
for (let access in values(data[group])) {
|
||||
if (type(access) != 'object') continue;
|
||||
for (let name in keys(access.file || {})) {
|
||||
if (name == '/tmp/firmware.bin' || (substr(name, 0, 17) == '/sbin/sysupgrade ' && !backup[name])) {
|
||||
delete access.file[name]; changed = true;
|
||||
}
|
||||
}
|
||||
let methods = access.ubus?.system;
|
||||
if (type(methods) == 'array' && index(methods, 'validate_firmware_image') >= 0) {
|
||||
access.ubus.system = filter(methods, method => method != 'validate_firmware_image');
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (changed) push(changes, [ path, sprintf('%J\n', data) ]);
|
||||
}
|
||||
// Do not write any menu/ACL if the view or input JSON failed validation.
|
||||
for (let change in changes) {
|
||||
let temporary = change[0] + '.upgrade-policy.tmp';
|
||||
if (writefile(temporary, change[1]) != length(change[1]) || !rename(temporary, change[0])) {
|
||||
unlink(temporary);
|
||||
die('Could not disable stock flashing: ' + change[0] + '\n');
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ validate_apply() {
|
||||
pair=${val#*:}; fr=${pair%,*}; pc=${pair#*,}
|
||||
# Decimal comparisons via awk also reject leading-zero surprises.
|
||||
printf '%s\n' "$fr,$pc" | awk -F, -v rat="${val%%:*}" '
|
||||
{ exit !($1 > 0 && $1 <= (rat=="nr" ? 3279165 : 262143) &&
|
||||
{ exit !($1 >= (rat=="nr" ? 1 : 0) && $1 <= (rat=="nr" ? 3279165 : 262143) &&
|
||||
$2 >= 0 && $2 <= (rat=="nr" ? 1007 : 503)) }' ||
|
||||
{ fail_apply '无效的小区参数'; return 1; }
|
||||
;;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=luci-app-unisoc-ota
|
||||
PKG_VERSION:=1.0.0
|
||||
PKG_RELEASE:=1
|
||||
PKG_LICENSE:=MIT
|
||||
PKGARCH:=all
|
||||
|
||||
include $(INCLUDE_DIR)/package.mk
|
||||
|
||||
define Package/luci-app-unisoc-ota
|
||||
SECTION:=luci
|
||||
CATEGORY:=LuCI
|
||||
TITLE:=Unisoc verified file hotfix updater
|
||||
DEPENDS:=+luci-base +rpcd +python3
|
||||
endef
|
||||
|
||||
define Build/Compile
|
||||
endef
|
||||
|
||||
define Package/luci-app-unisoc-ota/install
|
||||
$(INSTALL_DIR) $(1)/usr/lib/unisoc-ota $(1)/www
|
||||
$(CP) ./root/. $(1)/
|
||||
$(CP) ./htdocs/. $(1)/www/
|
||||
chmod 0755 $(1)/etc/init.d/unisoc-ota $(1)/usr/libexec/rpcd/unisoc-ota
|
||||
endef
|
||||
|
||||
define Package/luci-app-unisoc-ota/postinst
|
||||
#!/bin/sh
|
||||
[ -n "$${IPKG_INSTROOT}" ] || /etc/init.d/unisoc-ota enable
|
||||
exit 0
|
||||
endef
|
||||
|
||||
$(eval $(call BuildPackage,luci-app-unisoc-ota))
|
||||
@@ -0,0 +1,85 @@
|
||||
'use strict';
|
||||
'require view';
|
||||
'require rpc';
|
||||
'require ui';
|
||||
'require poll';
|
||||
|
||||
var callStatus = rpc.declare({object:'unisoc-ota', method:'status'});
|
||||
var callInspect = rpc.declare({object:'unisoc-ota', method:'inspect'});
|
||||
var callStart = rpc.declare({object:'unisoc-ota', method:'start', params:['id']});
|
||||
var callRollback = rpc.declare({object:'unisoc-ota', method:'rollback'});
|
||||
var callReboot = rpc.declare({object:'unisoc-ota', method:'reboot'});
|
||||
|
||||
return view.extend({
|
||||
load: function() { return callStatus(); },
|
||||
render: function(state) {
|
||||
var zh = (document.documentElement.lang || '').toLowerCase().indexOf('zh') === 0;
|
||||
var tr = function(a,b) { return zh ? a : b; };
|
||||
var error = function(r) { if (r && r.error) throw new Error(r.error); return r; };
|
||||
var detail = E('div', {style:'margin:18px 0;overflow-wrap:anywhere'});
|
||||
var status = E('p');
|
||||
var button = E('button', {class:'cbi-button cbi-button-action', disabled:!L.hasViewPermission()}, tr('导入差异包','Import patch'));
|
||||
var rollback = E('button', {class:'cbi-button', disabled:!L.hasViewPermission(), style:'margin-inline-start:12px'}, tr('撤销上次补丁','Roll back last patch'));
|
||||
var reboot = E('button', {class:'cbi-button', disabled:!L.hasViewPermission(), style:'margin-inline-start:12px'}, tr('重启生效','Reboot'));
|
||||
var busy = false, watching = false;
|
||||
function show(r) {
|
||||
error(r);
|
||||
var identity = r.identity || {};
|
||||
status.textContent = tr('当前版本:','Current version: ') + (identity.version || '--');
|
||||
if (r.job && r.job.status === 'running') {
|
||||
busy = true;
|
||||
detail.textContent = tr('正在应用补丁:','Applying patch: ') + (r.transaction ? r.transaction.started + ' / ' + r.transaction.total : tr('准备中','Preparing'));
|
||||
watch();
|
||||
}
|
||||
else {
|
||||
busy = false;
|
||||
if (r.job && r.job.result) {
|
||||
detail.textContent = r.job.result.error || (r.job.status === 'complete' ? tr('操作完成。请重启使所有服务使用新文件。','Complete. Reboot to use all updated files.') : '');
|
||||
}
|
||||
}
|
||||
button.disabled = busy || !L.hasViewPermission();
|
||||
rollback.disabled = busy || !L.hasViewPermission() || !(r.transaction && r.transaction.status === 'complete');
|
||||
reboot.disabled = busy || !L.hasViewPermission();
|
||||
}
|
||||
function watch() {
|
||||
if (watching) return;
|
||||
watching = true;
|
||||
function tick() {
|
||||
return callStatus().then(function(r) { show(r); if (!busy) {poll.remove(tick); watching=false;} });
|
||||
}
|
||||
poll.add(tick, 2);
|
||||
}
|
||||
function failed(e) { ui.addNotification(null, E('p', {}, e.message || String(e)), 'error'); }
|
||||
button.onclick = function() {
|
||||
if (busy) return;
|
||||
return ui.uploadFile('/etc/unisoc-ota/upload.ota', button).then(function() { return callInspect(); }).then(function(r) {
|
||||
error(r);
|
||||
var m = r.manifest;
|
||||
var text = E('div', {}, [E('p', {}, m.base_version + ' → ' + m.target_version),
|
||||
E('p', {}, m.operations.length + tr(' 个系统文件变更;保留配置、插件及用户数据。',' system file changes. Settings, extra plugins and user data are retained.')),
|
||||
E('p', {}, tr('仅导入可信来源的补丁。哈希校验不等同于发布者签名。','Import only trusted patches. Checksums do not authenticate the publisher.'))]);
|
||||
if (!r.applicable) {
|
||||
text.appendChild(E('p', {}, tr('无法应用。冲突文件或依赖:','Cannot apply. File/dependency conflicts: ') + r.conflicts.concat(r.package_conflicts || []).join(', ') + tr(';所需空间:','; required space: ') + r.required_bytes));
|
||||
}
|
||||
ui.showModal(tr('确认系统补丁','Review system patch'), [text, E('div', {class:'right'}, [
|
||||
E('button', {class:'cbi-button', click:ui.hideModal}, tr('取消','Cancel')),
|
||||
E('button', {class:'cbi-button cbi-button-action', disabled:!r.applicable, style:'margin-inline-start:12px', click:function() {
|
||||
ui.hideModal(); busy=true; button.disabled=true;
|
||||
callStart(r.id).then(error).then(function() {detail.textContent=tr('正在更新,关闭网页不会中断写入。','Updating. Closing this page does not interrupt writes.'); watch();}).catch(failed);
|
||||
}}, tr('应用补丁','Apply patch'))
|
||||
])]);
|
||||
}).catch(failed);
|
||||
};
|
||||
rollback.onclick = function() {
|
||||
ui.showModal(tr('撤销上次补丁?','Roll back the last patch?'), [E('p', {}, tr('已修改的系统文件会恢复为更新前版本。存在本地冲突时会停止。','Changed system files will return to their previous versions. Local conflicts stop rollback.')),
|
||||
E('button', {class:'cbi-button',click:ui.hideModal}, tr('取消','Cancel')),
|
||||
E('button', {class:'cbi-button cbi-button-action',style:'margin-inline-start:12px',click:function(){ui.hideModal();callRollback().then(error).then(watch).catch(failed);}},tr('撤销','Roll back'))]);
|
||||
};
|
||||
reboot.onclick = function() { callReboot().then(error).then(function(){ui.awaitReconnect();}).catch(failed); };
|
||||
show(state);
|
||||
return E('div', {class:'cbi-map'}, [E('h2', {}, tr('系统补丁','System patches')), status,
|
||||
E('p', {}, tr('从新版与旧版完整包生成的文件差异更新。应用前检查版本、机型及本地文件冲突,写入前保留恢复副本。','File hotfixes generated from two full releases. The updater checks model, base version and local conflicts, and keeps recovery copies before writing.')),
|
||||
E('div', {style:'margin:20px 0'}, [button,rollback,reboot]), detail]);
|
||||
},
|
||||
handleSaveApply: null, handleSave: null, handleReset: null
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh /etc/rc.common
|
||||
# No idle daemon, timer or polling. Only interrupted transactions need Python.
|
||||
START=06
|
||||
start() {
|
||||
[ -s /etc/unisoc-ota/journal.json ] || return 0
|
||||
case "$(jsonfilter -i /etc/unisoc-ota/journal.json -e '@.status')" in
|
||||
applying|rolling_back) ;; *) return 0 ;;
|
||||
esac
|
||||
python3 /usr/lib/unisoc-ota/engine.py recover || {
|
||||
logger -t unisoc-ota 'Interrupted OTA could not be recovered; review persistent journal'
|
||||
return 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unisoc file hotfix protocol 1. Standard-library-only device/desktop verifier.
|
||||
|
||||
No package supplied programs, no root extraction, no configuration replacement.
|
||||
The transaction journal is durable before its first mutation. Recovery is also
|
||||
run before network/modem startup by the packaged init service.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import contextlib
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import time
|
||||
import zipfile
|
||||
|
||||
FORMAT = 'unisoc-file-ota-1'
|
||||
MAX_MANIFEST = 16 << 20
|
||||
MAX_BYTES = 2 << 30
|
||||
MAX_FILES = 50000
|
||||
STATE = 'etc/unisoc-ota'
|
||||
HEX = re.compile(r'[0-9a-f]{64}')
|
||||
# Persistent state, board firmware/NV and package-manager ownership are never
|
||||
# overwritten by an arbitrary file update. New packages require a full installer.
|
||||
PROTECTED = ('lib/firmware', 'lib/apk', 'usr/lib/opkg', 'usr/lib/apk',
|
||||
'lib/modules', 'bin/busybox', 'sbin/init', 'sbin/procd',
|
||||
'lib/ld-musl-aarch64.so.1', 'lib/libc.so',
|
||||
'usr/lib/unisoc-ota', 'usr/libexec/unisoc-ota',
|
||||
'usr/share/unisoc-ota', 'etc/init.d/unisoc-ota',
|
||||
'opt/e5/vendor', 'opt/e5/firmware', 'opt/e5/nv', 'opt/e5/android',
|
||||
'opt/mu300/vendor', 'opt/mu300/firmware', 'opt/mu300/nv', 'etc/uci-defaults')
|
||||
OFFLINE_ONLY = ('lib/modules', 'bin/busybox', 'sbin/init', 'sbin/procd',
|
||||
'lib/ld-musl-aarch64.so.1', 'lib/libc.so', 'usr/lib/unisoc-ota',
|
||||
'usr/libexec/unisoc-ota', 'usr/libexec/rpcd/unisoc-ota', 'etc/init.d/unisoc-ota')
|
||||
|
||||
|
||||
def canonical(data):
|
||||
return json.dumps(data, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode()
|
||||
|
||||
|
||||
def digest(stream):
|
||||
h = hashlib.sha256()
|
||||
for block in iter(lambda: stream.read(1 << 20), b''):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def safe_name(name):
|
||||
if (not isinstance(name, str) or not name or len(name) > 2048 or
|
||||
'\\' in name or '\0' in name or any(ord(c) < 32 for c in name) or
|
||||
name.startswith('/') or any(p in ('', '.', '..') for p in name.split('/'))):
|
||||
raise ValueError('Unsafe path: ' + repr(name))
|
||||
return name
|
||||
|
||||
|
||||
def protected(name):
|
||||
safe_name(name)
|
||||
if name.split('/')[0] not in ('bin', 'sbin', 'lib', 'lib64', 'usr', 'opt', 'etc', 'www'):
|
||||
return True
|
||||
if name.startswith('etc/') and not name.startswith(('etc/init.d/', 'etc/hotplug.d/', 'etc/uci-defaults/')):
|
||||
return True
|
||||
return any(name == p or name.startswith(p + '/') for p in PROTECTED)
|
||||
|
||||
|
||||
def package_versions(raw):
|
||||
"""Only installed package identity/dependencies; never rewrite APK metadata."""
|
||||
result = {}
|
||||
for paragraph in raw.decode('utf-8').split('\n\n'):
|
||||
fields = {}
|
||||
for line in paragraph.splitlines():
|
||||
if len(line) > 2 and line[1] == ':':
|
||||
fields[line[0]] = line[2:]
|
||||
if 'P' in fields:
|
||||
result[fields['P']] = {key:fields.get(key, '') for key in ('V', 'A', 'D')}
|
||||
return result
|
||||
|
||||
|
||||
def descriptor(path):
|
||||
try:
|
||||
s = path.lstat()
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
result = {'mode': stat.S_IMODE(s.st_mode), 'uid': s.st_uid, 'gid': s.st_gid}
|
||||
if stat.S_ISLNK(s.st_mode):
|
||||
result.update(kind='symlink', target=os.readlink(path))
|
||||
elif stat.S_ISREG(s.st_mode):
|
||||
with path.open('rb') as stream:
|
||||
result.update(kind='file', sha256=digest(stream), size=s.st_size)
|
||||
elif stat.S_ISDIR(s.st_mode):
|
||||
result.update(kind='dir')
|
||||
else:
|
||||
raise ValueError('Unsupported special file: ' + str(path))
|
||||
result['xattrs'] = {k: base64.b64encode(os.getxattr(path, k, follow_symlinks=False)).decode()
|
||||
for k in os.listxattr(path, follow_symlinks=False)}
|
||||
return result
|
||||
|
||||
|
||||
def validate_descriptor(value):
|
||||
if value is None:
|
||||
return
|
||||
if not isinstance(value, dict) or value.get('kind') not in ('file', 'symlink', 'dir'):
|
||||
raise ValueError('Invalid file descriptor')
|
||||
if any(type(value.get(k)) is not int or not 0 <= value[k] <= limit
|
||||
for k, limit in (('mode', 0o7777), ('uid', 65535), ('gid', 65535))):
|
||||
raise ValueError('Invalid file permissions/ownership')
|
||||
if value['kind'] == 'file' and (not HEX.fullmatch(value.get('sha256', '')) or
|
||||
type(value.get('size')) is not int or not 0 <= value['size'] <= MAX_BYTES):
|
||||
raise ValueError('Invalid file hash/size')
|
||||
if value['kind'] == 'symlink' and (not isinstance(value.get('target'), str) or
|
||||
not value['target'] or len(value['target']) > 4096 or '\0' in value['target']):
|
||||
raise ValueError('Invalid symbolic link')
|
||||
for name, encoded in value.get('xattrs', {}).items():
|
||||
if not isinstance(name, str) or not name or '\0' in name or len(base64.b64decode(encoded, validate=True)) > 65536:
|
||||
raise ValueError('Invalid extended attribute')
|
||||
|
||||
|
||||
def validate_manifest(m):
|
||||
if not isinstance(m, dict) or m.get('format') != FORMAT:
|
||||
raise ValueError('Unsupported OTA format')
|
||||
if m.get('family') not in ('e5', 'mu300') or not isinstance(m.get('profile'), str):
|
||||
raise ValueError('Invalid OTA family/profile')
|
||||
for k in ('base_version', 'target_version', 'kernel_release'):
|
||||
if not isinstance(m.get(k), str) or not re.fullmatch(r'[A-Za-z0-9._+\-]{1,180}', m[k]):
|
||||
raise ValueError('Invalid ' + k)
|
||||
if m['base_version'] == m['target_version']:
|
||||
raise ValueError('Release versions are identical')
|
||||
ops = m.get('operations')
|
||||
if not isinstance(ops, list) or not 0 < len(ops) <= MAX_FILES:
|
||||
raise ValueError('Empty or excessive OTA operations')
|
||||
seen = set()
|
||||
for op in ops:
|
||||
name = safe_name(op['path'])
|
||||
if name in seen or protected(name):
|
||||
raise ValueError('Duplicate/protected OTA path: ' + name)
|
||||
seen.add(name)
|
||||
before, after = op.get('before'), op.get('after')
|
||||
validate_descriptor(before)
|
||||
validate_descriptor(after)
|
||||
if before == after or before is None and after is None:
|
||||
raise ValueError('Redundant operation')
|
||||
# Directory removal or type changes could remove user-owned descendants.
|
||||
if before and before['kind'] == 'dir' and (not after or after['kind'] != 'dir'):
|
||||
raise ValueError('Directory removal/type change is not supported: ' + name)
|
||||
if before and after and before['kind'] != after['kind']:
|
||||
raise ValueError('File type changes require full installation: ' + name)
|
||||
for name in seen:
|
||||
for parent in PurePosixPath(name).parents:
|
||||
p = str(parent)
|
||||
if p in seen:
|
||||
op = next(o for o in ops if o['path'] == p)
|
||||
if not op['after'] or op['after']['kind'] != 'dir':
|
||||
raise ValueError('Operation below a non-directory: ' + name)
|
||||
if m.get('boot') is not None:
|
||||
raise ValueError('Kernel/boot updates require the full installer in protocol 1')
|
||||
return m
|
||||
|
||||
|
||||
class Patch:
|
||||
def __init__(self, path):
|
||||
self.archive = zipfile.ZipFile(path)
|
||||
try:
|
||||
names = self.archive.namelist()
|
||||
if len(names) != len(set(names)) or len(names) > MAX_FILES + 1:
|
||||
raise ValueError('Duplicate/excessive ZIP entries')
|
||||
info = self.archive.getinfo('manifest.json')
|
||||
if info.file_size > MAX_MANIFEST:
|
||||
raise ValueError('OTA manifest too large')
|
||||
self.manifest = validate_manifest(json.loads(self.archive.read(info)))
|
||||
self.id = hashlib.sha256(canonical(self.manifest)).hexdigest()
|
||||
blobs = {o['after']['sha256']: o['after']['size'] for o in self.manifest['operations']
|
||||
if o['after'] and o['after']['kind'] == 'file'}
|
||||
if set(names) != {'manifest.json', *('blobs/' + h for h in blobs)}:
|
||||
raise ValueError('Unexpected or missing archive entries')
|
||||
if sum(blobs.values()) > MAX_BYTES:
|
||||
raise ValueError('OTA exceeds expanded size limit')
|
||||
for h, size in blobs.items():
|
||||
info = self.archive.getinfo('blobs/' + h)
|
||||
if info.file_size != size or info.flag_bits & 1:
|
||||
raise ValueError('Invalid encrypted blob or length')
|
||||
with self.archive.open(info) as stream:
|
||||
if digest(stream) != h:
|
||||
raise ValueError('OTA content checksum mismatch: ' + h)
|
||||
except BaseException:
|
||||
self.archive.close()
|
||||
raise
|
||||
|
||||
def close(self):
|
||||
self.archive.close()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.close()
|
||||
|
||||
|
||||
def sync_dir(path):
|
||||
fd = os.open(path, os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0))
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def atomic_json(path, value):
|
||||
tmp = path.with_suffix('.new')
|
||||
with tmp.open('wb') as stream:
|
||||
stream.write(canonical(value) + b'\n')
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(tmp, 0o600)
|
||||
os.replace(tmp, path)
|
||||
sync_dir(path.parent)
|
||||
|
||||
|
||||
class Engine:
|
||||
def __init__(self, root='/'):
|
||||
self.root = Path(root).resolve()
|
||||
self.state = self.path(STATE)
|
||||
|
||||
def path(self, name):
|
||||
safe_name(name)
|
||||
path = self.root / name
|
||||
# Check parents, not resolve(): /bin's legitimate links are also rejected
|
||||
# rather than following an unreviewed alias into a different file tree.
|
||||
for parent in path.parents:
|
||||
if parent == self.root:
|
||||
break
|
||||
if parent.is_symlink():
|
||||
raise ValueError('Symbolic link parent: ' + str(parent))
|
||||
return path
|
||||
|
||||
@contextlib.contextmanager
|
||||
def lock(self):
|
||||
import fcntl
|
||||
self.state.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if self.state.is_symlink():
|
||||
raise ValueError('Unsafe OTA state directory')
|
||||
with contextlib.ExitStack() as stack:
|
||||
stream = stack.enter_context((self.state / 'lock').open('a'))
|
||||
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
if self.root == Path('/'):
|
||||
if (self.root / '.e5-update/request').exists() or (self.root / '.e5-update/request.ready').exists():
|
||||
raise ValueError('A full system update is pending')
|
||||
paths = ['run/e5-part-update.lock', 'run/e5-upgrade/lock'] if (self.root / 'etc/e5/release.json').exists() else ['run/mu300-update/lock']
|
||||
for name in paths:
|
||||
target = self.path(name)
|
||||
target.parent.mkdir(mode=0o700, exist_ok=True)
|
||||
if target.is_symlink() or target.exists() and (not target.is_file() or target.stat().st_nlink != 1):
|
||||
raise ValueError('Unsafe shared upgrade lock')
|
||||
held = stack.enter_context(target.open('a'))
|
||||
fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
yield
|
||||
|
||||
def identity(self):
|
||||
current = self.state / 'current.json'
|
||||
if current.exists():
|
||||
return json.loads(current.read_text())
|
||||
for family in ('e5', 'mu300'):
|
||||
path = self.root / ('etc/' + family + '/release.json')
|
||||
if path.is_file():
|
||||
m = json.loads(path.read_text())
|
||||
return dict(family=family, profile=m['profile'], version=m['image_version'],
|
||||
kernel_release=m['kernel_release'])
|
||||
raise ValueError('Missing release identity; use full installer once')
|
||||
|
||||
def status(self):
|
||||
journal = self.state / 'journal.json'
|
||||
return dict(identity=self.identity(), transaction=json.loads(journal.read_text()) if journal.exists() else None)
|
||||
|
||||
def inspect(self, patch):
|
||||
m = patch.manifest
|
||||
identity = self.identity()
|
||||
for key, expected in (('family', m['family']), ('profile', m['profile']),
|
||||
('version', m['base_version']), ('kernel_release', m['kernel_release'])):
|
||||
if identity.get(key) != expected:
|
||||
raise ValueError('Device/base mismatch: ' + key)
|
||||
if self.root == Path('/') and os.uname().release != m['kernel_release']:
|
||||
raise ValueError('Running kernel differs from release identity')
|
||||
conflicts, backup, incoming = [], 0, 0
|
||||
package_conflicts = []
|
||||
db = self.root / 'lib/apk/db/installed'
|
||||
installed = package_versions(db.read_bytes()) if db.is_file() else {}
|
||||
owned = {'luci-app-t551m', 'luci-app-mu300'}
|
||||
for name, expected in m.get('base_packages', {}).items():
|
||||
actual = installed.get(name)
|
||||
if name in owned and actual:
|
||||
actual = dict(actual, V=expected['V'])
|
||||
if actual != expected:
|
||||
package_conflicts.append(name)
|
||||
for op in m['operations']:
|
||||
actual = descriptor(self.path(op['path']))
|
||||
if actual != op['before']:
|
||||
conflicts.append(op['path'])
|
||||
if actual and actual['kind'] == 'file':
|
||||
backup += actual['size']
|
||||
if op['after'] and op['after']['kind'] == 'file':
|
||||
incoming += op['after']['size']
|
||||
required = backup + incoming + (16 << 20)
|
||||
free = shutil.disk_usage(self.root).free
|
||||
return dict(id=patch.id, manifest=m, conflicts=conflicts, package_conflicts=package_conflicts,
|
||||
required_bytes=required, free_bytes=free,
|
||||
applicable=not conflicts and not package_conflicts and free >= required)
|
||||
|
||||
def install_descriptor(self, name, value, source=None):
|
||||
path = self.path(name)
|
||||
if value is None:
|
||||
if path.exists() or path.is_symlink():
|
||||
path.unlink()
|
||||
sync_dir(path.parent)
|
||||
return
|
||||
# All new parents have explicit directory operations; never invent root
|
||||
# ownership/mode for an existing user tree.
|
||||
if not path.parent.is_dir():
|
||||
raise ValueError('Missing parent directory: ' + name)
|
||||
if value['kind'] == 'dir':
|
||||
path.mkdir(exist_ok=True)
|
||||
else:
|
||||
tmp = path.with_name('.' + path.name + '.unisoc-ota-new')
|
||||
if tmp.exists() or tmp.is_symlink():
|
||||
raise ValueError('Temporary path already exists: ' + str(tmp))
|
||||
try:
|
||||
if value['kind'] == 'symlink':
|
||||
os.symlink(value['target'], tmp)
|
||||
else:
|
||||
with tmp.open('xb') as stream:
|
||||
shutil.copyfileobj(source, stream, 1 << 20)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
if value['kind'] != 'symlink':
|
||||
os.chmod(tmp, value['mode'])
|
||||
os.chown(tmp, value['uid'], value['gid'], follow_symlinks=False)
|
||||
for key, encoded in value.get('xattrs', {}).items():
|
||||
os.setxattr(tmp, key, base64.b64decode(encoded), follow_symlinks=False)
|
||||
if descriptor(tmp) != value:
|
||||
raise ValueError('Temporary file verification failed: ' + name)
|
||||
os.replace(tmp, path)
|
||||
finally:
|
||||
if tmp.exists() or tmp.is_symlink():
|
||||
tmp.unlink()
|
||||
if value['kind'] == 'dir':
|
||||
os.chmod(path, value['mode'])
|
||||
os.chown(path, value['uid'], value['gid'])
|
||||
wanted = value.get('xattrs', {})
|
||||
for key in os.listxattr(path, follow_symlinks=False):
|
||||
if key not in wanted:
|
||||
os.removexattr(path, key, follow_symlinks=False)
|
||||
for key, encoded in wanted.items():
|
||||
os.setxattr(path, key, base64.b64decode(encoded), follow_symlinks=False)
|
||||
sync_dir(path.parent)
|
||||
|
||||
def recover(self):
|
||||
journal = self.state / 'journal.json'
|
||||
if not journal.exists():
|
||||
return {'status': 'idle'}
|
||||
data = json.loads(journal.read_text())
|
||||
if data['status'] not in ('applying', 'rolling_back'):
|
||||
return data
|
||||
data['status'] = 'rolling_back'
|
||||
atomic_json(journal, data)
|
||||
operations = json.loads((self.state / data['backup'] / 'plan.json').read_text())
|
||||
for i in reversed(range(data['started'])):
|
||||
op = operations[i]
|
||||
old = op['before']
|
||||
path = self.path(op['path'])
|
||||
tmp = path.with_name('.' + path.name + '.unisoc-ota-new')
|
||||
if tmp.exists() or tmp.is_symlink():
|
||||
tmp.unlink()
|
||||
sync_dir(tmp.parent)
|
||||
if old is None and op['after']['kind'] == 'dir':
|
||||
# Only our empty new directory may disappear; keep user files.
|
||||
if path.exists():
|
||||
path.rmdir()
|
||||
sync_dir(path.parent)
|
||||
elif old and old['kind'] == 'file':
|
||||
backup = self.state / data['backup'] / str(i)
|
||||
with backup.open('rb') as stream:
|
||||
if digest(stream) != old['sha256']:
|
||||
raise ValueError('Rollback backup corrupt; do not reboot')
|
||||
stream.seek(0)
|
||||
self.install_descriptor(op['path'], old, stream)
|
||||
else:
|
||||
self.install_descriptor(op['path'], old)
|
||||
previous = data.get('previous_identity')
|
||||
if previous:
|
||||
atomic_json(self.state / 'current.json', previous)
|
||||
elif (self.state / 'current.json').exists():
|
||||
(self.state / 'current.json').unlink()
|
||||
sync_dir(self.state)
|
||||
data['status'] = 'rolled_back'
|
||||
atomic_json(journal, data)
|
||||
return data
|
||||
|
||||
def apply(self, patch, progress=lambda *_: None):
|
||||
with self.lock():
|
||||
self.recover()
|
||||
check = self.inspect(patch)
|
||||
if not check['applicable']:
|
||||
raise ValueError('Conflicting files/packages or insufficient space: ' + ', '.join((check['conflicts'] + check['package_conflicts'])[:20]))
|
||||
journal = self.state / 'journal.json'
|
||||
# Preserve the preceding transaction's recovery data until the new
|
||||
# journal is durable. A crash during backup must not invalidate it.
|
||||
backup = self.state / ('backup-' + str(time.time_ns()))
|
||||
backup.mkdir(mode=0o700)
|
||||
ops = sorted(patch.manifest['operations'], key=lambda o: (o['path'].count('/'), o['path']))
|
||||
data = dict(id=patch.id, status='preparing', started=0, total=len(ops), backup=backup.name,
|
||||
previous_identity=json.loads((self.state / 'current.json').read_text())
|
||||
if (self.state / 'current.json').exists() else None,
|
||||
target_version=patch.manifest['target_version'])
|
||||
# The large immutable plan is written once, not rewritten for every
|
||||
# file. A compact count journal keeps update writes O(n), not O(n²).
|
||||
atomic_json(backup / 'plan.json', ops)
|
||||
for i, op in enumerate(ops):
|
||||
if op['before'] and op['before']['kind'] == 'file':
|
||||
with self.path(op['path']).open('rb') as src, (backup / str(i)).open('xb') as dst:
|
||||
shutil.copyfileobj(src, dst, 1 << 20)
|
||||
dst.flush()
|
||||
os.fsync(dst.fileno())
|
||||
with (backup / str(i)).open('rb') as verified:
|
||||
if digest(verified) != op['before']['sha256']:
|
||||
raise ValueError('Backup verification failed: ' + op['path'])
|
||||
sync_dir(backup)
|
||||
data['status'] = 'applying'
|
||||
atomic_json(journal, data)
|
||||
try:
|
||||
for i, op in enumerate(ops):
|
||||
# Recheck at commit time; a concurrent user edit is a conflict.
|
||||
if descriptor(self.path(op['path'])) != op['before']:
|
||||
raise ValueError('File changed during update: ' + op['path'])
|
||||
data['started'] = i + 1
|
||||
atomic_json(journal, data)
|
||||
value = op['after']
|
||||
with contextlib.ExitStack() as stack:
|
||||
source = stack.enter_context(patch.archive.open('blobs/' + value['sha256'])) if value and value['kind'] == 'file' else None
|
||||
self.install_descriptor(op['path'], value, source)
|
||||
if descriptor(self.path(op['path'])) != value:
|
||||
raise ValueError('Written file verification failed: ' + op['path'])
|
||||
progress(i + 1, len(ops), op['path'])
|
||||
identity = dict(family=patch.manifest['family'], profile=patch.manifest['profile'],
|
||||
version=patch.manifest['target_version'], kernel_release=patch.manifest['kernel_release'])
|
||||
atomic_json(self.state / 'current.json', identity)
|
||||
data['status'] = 'complete'
|
||||
atomic_json(journal, data)
|
||||
except BaseException:
|
||||
self.recover()
|
||||
raise
|
||||
# Only the latest transaction is exposed for manual rollback.
|
||||
# Remove our older numbered recovery directories after the new
|
||||
# committed journal is durable, never during backup preparation.
|
||||
for previous in self.state.glob('backup-*'):
|
||||
if previous != backup and re.fullmatch(r'backup-[0-9]+', previous.name) and previous.is_dir() and not previous.is_symlink():
|
||||
with contextlib.suppress(OSError):
|
||||
shutil.rmtree(previous)
|
||||
return dict(status='complete', version=identity['version'], reboot_required=True, id=patch.id)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('command', choices=('inspect', 'apply', 'recover', 'status', 'rollback'))
|
||||
p.add_argument('package', nargs='?')
|
||||
p.add_argument('--root', default='/')
|
||||
args = p.parse_args()
|
||||
engine = Engine(args.root)
|
||||
if args.command in ('recover', 'rollback'):
|
||||
with engine.lock():
|
||||
if args.command == 'rollback':
|
||||
journal = engine.state / 'journal.json'
|
||||
data = json.loads(journal.read_text())
|
||||
if data['status'] != 'complete':
|
||||
raise ValueError('No completed update to roll back')
|
||||
# Never clobber changes made since the hotfix was applied.
|
||||
for op in json.loads((engine.state / data['backup'] / 'plan.json').read_text()):
|
||||
if descriptor(engine.path(op['path'])) != op['after']:
|
||||
raise ValueError('Rollback conflict: ' + op['path'])
|
||||
data['status'] = 'rolling_back'
|
||||
atomic_json(journal, data)
|
||||
result = engine.recover()
|
||||
elif args.command == 'status':
|
||||
result = engine.status()
|
||||
else:
|
||||
with Patch(args.package) as patch:
|
||||
result = engine.apply(patch) if args.command == 'apply' else engine.inspect(patch)
|
||||
print(json.dumps(result, ensure_ascii=True))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception as error:
|
||||
print(json.dumps({'error': str(error)}))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/python3
|
||||
"""Fixed RPC surface. Detached worker survives browser/SSH disconnection."""
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
|
||||
from engine import Engine, Patch, atomic_json
|
||||
|
||||
ENGINE = '/usr/lib/unisoc-ota/engine.py'
|
||||
STATE = Path('/etc/unisoc-ota')
|
||||
UPLOAD = STATE / 'upload.ota'
|
||||
JOB = STATE / 'job.json'
|
||||
METHODS = {'status': {}, 'inspect': {}, 'start': {'id':''}, 'rollback': {}, 'reboot': {}}
|
||||
|
||||
|
||||
def worker(command, path=None, expected_id=None):
|
||||
STATE.mkdir(mode=0o700, exist_ok=True)
|
||||
with (STATE / 'job.lock').open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
patch_id = None
|
||||
if path:
|
||||
candidate = STATE / ('candidate-' + str(time.time_ns()) + '.ota')
|
||||
source = Path(path)
|
||||
before = source.stat()
|
||||
if before.st_size > (2 << 30) or shutil.disk_usage(STATE).free < before.st_size + (16 << 20):
|
||||
raise ValueError('Insufficient staging space or excessive upload size')
|
||||
try:
|
||||
with source.open('rb') as src, candidate.open('xb') as dest:
|
||||
remaining = before.st_size
|
||||
while remaining:
|
||||
block = src.read(min(1 << 20, remaining))
|
||||
if not block:
|
||||
raise ValueError('Upload changed during staging')
|
||||
dest.write(block)
|
||||
remaining -= len(block)
|
||||
dest.flush()
|
||||
os.fsync(dest.fileno())
|
||||
with Patch(candidate) as patch:
|
||||
if patch.id != expected_id:
|
||||
raise ValueError('Upload differs from the patch you reviewed; inspect again')
|
||||
check = Engine().inspect(patch)
|
||||
if not check['applicable']:
|
||||
raise ValueError('File conflict or insufficient space')
|
||||
frozen = STATE / ('reviewed-' + patch.id + '.ota')
|
||||
patch_id = patch.id
|
||||
os.replace(candidate, frozen)
|
||||
after = source.stat()
|
||||
if (after.st_dev,after.st_ino,after.st_mtime_ns,after.st_size) == (before.st_dev,before.st_ino,before.st_mtime_ns,before.st_size):
|
||||
source.unlink()
|
||||
path = str(frozen)
|
||||
finally:
|
||||
candidate.unlink(missing_ok=True)
|
||||
# Parent holds the lock until a durable running marker is written, then
|
||||
# detaches a process which inherits it. Its close releases the lock.
|
||||
atomic_json(JOB, {'status': 'running', 'command': command, 'patch_id': patch_id})
|
||||
subprocess.Popen([sys.executable, __file__, '_worker', command, path or ''],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, start_new_session=True,
|
||||
pass_fds=(lock.fileno(),))
|
||||
return {'status': 'running'}
|
||||
|
||||
|
||||
def dispatch(method, path=None, review_id=None):
|
||||
STATE.mkdir(mode=0o700, exist_ok=True)
|
||||
if method == 'status':
|
||||
result = Engine().status()
|
||||
result['job'] = json.loads(JOB.read_text()) if JOB.exists() else {'status': 'idle'}
|
||||
if result['job']['status'] == 'running':
|
||||
with (STATE / 'job.lock').open('a') as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
pass
|
||||
else:
|
||||
transaction = result.get('transaction') or {}
|
||||
complete = (transaction.get('status') == 'complete' and transaction.get('id') == result['job'].get('patch_id')) if result['job'].get('command') == 'apply' else transaction.get('status') == 'rolled_back'
|
||||
result['job'] = dict(status='complete' if complete else 'failed',
|
||||
result={'error': 'Interrupted transaction; recovery status: ' + transaction.get('status', 'unknown')} if not complete else {})
|
||||
atomic_json(JOB, result['job'])
|
||||
return result
|
||||
if method == 'inspect':
|
||||
with Patch(UPLOAD) as patch:
|
||||
return Engine().inspect(patch)
|
||||
if method == 'start':
|
||||
path = Path(path) if path else UPLOAD
|
||||
# CLI may select only a pre-reviewed, content-addressed upload on the
|
||||
# same persistent filesystem. rpcd callers cannot supply arbitrary paths.
|
||||
if path.parent != STATE or path.is_symlink() or path.suffix != '.ota':
|
||||
raise ValueError('Invalid OTA upload path')
|
||||
if review_id is None:
|
||||
matched = re.fullmatch(r'upload-([a-f0-9]{64})\.ota', path.name)
|
||||
review_id = matched[1] if matched else None
|
||||
if not isinstance(review_id,str) or not re.fullmatch(r'[a-f0-9]{64}',review_id):
|
||||
raise ValueError('Inspect this patch before applying')
|
||||
return worker('apply', str(path), review_id)
|
||||
if method == 'rollback':
|
||||
return worker('rollback')
|
||||
if method == 'reboot':
|
||||
with (STATE / 'job.lock').open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
journal = STATE / 'journal.json'
|
||||
if journal.exists() and json.loads(journal.read_text())['status'] in ('applying', 'rolling_back'):
|
||||
raise ValueError('Update recovery is pending')
|
||||
os.sync()
|
||||
subprocess.Popen(['/sbin/reboot'], stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
return {'status': 'rebooting'}
|
||||
raise ValueError('Unknown OTA command')
|
||||
|
||||
|
||||
def main():
|
||||
if sys.argv[1:2] == ['_worker']:
|
||||
command, path = sys.argv[2:4]
|
||||
args = [sys.executable, ENGINE, command] + ([path] if path else [])
|
||||
result = subprocess.run(args, capture_output=True, text=True)
|
||||
try:
|
||||
detail = json.loads(result.stdout)
|
||||
except ValueError:
|
||||
detail = {'error': (result.stderr or result.stdout)[-4000:]}
|
||||
atomic_json(JOB, dict(status='failed' if result.returncode else 'complete', result=detail))
|
||||
if path and result.returncode == 0:
|
||||
uploaded = Path(path)
|
||||
if uploaded.parent == STATE and re.fullmatch(r'reviewed-[a-f0-9]{64}\.ota', uploaded.name):
|
||||
uploaded.unlink(missing_ok=True)
|
||||
return
|
||||
if sys.argv[1:] == ['list']:
|
||||
print(json.dumps(METHODS))
|
||||
return
|
||||
if sys.argv[1:2] == ['call']:
|
||||
# Standard rpcd plugins receive arguments via stdin. No dynamic command.
|
||||
args = json.loads(sys.stdin.read(4096) or '{}')
|
||||
method, path = sys.argv[2], None
|
||||
if method == 'start' and isinstance(args,dict) and set(args) == {'id'}:
|
||||
review_id = args['id']
|
||||
elif args:
|
||||
raise ValueError('Unexpected RPC arguments')
|
||||
else:
|
||||
review_id = None
|
||||
else:
|
||||
method = sys.argv[1]
|
||||
path = sys.argv[2] if len(sys.argv) == 3 else None
|
||||
review_id = None
|
||||
print(json.dumps(dispatch(method, path, review_id)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception as e:
|
||||
print(json.dumps({'error': str(e)}))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,2 @@
|
||||
#!/bin/sh
|
||||
exec python3 /usr/lib/unisoc-ota/rpc.py "$@"
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"admin/system/unisoc-ota": {
|
||||
"title": "系统补丁 / System patches",
|
||||
"order": 65,
|
||||
"action": {"type": "view", "path": "system/unisoc-ota"},
|
||||
"depends": {"acl": ["luci-app-unisoc-ota"]}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"luci-app-unisoc-ota": {
|
||||
"description": "Import reviewed system hotfixes and retain rollback",
|
||||
"read": {"ubus": {"unisoc-ota": ["status", "inspect"]}},
|
||||
"write": {
|
||||
"ubus": {"unisoc-ota": ["start", "rollback", "reboot"]},
|
||||
"file": {"/etc/unisoc-ota/upload.ota": ["write"]}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,28 @@
|
||||
#!/bin/sh
|
||||
# MU300: OpenWrt firmware images (armsr/armv8) are whole-disk images with their own kernel. Flashing one here would
|
||||
# overwrite the eMMC partition table and bootloaders and brick the device, so flashing is refused.
|
||||
# Configuration backups (-b, -l, --create-backup, --list-backup) still work through the original sysupgrade.
|
||||
for a in "$@"; do
|
||||
case "$a" in
|
||||
-b|--create-backup|-l|--list-backup) exec /sbin/sysupgrade.openwrt "$@" ;;
|
||||
esac
|
||||
done
|
||||
echo "sysupgrade is disabled on the MU300: firmware images would overwrite the eMMC." >&2
|
||||
echo "Update packages with 'apk upgrade' (not kernel/kmod-*) or reinstall with install.sh from the host." >&2
|
||||
# Firmware replacement uses the project updater. Keep only configuration tools.
|
||||
backup_operation() {
|
||||
mode=
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
-b|--create-backup|-r|--restore-backup)
|
||||
[ -z "$mode" ] && [ "$#" -ge 2 ] && [ -n "$2" ] || return 1
|
||||
mode=$1
|
||||
shift 2
|
||||
;;
|
||||
-l|--list-backup)
|
||||
[ -z "$mode" ] || return 1
|
||||
mode=$1
|
||||
shift
|
||||
;;
|
||||
-k|-u|-c|-o|-p|-v|-q) shift ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$mode" ]
|
||||
}
|
||||
if backup_operation "$@"; then
|
||||
exec /sbin/sysupgrade.openwrt "$@"
|
||||
fi
|
||||
echo "Stock firmware flashing is disabled; use the project OTA or desktop updater." >&2
|
||||
echo "Configuration backup, restore and listing remain available." >&2
|
||||
exit 1
|
||||
@@ -14,17 +14,26 @@
|
||||
export PATH="$PATH:/opt/mu300/busybox-bin"
|
||||
set -eu
|
||||
CONF=/etc/mu300/default-boot
|
||||
LINUX_SLOT=$(cat /run/mu300/linux-slot 2>/dev/null || echo b)
|
||||
case $LINUX_SLOT in a|b) ;; *) echo 'invalid Linux slot' >&2; exit 1 ;; esac
|
||||
LINUX_SLOT=$(cat /run/mu300/linux-slot 2>/dev/null || true)
|
||||
BC_ANDROID=/run/mu300/misc-bc-android.bin
|
||||
BC_LINUX=/run/mu300/misc-bc-linux-trial.bin
|
||||
if [ "$LINUX_SLOT" = b ]; then
|
||||
[ -s "$BC_ANDROID" ] || BC_ANDROID=/run/mu300/misc-bc-slot-a.bin
|
||||
[ -s "$BC_LINUX" ] || BC_LINUX=/run/mu300/misc-bc-slot-b-trial.bin
|
||||
fi
|
||||
[ -s "$BC_LINUX" ] || BC_LINUX=/run/mu300/misc-bc-slot-b-trial.bin
|
||||
case "$(dd if="$BC_LINUX" bs=1 count=2 2>/dev/null)" in
|
||||
_a) detected_slot=a; android_slot=b ;;
|
||||
_b) detected_slot=b; android_slot=a ;;
|
||||
*) echo 'Linux slot metadata unavailable; boot control unchanged' >&2; exit 1 ;;
|
||||
esac
|
||||
[ -z "$LINUX_SLOT" ] || [ "$LINUX_SLOT" = "$detected_slot" ] || {
|
||||
echo 'Conflicting Linux slot metadata; boot control unchanged' >&2; exit 1;
|
||||
}
|
||||
LINUX_SLOT=$detected_slot
|
||||
[ -s "$BC_ANDROID" ] || BC_ANDROID=/run/mu300/misc-bc-slot-$android_slot.bin
|
||||
[ -s "$BC_ANDROID" ] && [ -s "$BC_LINUX" ] || {
|
||||
echo 'boot control blocks for the active slot are unavailable' >&2; exit 1;
|
||||
}
|
||||
[ "$(dd if="$BC_ANDROID" bs=1 count=2 2>/dev/null)" = "_$android_slot" ] || {
|
||||
echo 'Conflicting Android/Linux slot metadata; boot control unchanged' >&2; exit 1;
|
||||
}
|
||||
MISC=$(cat /run/mu300/misc-dev 2>/dev/null || readlink -f /dev/block/by-name/misc)
|
||||
DEFAULT_ATTEMPTS=5
|
||||
|
||||
|
||||
@@ -5,15 +5,21 @@
|
||||
# Stock onSimStatusChanged() treats these ECIND values as a request to read
|
||||
# CPIN. They do NOT prove removal: SIM errors and PIN changes also use them.
|
||||
mu300_sim_changed() {
|
||||
local slot=$1 line=$2 type value cause extra
|
||||
local slot=$1 line=$2 type value cause extra field
|
||||
case "$slot:$line" in 0:+ECIND:*|1:+ECIND:*) ;; *) return 0 ;; esac
|
||||
case "$line" in '+ECIND: 3,'*|'+ECIND:3,'*) ;; *) return 0 ;; esac
|
||||
line=${line#*:}
|
||||
line=$(printf '%s' "$line" | tr -d ' \r\t')
|
||||
# Ready can be 3,0,0,1 after a transient SIM-busy indication. The stock
|
||||
# RIL ignores numeric metadata after cause; CPIN confirms our own slot.
|
||||
case "$line" in ''|,*|*,|*,,*|*[!0-9,]*) return 0 ;; esac
|
||||
for field in $(printf '%s' "$line" | tr ',' ' '); do
|
||||
[ "${#field}" -le 10 ] && [ "$field" -le 4294967295 ] || return 0
|
||||
done
|
||||
IFS=, read -r type value cause extra <<EOF
|
||||
$line
|
||||
EOF
|
||||
[ "$type" = 3 ] && [ -z "$extra" ] || return 0
|
||||
[ "$type" = 3 ] || return 0
|
||||
case "$value:$cause" in
|
||||
0:|2:|100:|4:|0:[0-9]*|2:[0-9]*|100:[0-9]*|4:[0-9]*|1:2|1:34|1:25|1:1|1:7) ;;
|
||||
*) return 0 ;;
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Exercise the real manual cell form with isolated RPC; never sends modem commands."""
|
||||
from pathlib import Path
|
||||
import argparse
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--repo',type=Path)
|
||||
a=parser.parse_args()
|
||||
repo=a.repo or next(p for p in Path(__file__).resolve().parents if (p/'openwrt').is_dir())
|
||||
app='luci-app-t551m' if (repo/'openwrt/luci-app-t551m').exists() else 'luci-app-mu300'
|
||||
res=repo/'openwrt'/app/'htdocs/luci-static/resources'
|
||||
common=(res/'mu300/common.js').read_text(encoding='utf8')
|
||||
locks=(res/'view/mu300/locks.js').read_text(encoding='utf8')
|
||||
cases=0
|
||||
with sync_playwright() as p:
|
||||
browser=p.chromium.launch()
|
||||
for width in (320,1280):
|
||||
for lang in ('zh','en','tr'):
|
||||
page=browser.new_page(viewport={'width':width,'height':900})
|
||||
errors=[];page.on('pageerror',lambda e:errors.append(str(e)))
|
||||
page.set_content('<html><body><main id="app"></main></body></html>')
|
||||
page.evaluate('''([common,locks,lang])=>{
|
||||
const L={env:{lang},resolveDefault:p=>Promise.resolve(p).catch(()=>null)},base={extend:x=>x};
|
||||
window.M=new Function('rpc','baseclass','L',common)({declare:()=>()=>Promise.resolve({})},base,L);
|
||||
window.slot='0';window.requests=[];window.notes=[];
|
||||
M.simSlot=M.selectedSlot=()=>slot;M.simSelector=M.watchSms=()=>{};
|
||||
M.callLockSet=(kind,value)=>{requests.push({kind,value,slot});return new Promise(r=>window.finish=r);};
|
||||
window.view=new Function('view','poll','R','M','L','AutoMode',locks)(base,{add(){},remove(){}},{poll:()=>()=>{}},M,L,{attach:()=>({update(){},reload(){}})});
|
||||
view.refresh=view.loadServing=view.loadServingMeta=()=>Promise.resolve();
|
||||
view.note=(text,type)=>notes.push({text,type});
|
||||
view.readback=(r,btn)=>{M.busy(btn,false);view._applying=false;};
|
||||
document.querySelector('#app').append(view.render());
|
||||
}''',[common,locks,lang])
|
||||
page.locator('.mud-manual-cell summary').click()
|
||||
form=page.locator('#mud-lock-manual-form')
|
||||
if lang!='zh':assert not any('\u3400'<=c<='\u9fff' for c in form.inner_text())
|
||||
for selector in ('#mud-lock-manual-rat','#mud-lock-manual-frequency','#mud-lock-manual-pci','#mud-lock-manual-apply'):
|
||||
b=page.locator(selector).bounding_box();assert b and b['x']>=0 and b['x']+b['width']<=width+1,(width,selector,b)
|
||||
def fill(rat,freq,pci):
|
||||
page.locator('#mud-lock-manual-rat').select_option(rat)
|
||||
page.locator('#mud-lock-manual-frequency').fill(freq)
|
||||
page.locator('#mud-lock-manual-pci').fill(pci)
|
||||
for rat,freq,pci in [('lte','','1'),('lte','1',''),('lte','-1','0'),('lte','1e3','1'),('lte','1.5','0'),('lte','262144','0'),('lte','123','504'),('nr','0','0'),('nr','3279166','0'),('nr','1','1008')]:
|
||||
fill(rat,freq,pci);page.locator('#mud-lock-manual-apply').click()
|
||||
assert page.locator('.mud-dlg-wrap').count()==0
|
||||
assert page.evaluate('requests.length')==0
|
||||
assert page.evaluate("notes.at(-1).type")== 'error'
|
||||
cases+=1
|
||||
for rat,freq,pci in [('lte','0','0'),('lte','262143','503'),('nr','1','0'),('nr','3279165','1007'),('nr',' 0627264 ',' 0393 ')]:
|
||||
fill(rat,freq,pci);page.locator('#mud-lock-manual-apply').click()
|
||||
assert page.locator('.mud-dlg-wrap').count()==1
|
||||
assert page.evaluate('requests.length')==0
|
||||
page.evaluate("document.querySelector('#mud-lock-manual-form').dispatchEvent(new Event('submit',{cancelable:true}))")
|
||||
assert page.locator('.mud-dlg-wrap').count()==1
|
||||
page.keyboard.press('Escape');page.wait_for_function('!view._manualConfirm')
|
||||
assert page.evaluate('requests.length')==0
|
||||
page.locator('#mud-lock-manual-apply').click();page.locator('.mud-dlg-btns [data-r="1"]').click()
|
||||
page.wait_for_function('requests.length===1')
|
||||
assert page.evaluate('requests[0]')=={'kind':'cell','value':rat+':'+str(int(freq))+','+str(int(pci)),'slot':'0'}
|
||||
page.evaluate("document.querySelector('#mud-lock-manual-form').dispatchEvent(new Event('submit',{cancelable:true}))");assert page.evaluate('requests.length')==1
|
||||
page.evaluate("finish({ok:1});requests=[]");page.wait_for_function('!view._applying')
|
||||
cases+=1
|
||||
fill('nr','627264','393')
|
||||
page.locator('#mud-lock-manual-apply').click();page.evaluate("slot='1'")
|
||||
page.locator('.mud-dlg-btns [data-r="1"]').click();page.wait_for_function('!view._manualConfirm')
|
||||
assert page.evaluate('requests.length')==0,'confirmation crossed SIM slots'
|
||||
page.locator('#mud-lock-manual-apply').click();page.locator('.mud-dlg-btns [data-r="1"]').click()
|
||||
page.wait_for_function('requests.length===1');assert page.evaluate('requests[0].slot')=='1'
|
||||
page.evaluate("finish({ok:1});requests=[]");page.wait_for_function('!view._applying')
|
||||
page.locator('#mud-lock-manual-apply').click();page.evaluate('view.unload()')
|
||||
page.locator('.mud-dlg-btns [data-r="1"]').click();page.wait_for_function('!view._manualConfirm')
|
||||
assert page.evaluate('requests.length')==0,'request after unload'
|
||||
assert not errors,errors
|
||||
page.close()
|
||||
browser.close()
|
||||
print('PASS',repo.name,cases,'manual-cell validation/confirmation cases; both SIM slots, cancellation, duplicates, unload, translations and phone/desktop layout')
|
||||
@@ -11,6 +11,7 @@ function fixture(on) {
|
||||
}};
|
||||
const M = {
|
||||
confirmBox(title,body,options) { dialogs.push({title,body,options}); return new Promise(resolve => { decide=resolve; }); },
|
||||
choiceBox(title,body,choices) { dialogs.push({title,body,choices}); return new Promise(resolve => { decide=resolve; }); },
|
||||
callAct(op,arg) { requests.push([op,arg]); return new Promise(resolve => { complete=resolve; }); },
|
||||
busy(btn,on) { btn.busy=on; }, toast(message,options){toasts.push({message,options});}
|
||||
};
|
||||
@@ -28,7 +29,7 @@ function fixture(on) {
|
||||
['data',true,'data','down'], ['data',false,'data','up'],
|
||||
['radio',true,'radio','off'], ['radio',false,'radio','on'],
|
||||
['wifi',true,'wifi','off'], ['wifi',false,'wifi','on'],
|
||||
['modem',true,'modem-reset',null], ['reboot',true,'reboot',null], ['android',true,'os','android']
|
||||
['modem',true,'modem-reset',null], ['android',true,'os','android']
|
||||
];
|
||||
for (const [id,on,op,arg] of cases) {
|
||||
for (const decision of ['cancel','confirm','unload','detach']) {
|
||||
@@ -54,6 +55,31 @@ function fixture(on) {
|
||||
assert(!f.view._quickPending,id+' left confirmation locked');
|
||||
}
|
||||
}
|
||||
for (const op of ['poweroff','reboot']) {
|
||||
for (const decision of ['cancel','confirm','unload','detach','error']) {
|
||||
const f=fixture(true), button=f.buttons['#mud-btn-reboot'];
|
||||
button.onclick();
|
||||
assert.equal(f.dialogs.length,1);
|
||||
assert.deepEqual(f.dialogs[0].choices.map(c=>c.value),[undefined,'poweroff','reboot']);
|
||||
assert.equal(f.requests.length,0,'power request before choosing');
|
||||
button.onclick();f.buttons['#mud-btn-data'].onclick();
|
||||
assert.equal(f.dialogs.length,1,'duplicate power chooser');
|
||||
if(decision==='unload') f.view.unload();
|
||||
if(decision==='detach') f.root.isConnected=false;
|
||||
f.decide(decision==='cancel'?undefined:op);await tick();
|
||||
if(decision==='confirm'||decision==='error') {
|
||||
assert.deepEqual(f.requests,[[op,null]],'wrong power operation');
|
||||
button.onclick();assert.equal(f.requests.length,1);
|
||||
assert(button.busy && f.view._quickPending);
|
||||
f.complete(decision==='error'?{ok:0,error:'unavailable'}:{ok:1,started:1,op});await tick();
|
||||
assert(!button.busy && !f.view._quickPending,'power action left busy');
|
||||
assert.equal(f.toasts.at(-1).options.type,decision==='error'?'error':'success');
|
||||
} else {
|
||||
assert.equal(f.requests.length,0,'power executed after '+decision);
|
||||
assert(!f.view._quickPending);
|
||||
}
|
||||
}
|
||||
}
|
||||
for(const outcome of ['done','error','leave']) {
|
||||
const f=fixture(true),b=f.buttons['#mud-btn-radio'];
|
||||
b.onclick();f.decide(true);await tick();
|
||||
@@ -75,5 +101,5 @@ function fixture(on) {
|
||||
if(state==='busy')f.view._wifiBusy=true;
|
||||
f.buttons['#mud-btn-wifi'].onclick(); assert.equal(f.dialogs.length,0,state);
|
||||
}
|
||||
console.log('PASS: all six quick controls confirmed; on/off, cancellation, leaving view, duplicate clicks, busy cleanup and fixed targets');
|
||||
console.log('PASS: quick controls and power chooser; shutdown/restart, cancellation, view lifecycle, duplicates, RPC errors and busy cleanup');
|
||||
})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
@@ -44,7 +44,7 @@ function transport(info, options = {}) {
|
||||
const fn = async command => {
|
||||
commands.push(command);
|
||||
if (command.includes('echo SLOT=')) return {success: true, content:
|
||||
`SLOT=${options.slot === undefined ? '_' + info.slot : options.slot}\nMODEL=${options.model || (info.family === 'e5' ? 'E5' : 'MU300')}\nDEVICE=${options.device || 'MU300'}\nPLATFORM=${options.platform || 'ums9620'}\nUNLOCKED=orange`};
|
||||
`SLOT=${options.slot === undefined ? '_' + info.slot : options.slot}\nMODEL=${options.model || (info.family === 'e5' ? 'E5' : 'MU300')}\nDEVICE=${options.device || 'MU300'}\nPLATFORM=${options.platform || 'ums9620'}\nUNLOCKED=${options.unlocked || 'orange'}`};
|
||||
if (command.includes('blockdev --getsize64')) return {success: true, content: String(info.size)};
|
||||
if (command.includes('if=/dev/block/by-name/misc')) return {success: true, content: options.live || info.live};
|
||||
if (command.includes('if=/dev/block/by-name/boot_' + info.other)) return {success: true, content: command.includes('bs=512') ? info.tail : info.head};
|
||||
@@ -83,8 +83,8 @@ test('recognition accepts current boot families and refuses stock, corrupt and p
|
||||
assert.throws(() => api.inspectBoot(info.head, info.tail, 2 ** 20, family));
|
||||
}
|
||||
});
|
||||
test('probe E5 family A and MU family A/B with actual getprop slot', async () => {
|
||||
for (const [family, models, slots] of [['e5', ['E5', 'T551M', 'VIPME M8'], ['a']], ['mu300', ['MU300', 'F50', 'U30AIR', 'V50'], ['a', 'b']]]) {
|
||||
test('probe every supported family in either Android slot using actual getprop slot', async () => {
|
||||
for (const [family, models, slots] of [['e5', ['E5', 'T551M', 'VIPME M8', 'T512N', 'ZTE 7546N', 'angelcare K1'], ['a', 'b']], ['mu300', ['MU300', 'F50', 'U30AIR', 'V50'], ['a', 'b']]]) {
|
||||
for (const model of models) for (const slot of slots) {
|
||||
const info = fixture(family, slot), tr = transport(info, {model, device: model === 'V50' ? 'MU3351' : model});
|
||||
const result = await load(tr.fn).probe(); assert.equal(result.slot, slot); assert.equal(result.family, family);
|
||||
@@ -92,12 +92,18 @@ test('probe E5 family A and MU family A/B with actual getprop slot', async () =>
|
||||
}
|
||||
}
|
||||
});
|
||||
test('missing current slot never falls back to misc; unsupported models, E5 B and identical boots stop', async () => {
|
||||
test('installed E5-family images do not require an orange verified-boot property', async () => {
|
||||
for (const slot of ['a', 'b']) for (const unlocked of ['green', 'yellow', 'unknown']) {
|
||||
const info = fixture('e5', slot), tr = transport(info, {unlocked, model: 'angelcare K1'});
|
||||
const result = await load(tr.fn).probe(); assert.equal(result.slot, slot); assert.equal(result.family, 'e5');
|
||||
}
|
||||
});
|
||||
|
||||
test('missing current slot never falls back to misc; unsupported models and identical boots stop', async () => {
|
||||
for (const options of [{slot: ''}, {slot: '_c'}, {model: 'FM_U20', device: 'FM_U20'}, {model: 'V50', device: 'MU3351', platform: 'wrong'}, {identical: true}]) {
|
||||
const tr = transport(fixture(), options); await assert.rejects(load(tr.fn).probe());
|
||||
if ('slot' in options) assert.equal(tr.commands.length, 1);
|
||||
}
|
||||
const tr = transport(fixture('e5', 'b')); await assert.rejects(load(tr.fn).probe(), /A 槽/);
|
||||
});
|
||||
function fixtureFiles(root, info) {
|
||||
fs.mkdirSync(path.join(root, 'by'));
|
||||
@@ -121,8 +127,8 @@ function commandFor(root, info, prefix = '') {
|
||||
}
|
||||
const posix = process.platform !== 'win32';
|
||||
for (const shell of ['bash', 'busybox']) {
|
||||
test(`${shell}: real writes change exactly 32 bytes for both families and MU Android B`, {skip: !posix}, () => {
|
||||
for (const [family, slot] of [['e5', 'a'], ['mu300', 'a'], ['mu300', 'b']]) {
|
||||
test(`${shell}: real writes change exactly 32 bytes for both families and either Android slot`, {skip: !posix}, () => {
|
||||
for (const [family, slot] of [['e5', 'a'], ['e5', 'b'], ['mu300', 'a'], ['mu300', 'b']]) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'switch-plugin-'));
|
||||
try {
|
||||
const info = fixture(family, slot), before = fixtureFiles(root, info), script = commandFor(root, info);
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build orchestration boundaries: no compilation, containers or device access."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import zipfile
|
||||
|
||||
TOP = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location('build_release', TOP / 'tools/build-release.py')
|
||||
build = importlib.util.module_from_spec(spec); spec.loader.exec_module(build)
|
||||
|
||||
|
||||
class Layout(unittest.TestCase):
|
||||
def test_installer_defaults_match_native_builder_directories(self):
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
self.assertEqual(build.installer_artifact('windows-x64'), TOP / 'installer/artifacts/windows')
|
||||
self.assertEqual(build.installer_artifact('macos-arm64'), TOP / 'installer/artifacts/macos-arm64')
|
||||
with patch.dict(os.environ, {'OPENWRT_GUI_ARTIFACT': '/verified/windows',
|
||||
'OPENWRT_GUI_MACOS_ARTIFACT': '/verified/mac'}):
|
||||
self.assertEqual(build.installer_artifact('windows-x64'), Path('/verified/windows'))
|
||||
self.assertEqual(build.installer_artifact('macos-arm64'), Path('/verified/mac'))
|
||||
|
||||
def test_registry_covers_every_model_without_copying_or_creating(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
workspace = Path(folder) / 'not-created'
|
||||
common, rows = build.layout(TOP / 'tools/build-layout.json', workspace, build.PROFILES)
|
||||
self.assertEqual(set(rows), set(build.PROFILES))
|
||||
self.assertEqual(rows['mu300-7.2']['kernel'], workspace / 'kernels/mu300-7.2.8')
|
||||
self.assertEqual(common['inputs'], TOP.parent / 'mu300-linux/work')
|
||||
self.assertFalse(workspace.exists())
|
||||
|
||||
def test_missing_inputs_stop_before_any_copy(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder); missing = root / 'missing'
|
||||
with self.assertRaisesRegex(ValueError, 'Missing registered inputs'):
|
||||
build.input_check({'base': missing}, {})
|
||||
self.assertFalse(missing.exists())
|
||||
|
||||
def test_unknown_profile_and_unsafe_workspace(self):
|
||||
with self.assertRaisesRegex(ValueError, 'Unknown'):
|
||||
build.layout(TOP / 'tools/build-layout.json', Path('/tmp/e5-build'), ['other'])
|
||||
with self.assertRaisesRegex(ValueError, 'dedicated'):
|
||||
build.layout(TOP / 'tools/build-layout.json', Path('/'), ['mu300-7.2'])
|
||||
with self.assertRaisesRegex(ValueError, 'C:'):
|
||||
build.layout(TOP / 'tools/build-layout.json', Path('/mnt/c/build'), ['mu300-7.2'])
|
||||
|
||||
|
||||
@unittest.skipIf(os.name == 'nt', 'Linux workspace lock and mount checks')
|
||||
class Ownership(unittest.TestCase):
|
||||
def test_second_owner_is_blocked_and_lock_releases_after_failure(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
workspace = Path(folder)
|
||||
with self.assertRaisesRegex(RuntimeError, 'fixture'):
|
||||
with build.workspace_lock(workspace):
|
||||
with self.assertRaisesRegex(ValueError, 'Another build'):
|
||||
with build.workspace_lock(workspace):self.fail('lock bypass')
|
||||
raise RuntimeError('fixture')
|
||||
with build.workspace_lock(workspace):pass
|
||||
|
||||
def test_only_owned_staging_deleted_caches_and_backups_remain(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
for name in ['sources/kernel', 'objects/e5', 'cache/input', 'backups/boot.img']:
|
||||
path = root / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text('keep')
|
||||
stage = build.stage_path(root, 'mu300-7.2'); stage.mkdir(parents=True)
|
||||
(stage / 'root').mkdir()
|
||||
with self.assertRaises(FileNotFoundError):build.clean_stage(root, 'mu300-7.2')
|
||||
build.write_json(stage / '.build-owner.json', {'owner': build.OWNER, 'profile': 'invalid'})
|
||||
with self.assertRaisesRegex(ValueError, 'unowned'):build.clean_stage(root, 'mu300-7.2')
|
||||
build.write_json(stage / '.build-owner.json', {'owner': build.OWNER, 'profile': 'mu300-7.2'})
|
||||
build.clean_stage(root, 'mu300-7.2')
|
||||
self.assertFalse(stage.exists())
|
||||
self.assertTrue(all((root / n).exists() for n in
|
||||
['sources/kernel', 'objects/e5', 'cache/input', 'backups/boot.img']))
|
||||
|
||||
def test_symlink_escape_and_live_mount_are_not_deleted(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder); outside = root / 'outside'; outside.mkdir()
|
||||
workspace = root / 'workspace'; parent = workspace / 'package-work/mu300-release'
|
||||
parent.mkdir(parents=True)
|
||||
target = parent / 'mu300-7.2'; target.symlink_to(outside, target_is_directory=True)
|
||||
with self.assertRaisesRegex(ValueError, 'symlinks'):build.clean_stage(workspace, 'mu300-7.2')
|
||||
target.unlink(); target.mkdir()
|
||||
build.write_json(target / '.build-owner.json', {'owner': build.OWNER, 'profile': 'mu300-7.2'})
|
||||
read_text = Path.read_text
|
||||
def read(path, *args, **kwargs):
|
||||
if str(path) == '/proc/self/mountinfo':
|
||||
return '1 2 3 / ' + str(target / 'assembly/root') + ' rw - ext4 /dev/loop0 rw\n'
|
||||
return read_text(path, *args, **kwargs)
|
||||
with patch.object(Path, 'read_text', read):
|
||||
with self.assertRaisesRegex(ValueError, 'Unmount'):build.clean_stage(workspace, 'mu300-7.2')
|
||||
self.assertTrue(target.exists()); self.assertTrue(outside.exists())
|
||||
|
||||
|
||||
class Archives(unittest.TestCase):
|
||||
def fixture(self, path, *, corrupt=False, extra=None):
|
||||
files = {'payload/boot-linux.img': b'boot', 'payload/mu300-openwrt.tar.gz': b'root', 'OpenWrt-Installer.py': b'cli'}
|
||||
if extra:files[extra] = b'duplicate root'
|
||||
manifest = {'magisk_layout': {'boot-linux.img':'payload/boot-linux.img', 'mu300-openwrt.tar.gz':'payload/mu300-openwrt.tar.gz'},
|
||||
'magisk': {k:hashlib.sha256(v).hexdigest() for k,v in files.items() if k.startswith('payload/')},
|
||||
'desktop': {'OpenWrt-Installer.py':hashlib.sha256(files['OpenWrt-Installer.py']).hexdigest()}}
|
||||
if corrupt:files['payload/boot-linux.img'] = b'wrong'
|
||||
with zipfile.ZipFile(path, 'w') as archive:
|
||||
for k,v in files.items():archive.writestr(k,v)
|
||||
archive.writestr('desktop/manifest.json', json.dumps(manifest))
|
||||
|
||||
def test_full_archive_and_corruption(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / 'test.zip'; self.fixture(path); build.verify_archive(path)
|
||||
self.fixture(path, corrupt=True)
|
||||
with self.assertRaisesRegex(ValueError, 'checksum mismatch'):build.verify_archive(path)
|
||||
|
||||
def test_duplicate_payloads_and_missing_checksum_coverage(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / 'test.zip'
|
||||
for extra in ['other/mu300-openwrt.tar.gz', 'other/openwrt.ext4.gz', 'rootfs.tar.gz']:
|
||||
self.fixture(path, extra=extra)
|
||||
with self.assertRaisesRegex(ValueError, 'one boot'):build.verify_archive(path)
|
||||
self.fixture(path)
|
||||
with zipfile.ZipFile(path, 'a') as archive:archive.writestr('unrecorded', b'extra')
|
||||
with self.assertRaisesRegex(ValueError, 'Incomplete'):build.verify_archive(path)
|
||||
|
||||
|
||||
class TaskState(unittest.TestCase):
|
||||
def fake_assembly(self, task, model, args, extra_env=None):
|
||||
current = model.removesuffix('-package')
|
||||
active = [p.name for p in (task.workspace / 'package-work/mu300-release').iterdir()]
|
||||
self.assertEqual(active, [current])
|
||||
stage = Path(extra_env['MU300_PACKAGE_WORK'])
|
||||
(stage / 'temporary-image').write_bytes(b'temporary root')
|
||||
Archives().fixture(Path(args[-1]))
|
||||
series = extra_env['MU300_KERNEL']
|
||||
(stage / ('release-' + series + '.json')).write_text(json.dumps({'package_name':current+'-release'}))
|
||||
|
||||
def test_serial_success_cleans_only_staging_and_publishes_at_end(self):
|
||||
with tempfile.TemporaryDirectory() as folder, patch.object(build, 'TOP', Path(folder)), \
|
||||
patch.object(build.os, 'geteuid', return_value=0), patch.object(build, 'input_check'), \
|
||||
patch.object(build.runpy, 'run_path', return_value={
|
||||
'identify': lambda *a: {'private_version':'r-test','source_fingerprint':'same'}}):
|
||||
task = build.Task(Path(folder) / 'native', 'fixture')
|
||||
with patch.object(task, 'run', side_effect=lambda model,args,**kw:self.fake_assembly(task,model,args,**kw)):
|
||||
build.package(task, {'inputs':Path('/input'),'desktop_tools':Path('/tools')}, {'mu300-7.2': {'kernel':Path('/kernel')}, 'mu300-6.18': {'kernel':Path('/kernel2')}})
|
||||
destination = Path(folder) / 'release' / task.id
|
||||
self.assertTrue(destination.is_dir())
|
||||
self.assertFalse(destination.with_name('.building-' + task.id).exists())
|
||||
self.assertEqual(len(list(destination.glob('*.zip'))), 2)
|
||||
self.assertFalse(build.stage_path(task.workspace, 'mu300-7.2').exists())
|
||||
self.assertFalse(build.stage_path(task.workspace, 'mu300-6.18').exists())
|
||||
self.assertEqual(task.data['state'], 'complete')
|
||||
|
||||
def test_changed_sources_block_publication_after_assembly(self):
|
||||
with tempfile.TemporaryDirectory() as folder, patch.object(build, 'TOP', Path(folder)), \
|
||||
patch.object(build.os, 'geteuid', return_value=0), patch.object(build, 'input_check'):
|
||||
identify = unittest.mock.Mock(side_effect=[
|
||||
{'private_version':'r-test','source_fingerprint':'before'},
|
||||
{'private_version':'r-test','source_fingerprint':'after'}])
|
||||
with patch.object(build.runpy, 'run_path', return_value={'identify': identify}):
|
||||
task = build.Task(Path(folder) / 'native', 'fixture')
|
||||
with patch.object(task, 'run', side_effect=lambda model,args,**kw:self.fake_assembly(task,model,args,**kw)):
|
||||
with self.assertRaisesRegex(ValueError, 'sources changed'):
|
||||
build.package(task, {'inputs':Path('/input'),'desktop_tools':Path('/tools')}, {'mu300-7.2': {'kernel':Path('/kernel')}})
|
||||
self.assertFalse((Path(folder) / 'release' / task.id).exists())
|
||||
self.assertTrue((Path(folder) / 'release' / ('.building-' + task.id)).exists())
|
||||
|
||||
def test_real_child_logs_and_failure_status(self):
|
||||
with tempfile.TemporaryDirectory() as folder, patch.object(build, 'TOP', Path(folder)):
|
||||
workspace = Path(folder) / 'native'
|
||||
task = build.Task(workspace, 'fixture')
|
||||
task.run('ok', [sys.executable, '-c', 'print("test-log-output")'])
|
||||
self.assertIn('test-log-output', (task.logs / 'ok.log').read_text())
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
task.run('error', [sys.executable, '-c', 'raise SystemExit(3)'])
|
||||
status = json.loads((task.logs / 'status.json').read_text())
|
||||
self.assertEqual(status['state'], 'failed')
|
||||
self.assertEqual([x['state'] for x in status['steps']], ['complete', 'failed'])
|
||||
self.assertFalse((Path(folder) / 'release').exists())
|
||||
self.assertEqual(list((workspace / 'tmp').iterdir()), [])
|
||||
|
||||
def test_failure_keeps_owned_staging_and_unpublished_archive(self):
|
||||
with tempfile.TemporaryDirectory() as folder, patch.object(build, 'TOP', Path(folder)):
|
||||
root = Path(folder); workspace = root / 'native'
|
||||
with patch.object(build.runpy, 'run_path', return_value={
|
||||
'identify': lambda *a: {'private_version':'r-test','source_fingerprint':'same'}}), \
|
||||
patch.object(build, 'input_check'), patch.object(build.os, 'geteuid', return_value=0):
|
||||
task = build.Task(workspace, 'fixture')
|
||||
def fail(*args, **kwargs):raise RuntimeError('assembler failed')
|
||||
with patch.object(task, 'run', side_effect=fail):
|
||||
with self.assertRaisesRegex(RuntimeError, 'assembler failed'):
|
||||
build.package(task, {'inputs':Path('/input'),'desktop_tools':Path('/tools')}, {'mu300-7.2': {'kernel':Path('/kernel')}})
|
||||
stage = build.stage_path(workspace, 'mu300-7.2')
|
||||
self.assertTrue((stage / '.build-owner.json').exists())
|
||||
self.assertEqual([p.name for p in (root / 'release').iterdir()], ['.building-' + task.id])
|
||||
|
||||
def test_preflight_failure_creates_no_root_staging_or_release(self):
|
||||
with tempfile.TemporaryDirectory() as folder, patch.object(build, 'TOP', Path(folder)), \
|
||||
patch.object(build.os, 'geteuid', return_value=0), \
|
||||
patch.object(build, 'input_check', side_effect=ValueError('stale GUI')):
|
||||
task = build.Task(Path(folder) / 'native', 'fixture')
|
||||
with self.assertRaisesRegex(ValueError, 'stale GUI'):build.package(task, {'inputs':Path('/input'),'desktop_tools':Path('/tools')}, {'mu300-7.2': {'kernel':Path('/kernel')}})
|
||||
self.assertFalse((Path(folder) / 'native/package-work').exists())
|
||||
self.assertFalse((Path(folder) / 'release').exists())
|
||||
|
||||
|
||||
if __name__ == '__main__':unittest.main()
|
||||
@@ -741,6 +741,19 @@ print('OK')
|
||||
self.assertNotEqual(r.returncode, 0, (kind,val))
|
||||
self.assertEqual((self.tmp / 'commands').read_text(), '')
|
||||
|
||||
def test_manual_cell_channel_boundaries(self):
|
||||
for shell in self.each_shell():
|
||||
for value in ('lte:0,0', 'lte:262143,503', 'nr:1,0', 'nr:3279165,1007'):
|
||||
self.reset()
|
||||
result = self.apply(shell, 'cell', value)
|
||||
self.assertEqual(result.returncode, 0, (value, result.stderr))
|
||||
self.assertIn(value, (self.state / 'cell').read_text().splitlines())
|
||||
for value in ('nr:0,0', 'lte:262144,0', 'nr:3279166,0', 'lte:1,-1', 'nr:1,1008'):
|
||||
self.reset()
|
||||
result = self.apply(shell, 'cell', value)
|
||||
self.assertNotEqual(result.returncode, 0, value)
|
||||
self.assertEqual((self.tmp / 'commands').read_text(), '')
|
||||
|
||||
def test_duplicate_bands_and_multi_rat_cells(self):
|
||||
for shell in self.each_shell():
|
||||
self.reset()
|
||||
|
||||
@@ -19,17 +19,23 @@ mu300_sim_changed 0 '+ECIND: 3,1,2'
|
||||
mu300_sim_changed 1 '+ECIND: 3,2'
|
||||
mu300_sim_changed 1 '+ECIND: 3,4'
|
||||
mu300_sim_changed 0 '+ECIND: 3,100'
|
||||
mu300_sim_changed 0 '+ECIND: 3,0,0,1'
|
||||
mu300_sim_changed 1 '+ECIND: 3,1,2,0,1'
|
||||
mu300_sim_changed 0 '+ECIND: 2,1,2'
|
||||
mu300_sim_changed 0 '+ECIND: 3,1,99'
|
||||
mu300_sim_changed 0 '+ECIND: 3,2junk'
|
||||
mu300_sim_changed 0 '+ECIND: 3,1,2,7'
|
||||
mu300_sim_changed 0 '+ECIND: 3,1,2,7junk'
|
||||
mu300_sim_changed 0 '+ECIND: 3,0,0,-1'
|
||||
mu300_sim_changed 0 '+ECIND: 3,0,0,4294967296'
|
||||
mu300_sim_changed 0 '+ECIND: 3,0,0,'
|
||||
mu300_sim_changed 0 '+ECIND: 3,0,,1'
|
||||
mu300_sim_changed 2 '+ECIND: 3,2'
|
||||
wait
|
||||
'''
|
||||
cache = self.tmp / 'sim'
|
||||
r = self.sh(shell, source, MU300_REGISTRATION_DIR=cache)
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual(len(events.read_text().splitlines()), 4)
|
||||
self.assertEqual(len(events.read_text().splitlines()), 6)
|
||||
self.assertFalse(cache.exists())
|
||||
|
||||
def test_confirmed_cpin_scopes_and_unknown_reply(self):
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stock flashing policy; no device writes, downloads or image builds."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
TOP = next(p for p in Path(__file__).resolve().parents if (p/'openwrt').is_dir() and (p/'rootfs').is_dir())
|
||||
E5 = (TOP/'openwrt/luci-app-t551m').exists()
|
||||
PLUGIN = TOP/'openwrt'/('luci-app-t551m' if E5 else 'luci-app-mu300')
|
||||
POLICY = PLUGIN/'root/usr/libexec/unisoc-modem/disable-stock-upgrade'
|
||||
GUARD = TOP/'openwrt/overlay/usr/libexec'/('e5-sysupgrade' if E5 else 'mu300-sysupgrade')
|
||||
IMAGE = 'mu300-openwrt-base:25.12.5'
|
||||
|
||||
|
||||
class Guard(unittest.TestCase):
|
||||
def test_backup_restore_and_list_remain_available(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder); old = root/'original'; receipt = root/'called'
|
||||
old.write_text('#!/bin/sh\nprintf "%s\\n" "$@" > "$RECEIPT"\n'); old.chmod(0o755)
|
||||
script = root/'guard'; script.write_text(GUARD.read_text().replace('/sbin/sysupgrade.openwrt', str(old)))
|
||||
for args in [['-b','backup.tgz'], ['--restore-backup','backup.tgz'], ['-r','backup.tgz'],
|
||||
['-k','-b','-'], ['--list-backup'], ['-v','-l']]:
|
||||
with self.subTest(args=args):
|
||||
subprocess.run(['sh',str(script),*args],env=dict(os.environ,RECEIPT=str(receipt)),check=True)
|
||||
self.assertEqual(receipt.read_text().splitlines(),args)
|
||||
|
||||
def test_images_and_mixed_modes_never_reach_original(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder); old = root/'original'; receipt = root/'called'
|
||||
old.write_text('#!/bin/sh\ntouch "$RECEIPT"\n'); old.chmod(0o755)
|
||||
script = root/'guard'; script.write_text(GUARD.read_text().replace('/sbin/sysupgrade.openwrt', str(old)))
|
||||
for args in [[],['firmware.bin'],['-n','firmware.bin'],['--force','firmware.bin'],
|
||||
['--test','firmware.bin'],['-b'],['-l','firmware.bin'],
|
||||
['-b','backup.tgz','--force','firmware.bin'],['-b','one','-r','two']]:
|
||||
with self.subTest(args=args):
|
||||
r=subprocess.run(['sh',str(script),*args],env=dict(os.environ,RECEIPT=str(receipt)),capture_output=True)
|
||||
self.assertNotEqual(r.returncode,0); self.assertFalse(receipt.exists())
|
||||
|
||||
|
||||
class Policy(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if not shutil.which('docker') or subprocess.run(['docker','image','inspect',IMAGE],capture_output=True).returncode:
|
||||
raise unittest.SkipTest('existing OpenWrt ucode image required; never download/build during tests')
|
||||
|
||||
def fixture(self, root):
|
||||
files = {
|
||||
'www/luci-static/resources/view/system/flash.js': """return {render(){var m,s,o,ss;
|
||||
m=new form.JSONMap({},_('Flash operations'));
|
||||
o=s.option(form.Button,'restore',_('Restore backup'));
|
||||
o=s.option(form.SectionValue,'actions',form.NamedSection,'actions','actions',_('Flash new firmware image'),'description');
|
||||
ss=o.subsection;o=ss.option(form.Button,'sysupgrade',_('Image'));
|
||||
s=m.section(form.NamedSection,'config','config',_('Configuration'));return m.render();}};""",
|
||||
'usr/share/luci/menu.d/system.json': json.dumps({
|
||||
'admin/system/flash':{'title':'Backup / Flash Firmware','action':{'path':'system/flash'}},
|
||||
'admin/system/reboot':{'title':'Reboot'},
|
||||
'admin/system/attendedsysupgrade':{'action':{'path':'system/attendedsysupgrade'}},
|
||||
'admin/system/ota':{'action':{'path':'unisoc/ota'}},
|
||||
'admin/system/upgrade':{'action':{'path':'unisoc/ota'}}}),
|
||||
'usr/share/rpcd/acl.d/system.json': json.dumps({
|
||||
'luci-mod-system-flash':{
|
||||
'read':{'file':{'/sbin/sysupgrade --list-backup':['exec'],'/etc/sysupgrade.conf':['read']}},
|
||||
'write':{'file':{'/sbin/sysupgrade --restore-backup /tmp/backup.tar.gz':['exec'],
|
||||
'/sbin/firstboot -r -y':['exec'],'/sbin/reboot':['exec'],
|
||||
'/sbin/sysupgrade --force /tmp/firmware.bin':['exec'],'/tmp/firmware.bin':['write']},
|
||||
'ubus':{'system':['validate_firmware_image']}}},
|
||||
'luci-app-attendedsysupgrade':{}, 'my-ota':{'write':{'file':{'/usr/bin/ota':['exec']}}}})}
|
||||
for name, text in files.items():
|
||||
p=root/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_text(text)
|
||||
|
||||
def run_policy(self, root):
|
||||
return subprocess.run(['docker','run','--rm','--pull=never','--network','none','--platform','linux/arm64',
|
||||
'-v',str(POLICY)+':/policy:ro','-v',str(root)+':/target',IMAGE,'ucode','/policy','/target'],capture_output=True,text=True)
|
||||
|
||||
def test_backup_controls_and_custom_ota_survive_and_second_run_is_unchanged(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root=Path(folder);self.fixture(root);r=self.run_policy(root);self.assertEqual(r.returncode,0,r.stderr)
|
||||
view=root/'www/luci-static/resources/view/system/flash.js'
|
||||
self.assertNotIn('Flash new firmware image',view.read_text())
|
||||
self.assertIn('Restore backup',view.read_text());self.assertIn("'Configuration'",view.read_text())
|
||||
if shutil.which('node'):
|
||||
subprocess.run(['node','-e',"new Function(require('fs').readFileSync(process.argv[1],'utf8'))",str(view)],check=True)
|
||||
menu=json.loads((root/'usr/share/luci/menu.d/system.json').read_text())
|
||||
self.assertEqual(menu['admin/system/flash']['title'],'Backup')
|
||||
self.assertIn('admin/system/reboot',menu);self.assertIn('admin/system/ota',menu)
|
||||
self.assertNotIn('admin/system/attendedsysupgrade',menu)
|
||||
self.assertIn('admin/system/upgrade',menu)
|
||||
acl=json.loads((root/'usr/share/rpcd/acl.d/system.json').read_text())
|
||||
self.assertIn('my-ota',acl);self.assertNotIn('luci-app-attendedsysupgrade',acl)
|
||||
write=acl['luci-mod-system-flash']['write']['file']
|
||||
self.assertIn('/sbin/sysupgrade --restore-backup /tmp/backup.tar.gz',write)
|
||||
self.assertIn('/sbin/firstboot -r -y',write);self.assertIn('/sbin/reboot',write)
|
||||
self.assertNotIn('/tmp/firmware.bin',write)
|
||||
self.assertNotIn('/sbin/sysupgrade --force /tmp/firmware.bin',write)
|
||||
before={str(p):(p.read_bytes(),p.stat().st_mtime_ns) for p in root.rglob('*') if p.is_file()}
|
||||
r=self.run_policy(root);self.assertEqual(r.returncode,0,r.stderr)
|
||||
self.assertEqual(before,{str(p):(p.read_bytes(),p.stat().st_mtime_ns) for p in root.rglob('*') if p.is_file()})
|
||||
|
||||
def test_unknown_luci_layout_fails_without_changing_menu_or_acl(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root=Path(folder);self.fixture(root)
|
||||
(root/'www/luci-static/resources/view/system/flash.js').write_text('new upstream view')
|
||||
before={str(p):p.read_bytes() for p in root.rglob('*') if p.is_file()}
|
||||
r=self.run_policy(root);self.assertNotEqual(r.returncode,0)
|
||||
self.assertEqual(before,{str(p):p.read_bytes() for p in root.rglob('*') if p.is_file()})
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -25,6 +25,36 @@ def misc_head():
|
||||
|
||||
|
||||
class BootBlocks(unittest.TestCase):
|
||||
@unittest.skipIf(os.name=='nt','Requires POSIX shell')
|
||||
def test_init_detects_both_slots_and_refuses_unknown(self):
|
||||
source=(TOP/'boot/init').read_text()
|
||||
function=source[source.index('detect_linux_slot() {'):source.index('\nfind_partitions() {')]
|
||||
for prefix,args,wanted in [(b'_a',b'','a'),(b'_b',b'','b'),
|
||||
(b'??',b'androidboot.slot_suffix=_a\0','a'),
|
||||
(b'??',b'androidboot.slot_suffix=_b','b'),(b'??',b'','')]:
|
||||
with self.subTest(prefix=prefix,args=args),tempfile.TemporaryDirectory() as temp:
|
||||
root=Path(temp);misc=root/'misc';misc.write_bytes(b'\0'*2048+prefix)
|
||||
dt=root/'bootargs';dt.write_bytes(args);cmd=root/'cmdline';cmd.write_bytes(b'')
|
||||
text=function.replace('/proc/device-tree/chosen/bootargs',str(dt)).replace('/proc/cmdline',str(cmd))
|
||||
script='log(){ :; }; misc='+str(misc)+'; linux_slot=;\n'+text+'\ndetect_linux_slot; r=$?; printf "%s:%s" "$r" "$linux_slot"'
|
||||
result=subprocess.run(['sh','-c',script],capture_output=True,text=True)
|
||||
self.assertEqual(result.stdout,('0:' if wanted else '1:')+wanted)
|
||||
|
||||
def test_cpio_slot_metadata_has_its_parent_directory(self):
|
||||
build=runpy.run_path(str(TOP/'boot/build-boot-image.py'))
|
||||
raw=build['cpio_archive']({'dev'}, {'etc/mu300/linux-slot': (b'a\n', 0o100644)})
|
||||
offset=0;seen=set()
|
||||
while offset<len(raw):
|
||||
self.assertEqual(raw[offset:offset+6],b'070701')
|
||||
fields=[int(raw[offset+6+i*8:offset+14+i*8],16) for i in range(13)]
|
||||
size,namesize=fields[6],fields[11]
|
||||
name=raw[offset+110:offset+110+namesize-1].decode()
|
||||
start=(offset+110+namesize+3)&~3
|
||||
if name=='TRAILER!!!':break
|
||||
if '/' in name:self.assertIn(name.rsplit('/',1)[0],seen)
|
||||
seen.add(name);offset=(start+size+3)&~3
|
||||
self.assertIn('etc/mu300/linux-slot',seen)
|
||||
|
||||
def test_both_android_and_linux_blocks_have_valid_crc(self):
|
||||
build = runpy.run_path(str(TOP / 'boot/build-boot-image.py'))
|
||||
android_a, linux_b, android_b, linux_a = build['bootloader_control'](misc_head())
|
||||
|
||||
@@ -52,7 +52,11 @@ class Layouts(UpdateBase):
|
||||
struct.pack_into('<I',bc,28,zlib.crc32(bc[:28]))
|
||||
(run/'mu300/linux-slot').write_text(slot+'\n')
|
||||
(run/'mu300/misc-bc-linux-trial.bin').write_bytes(bc)
|
||||
(run/'mu300/misc-bc-android.bin').write_bytes(bc)
|
||||
android=bytearray(bc)
|
||||
android[:4]=b'_b\0\0' if slot=='a' else b'_a\0\0'
|
||||
android[12],android[14]=(0x1e,0x9f) if slot=='a' else (0x9f,0x1e)
|
||||
struct.pack_into('<I',android,28,zlib.crc32(android[:28]))
|
||||
(run/'mu300/misc-bc-android.bin').write_bytes(android)
|
||||
for default in ('android','linux',None):
|
||||
conf.unlink(missing_ok=True)
|
||||
if default:conf.write_text(default+'\n')
|
||||
@@ -65,6 +69,23 @@ class Layouts(UpdateBase):
|
||||
block=after[2048:2080];self.assertEqual(block[12 if slot=='a' else 14],0x4f)
|
||||
self.assertEqual(struct.unpack_from('<I',block,28)[0],zlib.crc32(block[:28]))
|
||||
self.assertEqual((area/'.mu300/boot-tries').read_text(),'0\n')
|
||||
# No role file is needed when the supplied Linux trial block
|
||||
# identifies its slot. Unknown/conflicting roles may not write misc.
|
||||
role=run/'mu300/linux-slot'
|
||||
role.unlink()
|
||||
result=subprocess.run(['bash',str(script),'--trial'],capture_output=True,text=True,timeout=10)
|
||||
self.assertEqual(result.returncode,0,result.stderr)
|
||||
original=misc.read_bytes()
|
||||
role.write_text(('b' if slot=='a' else 'a')+'\n')
|
||||
result=subprocess.run(['bash',str(script),'--trial'],capture_output=True,text=True,timeout=10)
|
||||
self.assertNotEqual(result.returncode,0)
|
||||
self.assertEqual(misc.read_bytes(),original)
|
||||
role.write_text(slot+'\n')
|
||||
(run/'mu300/misc-bc-android.bin').write_bytes(bc)
|
||||
result=subprocess.run(['bash',str(script),'android'],capture_output=True,text=True,timeout=10)
|
||||
self.assertNotEqual(result.returncode,0)
|
||||
self.assertEqual(misc.read_bytes(),original)
|
||||
(run/'mu300/misc-bc-android.bin').write_bytes(android)
|
||||
|
||||
def test_root_device_detection_does_not_mount_userdata(self):
|
||||
sys=self.root/'sys/class/block'
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"format": 1,
|
||||
"inputs": "{repo}/../mu300-linux/work",
|
||||
"desktop_tools": "{repo}/work/v50-20261014/installer-final/desktop/files/boot/repair",
|
||||
"block_apk": "{repo}/work/block-mount-mu300.apk",
|
||||
"wifi_apks": "{repo}/work/wifi-sae",
|
||||
"profiles": {
|
||||
"mu300-7.2": {"kernel": "{workspace}/kernels/mu300-7.2.8"},
|
||||
"mu300-6.18": {"kernel": "{workspace}/kernels/mu300-6.18.54"}
|
||||
}
|
||||
}
|
||||
@@ -16,11 +16,15 @@ UO=${MU300_UPSTREAM_OUT:-$DEFAULT_UO}
|
||||
PLUGIN=${MU300_LUCI_PLUGIN_SRC:-$TOP/openwrt/luci-app-mu300}
|
||||
[ -s "$PLUGIN/Makefile" ] || { echo "standalone LuCI plugin missing: $PLUGIN (set MU300_LUCI_PLUGIN_SRC)" >&2; exit 1; }
|
||||
OUT=${1:-}
|
||||
ROOTFS=$TOP/openwrt/mu300-openwrt-tf-$KERNEL-rootfs.tar.gz
|
||||
BOOT=$TOP/work/boot-linux-tf-$KERNEL.img
|
||||
GENERIC=$TOP/work/ramdisk-$KERNEL-tf.lz4
|
||||
WRAPPED=$TOP/work/Image-$KERNEL.lk
|
||||
mkdir -p "$TOP/work"
|
||||
PACKAGE_WORK=${MU300_PACKAGE_WORK:-$TOP/work}
|
||||
ROOTFS_DIR=${MU300_ROOTFS_OUT_DIR:-$TOP/openwrt}
|
||||
mkdir -p "$PACKAGE_WORK" "$ROOTFS_DIR"
|
||||
PACKAGE_WORK=$(cd "$PACKAGE_WORK" && pwd)
|
||||
ROOTFS_DIR=$(cd "$ROOTFS_DIR" && pwd)
|
||||
ROOTFS=$ROOTFS_DIR/mu300-openwrt-tf-$KERNEL-rootfs.tar.gz
|
||||
BOOT=$PACKAGE_WORK/boot-linux-tf-$KERNEL.img
|
||||
GENERIC=$PACKAGE_WORK/ramdisk-$KERNEL-tf.lz4
|
||||
WRAPPED=$PACKAGE_WORK/Image-$KERNEL.lk
|
||||
|
||||
# Hybrid layout relocates original deployment files behind a thin Magisk entry;
|
||||
# desktop code is not added to the Magisk boot image.
|
||||
@@ -60,7 +64,7 @@ grep -qx 'CONFIG_LEDS_AW9523B=y' "$UO/kernel.config" || {
|
||||
}
|
||||
rel=$(strings "$UO/Image" | sed -n 's/^Linux version \([^ ]*\) .*/\1/p' | head -n1)
|
||||
case $rel in "$KERNEL".*) ;; *) echo "$UO is kernel '$rel', expected $KERNEL.x" >&2; exit 1 ;; esac
|
||||
RELEASE_JSON=$TOP/work/release-$KERNEL.json
|
||||
RELEASE_JSON=$PACKAGE_WORK/release-$KERNEL.json
|
||||
if [ -n "${MU300_VERSION:-}" ]; then
|
||||
VERSION=$(python3 "$TOP/tools/release-identity.py" --profile mu300 --kernel "$rel" --version "$MU300_VERSION" --output "$RELEASE_JSON" --field image_version)
|
||||
else
|
||||
@@ -101,7 +105,7 @@ done
|
||||
|
||||
echo "==> OpenWrt rootfs ($rel modules included)"
|
||||
MU300_GPU=0 MU300_INPUTS="$IN" MU300_MAINLINE_OUT="$UO" MU300_LUCI_PLUGIN_SRC="$PLUGIN" \
|
||||
MU300_VERSION="$VERSION" MU300_RELEASE_JSON="$RELEASE_JSON" \
|
||||
MU300_VERSION="$VERSION" MU300_RELEASE_JSON="$RELEASE_JSON" MU300_ROOTFS_OUT_DIR="$ROOTFS_DIR" \
|
||||
sh "$TOP/openwrt/build-rootfs.sh" "$(basename "$ROOTFS")"
|
||||
for f in ./lib/netifd/proto/mu300cell.sh ./lib/netifd/proto/mu300cell-v6.sh \
|
||||
./sbin/block ./lib/libblkid-tiny.so ./etc/init.d/fstab ./etc/mu300/block-mount.build-id \
|
||||
@@ -176,7 +180,7 @@ python3 "$TOP/boot/build-boot-image.py" \
|
||||
--ueventd-perms "$TOP/android-vendor/ueventd-perms.sh" \
|
||||
--android-subset "$IN/android-subset" --root-target sd --out "$BOOT" >/dev/null
|
||||
|
||||
STAGE=$(mktemp -d "$TOP/work/tf-magisk-stage.XXXXXX")
|
||||
STAGE=$(mktemp -d "$PACKAGE_WORK/tf-magisk-stage.XXXXXX")
|
||||
trap 'rm -rf "$STAGE"' EXIT
|
||||
cp "$TOP/android/magisk/mu300-openwrt-tf/module.prop" \
|
||||
"$TOP/android/magisk/mu300-openwrt-tf/customize.sh" \
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local build task logging and serial release assembly; never flash a device.
|
||||
|
||||
Run in Linux/WSL. Native installer compilation keeps installer/build.py.
|
||||
plan/check are read-only; package reuses verified kernels/APKs and assembles rootfs.
|
||||
"""
|
||||
import argparse
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import runpy
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import zipfile
|
||||
|
||||
TOP = Path(__file__).resolve().parents[1]
|
||||
sys.dont_write_bytecode = True
|
||||
OWNER = 'mu300-build-release-v1'
|
||||
PROFILES = ('mu300-7.2', 'mu300-6.18')
|
||||
COMMON = ('inputs', 'desktop_tools', 'block_apk', 'wifi_apks')
|
||||
|
||||
|
||||
def write_json(path, value):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name(path.name + '.new')
|
||||
temporary.write_text(json.dumps(value, indent=2) + '\n', encoding='utf-8')
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def layout(config, workspace, profiles, repo=TOP):
|
||||
data = json.loads(config.read_text(encoding='utf-8'))
|
||||
if data.get('format') != 1:
|
||||
raise ValueError('Unsupported build layout')
|
||||
workspace = workspace.expanduser().resolve()
|
||||
if workspace == Path('/') or workspace == Path.home():
|
||||
raise ValueError('Choose a dedicated build workspace')
|
||||
if workspace == Path('/mnt/c') or workspace.is_relative_to('/mnt/c'):
|
||||
raise ValueError('Build workspace must not migrate to C:')
|
||||
values = {'repo': str(repo.resolve()), 'workspace': str(workspace)}
|
||||
def path(value):
|
||||
result = Path(value.format(**values)).expanduser()
|
||||
if not result.is_absolute():
|
||||
raise ValueError('Build input paths must be absolute after expansion')
|
||||
return result.resolve()
|
||||
common = {key: path(data[key]) for key in COMMON}
|
||||
rows = {}
|
||||
for model in profiles:
|
||||
if model not in PROFILES or model not in data['profiles']:
|
||||
raise ValueError('Unknown/unconfigured model: ' + model)
|
||||
rows[model] = {'kernel': path(data['profiles'][model]['kernel'])}
|
||||
return common, rows
|
||||
|
||||
|
||||
@contextmanager
|
||||
def workspace_lock(workspace):
|
||||
import fcntl
|
||||
directory = workspace / 'locks'
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
# A sudo packaging run must not make the next user's compiler task require
|
||||
# write access to a root-owned lock file. Linux flock works on a read FD.
|
||||
descriptor = os.open(directory / 'openwrt-release.lock', os.O_RDONLY | os.O_CREAT, 0o644)
|
||||
with os.fdopen(descriptor, 'rb') as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError as error:
|
||||
raise ValueError('Another build/package task owns this workspace') from error
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(lock, fcntl.LOCK_UN)
|
||||
|
||||
|
||||
def stage_path(workspace, model):
|
||||
if model not in PROFILES:
|
||||
raise ValueError('Unknown staging model')
|
||||
parent = workspace / 'package-work/mu300-release'
|
||||
target = parent / model
|
||||
if parent.is_symlink() or parent.resolve() != parent or target.is_symlink():
|
||||
raise ValueError('Staging path must not use symlinks')
|
||||
if not target.resolve().is_relative_to(workspace.resolve()):
|
||||
raise ValueError('Staging path escaped workspace')
|
||||
return target
|
||||
|
||||
|
||||
def clean_stage(workspace, model):
|
||||
target = stage_path(workspace, model)
|
||||
if not target.exists():
|
||||
return
|
||||
marker = target / '.build-owner.json'
|
||||
if marker.is_symlink() or json.loads(marker.read_text()) != {'owner': OWNER, 'profile': model}:
|
||||
raise ValueError('Refusing to clean unowned staging: ' + str(target))
|
||||
# Refuse a live image/root mount anywhere below the staging tree.
|
||||
for line in Path('/proc/self/mountinfo').read_text().splitlines():
|
||||
mount = Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), line.split()[4]))
|
||||
if mount == target or mount.is_relative_to(target):
|
||||
raise ValueError('Unmount staging before cleanup: ' + str(mount))
|
||||
shutil.rmtree(target)
|
||||
|
||||
|
||||
def installer_artifact(platform):
|
||||
directory, variable = {
|
||||
'windows-x64': ('windows', 'OPENWRT_GUI_ARTIFACT'),
|
||||
'macos-arm64': ('macos-arm64', 'OPENWRT_GUI_MACOS_ARTIFACT'),
|
||||
}[platform]
|
||||
return Path(os.environ.get(variable, str(TOP / 'installer/artifacts' / directory)))
|
||||
|
||||
|
||||
def input_check(common, rows):
|
||||
missing = [str(p) for p in common.values() if not p.exists()]
|
||||
missing += [str(p) for row in rows.values() for p in row.values() if not p.exists()]
|
||||
if missing:
|
||||
raise ValueError('Missing registered inputs (nothing was built/copied):\n' + '\n'.join(missing))
|
||||
required = ['dumps/boot_a.img', 'dumps/misc-head.bin', 'busybox', 'tools/logdw/logdw',
|
||||
'firmware', 'android-subset', 'tools/bt-init/mu300-bt-init', 'tools/keys/mu300-keys']
|
||||
required += ['out/modules/' + n for n in ('wcn_bsp.ko', 'sprd_wlan_combo.ko', 'sprdbt_tty.ko', 'mali_kbase.ko')]
|
||||
missing = [str(common['inputs'] / n) for n in required if not (common['inputs'] / n).exists()]
|
||||
if not (common['desktop_tools'] / 'lib/ld-musl-aarch64.so.1').is_file():
|
||||
missing.append(str(common['desktop_tools'] / 'lib/ld-musl-aarch64.so.1'))
|
||||
if missing: raise ValueError('Missing registered MU300 inputs:\n' + '\n'.join(missing))
|
||||
runpy.run_path(str(TOP / 'openwrt/wifi-sae-state.py'))['inspect'](common['wifi_apks'])
|
||||
block = common['block_apk']
|
||||
block_sources = ('block-mount.Dockerfile', 'build-block-mount.sh', 'build-block-mount-inner.sh',
|
||||
'block-probe-guard.h', 'patches/fstools-probe-device-types.patch')
|
||||
expected = hashlib.sha256(b''.join((TOP / 'openwrt' / n).read_bytes() for n in block_sources)).hexdigest()
|
||||
if Path(str(block) + '.build-id').read_text().strip() != expected:
|
||||
raise ValueError('block-mount input is stale')
|
||||
if Path(str(block) + '.sha256').read_text().split()[0] != digest(block):
|
||||
raise ValueError('block-mount input checksum mismatch')
|
||||
sys.path.insert(0, str(TOP / 'installer'))
|
||||
from package_gui import sources, validate_artifact
|
||||
source = sources()
|
||||
for platform in ('windows-x64', 'macos-arm64'):
|
||||
validate_artifact(installer_artifact(platform), platform, source)
|
||||
check = runpy.run_path(str(TOP / 'upstream/check-container-support.py'))['check']
|
||||
for model, row in rows.items():
|
||||
release = check(row['kernel'])
|
||||
if not release.startswith(model.removeprefix('mu300-') + '.'):
|
||||
raise ValueError('Wrong kernel model: ' + model + ': ' + release)
|
||||
|
||||
|
||||
def digest(path):
|
||||
h = hashlib.sha256()
|
||||
with path.open('rb') as stream:
|
||||
for chunk in iter(lambda: stream.read(1 << 20), b''):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def verify_archive(path):
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
names = archive.namelist()
|
||||
if len(names) != len(set(names)) or archive.testzip():
|
||||
raise ValueError('ZIP duplicate entries or CRC failure: ' + str(path))
|
||||
manifest = json.loads(archive.read('desktop/manifest.json'))
|
||||
shared_root = manifest['magisk_layout']['mu300-openwrt.tar.gz']
|
||||
shared_boot = manifest['magisk_layout']['boot-linux.img']
|
||||
if (names.count(shared_root) != 1 or names.count(shared_boot) != 1
|
||||
or sum(n.endswith('boot-linux.img') for n in names) != 1
|
||||
or sum(n.endswith(('openwrt.ext4.gz', 'rootfs.tar.gz', 'mu300-openwrt.tar.gz'))
|
||||
for n in names) != 1):
|
||||
raise ValueError('Expected one boot and one system image')
|
||||
expected = dict(manifest['magisk'])
|
||||
for name, wanted in manifest['desktop'].items():
|
||||
if name in expected and expected[name] != wanted:
|
||||
raise ValueError('Conflicting checksum entry')
|
||||
expected[name] = wanted
|
||||
if set(expected) != {n for n in names if not n.endswith('/') and n != 'desktop/manifest.json'}:
|
||||
raise ValueError('Incomplete ZIP checksums')
|
||||
for name, wanted in expected.items():
|
||||
with archive.open(name) as stream:
|
||||
h = hashlib.sha256()
|
||||
for chunk in iter(lambda: stream.read(1 << 20), b''):
|
||||
h.update(chunk)
|
||||
if h.hexdigest() != wanted:
|
||||
raise ValueError('ZIP checksum mismatch: ' + name)
|
||||
|
||||
|
||||
class Task:
|
||||
def __init__(self, workspace, label):
|
||||
if not re.fullmatch(r'[a-z0-9][a-z0-9-]{0,60}', label):
|
||||
raise ValueError('Invalid task label')
|
||||
self.workspace = workspace
|
||||
stamp = datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')
|
||||
self.id = stamp + '-' + label + '-' + str(os.getpid())
|
||||
self.logs = TOP / 'out/build-logs' / self.id
|
||||
self.logs.mkdir(parents=True)
|
||||
self.data = {'format': 1, 'task': self.id, 'pid': os.getpid(), 'state': 'running',
|
||||
'workspace': str(workspace), 'logs': str(self.logs), 'steps': []}
|
||||
self.save()
|
||||
|
||||
def save(self, **fields):
|
||||
self.data.update(fields)
|
||||
write_json(self.logs / 'status.json', self.data)
|
||||
write_json(TOP / 'out/build-state/latest.json', self.data)
|
||||
|
||||
def run(self, label, command, extra_env=None):
|
||||
log = self.logs / (label + '.log')
|
||||
step = {'stage': label, 'command': list(map(str, command)), 'log': str(log),
|
||||
'started': time.time(), 'state': 'running'}
|
||||
self.data['steps'].append(step); self.save(stage=label)
|
||||
temp_parent = self.workspace / 'tmp'
|
||||
temp_parent.mkdir(parents=True, exist_ok=True)
|
||||
print(label + ': ' + str(log), flush=True)
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix='mu300-release-', dir=temp_parent) as temp:
|
||||
env = dict(os.environ, TMPDIR=temp, PYTHONDONTWRITEBYTECODE='1')
|
||||
env.update(extra_env or {})
|
||||
with log.open('wb') as stream:
|
||||
subprocess.run(list(map(str, command)), cwd=TOP, env=env,
|
||||
stdout=stream, stderr=subprocess.STDOUT, check=True)
|
||||
except BaseException:
|
||||
step.update(state='failed', finished=time.time()); self.save(state='failed')
|
||||
raise
|
||||
step.update(state='complete', finished=time.time()); self.save()
|
||||
|
||||
|
||||
def package(task, common, rows):
|
||||
input_check(common, rows) # All models and both GUI platforms before copying rootfs.
|
||||
for model in rows:
|
||||
if stage_path(task.workspace, model).exists():
|
||||
raise ValueError('Prior staging retained; inspect it then run clean-staging: ' + model)
|
||||
identify = runpy.run_path(str(TOP / 'tools/release-identity.py'))['identify']
|
||||
before = identify(TOP, 'mu300', '7.2.8')
|
||||
version = before['private_version']
|
||||
parent = TOP / 'release'
|
||||
pending = parent / ('.building-' + task.id)
|
||||
pending.mkdir(parents=True)
|
||||
task.save(pending_output=str(pending))
|
||||
assets = []
|
||||
for model, row in rows.items():
|
||||
stage = stage_path(task.workspace, model)
|
||||
stage.mkdir(parents=True)
|
||||
write_json(stage / '.build-owner.json', {'owner': OWNER, 'profile': model})
|
||||
assembly = stage / 'assembly'; assembly.mkdir()
|
||||
archive = assembly / 'package.zip'
|
||||
env = {'MU300_INPUTS': str(common['inputs']), 'MU300_DESKTOP_TOOLS': str(common['desktop_tools']),
|
||||
'MU300_UPSTREAM_OUT': str(row['kernel']), 'MU300_KERNEL': model.removeprefix('mu300-'),
|
||||
'MU300_PACKAGE_WORK': str(assembly), 'MU300_ROOTFS_OUT_DIR': str(assembly),
|
||||
'MU300_VERSION': version, 'MU300_DESKTOP_INSTALLER': '1', 'OPENWRT_GUI_OPTIONAL': '0'}
|
||||
task.run(model + '-package', ['sh', TOP / 'tools/build-openwrt-tf-magisk.sh', archive], extra_env=env)
|
||||
verify_archive(archive)
|
||||
release = json.loads((assembly / ('release-' + env['MU300_KERNEL'] + '.json')).read_text())
|
||||
target = pending / (release['package_name'] + '.zip')
|
||||
shutil.copyfile(archive, target)
|
||||
checksum = digest(archive)
|
||||
if digest(target) != checksum: raise ValueError('Published copy differs from verified archive')
|
||||
(pending / (target.name + '.sha256')).write_text(checksum + ' ' + target.name + '\n')
|
||||
assets.append({'profile': model, 'file': target.name, 'bytes': target.stat().st_size, 'sha256': checksum})
|
||||
clean_stage(task.workspace, model)
|
||||
after = identify(TOP, 'mu300', '7.2.8')
|
||||
if after['source_fingerprint'] != before['source_fingerprint']:
|
||||
raise ValueError('Repository sources changed during release; output stays unpublished')
|
||||
write_json(pending / 'BUILD-RUN.json', {**task.data, 'state': 'verified',
|
||||
'source': before, 'assets': assets})
|
||||
destination = parent / task.id
|
||||
pending.rename(destination)
|
||||
task.save(state='complete', output=str(destination), assets=assets)
|
||||
print('Verified release: ' + str(destination))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('plan', 'check', 'package', 'run', 'status', 'clean-staging'))
|
||||
parser.add_argument('--profiles', nargs='+', choices=('all', *PROFILES), default=['all'])
|
||||
parser.add_argument('--workspace', type=Path, default=Path.home() / 'openwrt-build')
|
||||
parser.add_argument('--config', type=Path, default=TOP / 'tools/build-layout.json')
|
||||
parser.add_argument('--label', default='build')
|
||||
# Compiler arguments follow -- and are passed without a shell.
|
||||
args, command = parser.parse_known_args()
|
||||
if command and command[0] == '--': command = command[1:]
|
||||
if command and args.action != 'run': parser.error('Unexpected extra arguments')
|
||||
if os.name == 'nt': parser.error('Run in WSL; see docs/LOCAL-BUILD.zh-CN.md')
|
||||
workspace = args.workspace.expanduser().resolve()
|
||||
profiles = list(PROFILES) if 'all' in args.profiles else list(dict.fromkeys(args.profiles))
|
||||
common, rows = layout(args.config, workspace, profiles)
|
||||
if args.action == 'plan':
|
||||
print(json.dumps({'workspace': str(workspace), 'inputs': common, 'profiles': rows,
|
||||
'staging': workspace / 'package-work/mu300-release', 'output': TOP / 'release',
|
||||
'logs': TOP / 'out/build-logs'}, default=str, indent=2)); return
|
||||
if args.action == 'status':
|
||||
print((TOP / 'out/build-state/latest.json').read_text(encoding='utf-8')); return
|
||||
if args.action == 'check':
|
||||
input_check(common, rows); print('All selected inputs verified; nothing built/copied'); return
|
||||
with workspace_lock(workspace):
|
||||
if args.action == 'clean-staging':
|
||||
for model in profiles: clean_stage(workspace, model)
|
||||
return
|
||||
task = Task(workspace, args.label)
|
||||
try:
|
||||
if args.action == 'run':
|
||||
if not command: raise ValueError('Supply a real compiler/build command after --')
|
||||
task.run('command', command); task.save(state='complete')
|
||||
else:
|
||||
package(task, common, rows)
|
||||
except BaseException as error:
|
||||
task.save(state='failed', error=str(error))
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (ValueError, OSError, subprocess.SubprocessError) as error:
|
||||
sys.exit('Build stopped: ' + str(error))
|
||||
Reference in new issue
Block a user