fix: preserve alphanumeric SIM identities and sync device-evidence uninstall

Keep complete ICCIDs in APN binding, dialer identity parsing and device information. Add card-isolation and alphanumeric identity regression coverage.

Sync the shared installer evidence-based uninstall flow, documentation and UI updates.
This commit is contained in:
kanoqwq committed 2026-10-17 02:20:22 +08:00
1 parent abc5a93c3d
commit 18d3725ad0
27 files changed
+878 -69

No files matched your search

@@ -0,0 +1,19 @@
# 带字母 ICCID 的 APN 兼容修复
E5 用户报告 APN 可以新建,却无法切换;排查发现按卡保存的身份校验只允许
纯数字。MU300 的 APN 库、`apn-identity` 和 `mobile-data` 也存在同类限制。
本次同步修复:
- 18–22 位 ASCII 字母数字 ICCID 原样进入按卡配置键,包括 A–F、G–Z 和小写字母。
保留大小写/填充,不将字母删除后再比较,避免把不同卡绑定到同一配置。
- 网页身份刷新和拨号时的身份读取同时修改,支持带引号/不带引号的 `+CCID`。
继续拒绝过短、过长、控制字符、分隔符和非字符串。
- 设备信息页也不再只提取数字,避免显示另一种截断后的 ICCID。
- 未配置按卡 APN 时仍不额外查询 ICCID;保留现有鉴权、初始附着和 AT 顺序。
- 新增真实 ucode/UCI 绑定、重新读取、不同字母卡隔离、自动匹配,以及多种
shell 的 AT 解析和拨号配置回归。
E5 的 IPv4-only 报错是 ModemManager 没登记 CID2 网口造成的;MU300 的
`mobile-data` 直接配置指定 CID,机制不同,因此不照搬 E5 的 MM 补丁。
本次 MU300 为代码和离线测试验证,未部署或验证实机切换。
@@ -0,0 +1,33 @@
# 无原安装记录卸载:设备证据与空间边界
日期:2026-10-17。开发验证报告。用户操作说明见 [安装器使用指南](../installer/GUIDE.md)。本修订取消“必须保留原分区创建事务”的硬性限制,沿用保数据检查、明确格式化选择及离线执行流程。
## 行为
- 有匹配原安装记录、完整身份信息和已校验 GPT 备份时优先使用,仍检查其他分区没有变化;原空闲区安装只释放为空闲,原缩容按已证明的边界归还。
- 无原记录或原备份已不可用时,检查当前双份 GPT、Linux 文件系统分区类型、GUID、对齐、内核节点起止及容量、挂载/映射占用、另一槽的 Linux boot/ramdisk 路由,以及已安装文件系统内的固定标记。不是只检测 `e5root`/`mu300root` 分区名。
- 可信 OpenWrt 分区紧邻 userdata 尾部时,仅合并这一个分区的范围,userdata 新尾部等于当前 OpenWrt 分区尾部。不猜历史容量,也不合并额外隐藏空间或其他未分配范围。
- 不相邻时只移除 OpenWrt 分区并释放为空闲,不跨越间隔或其他分区扩大 Android。计划分别显示 Android 前后容量、归还 Android 的容量及释放为空闲的容量。
- 保留 Android 数据的要求不变:明确未加密、直接 userdata、身份及容量可读、工具支持。否则先说明原因并询问是否格式化,仍需最终确认;格式化选择不能绕过分区归属和边界检查。
- 本次卸载始终新建持久记录、当前布局快照、boot/misc 及启动链备份。没有旧安装事务与没有本次卸载恢复记录是不同情况。新记录丢失且设备已存在待执行卸载标记时,仍须恢复记录,不能重建另一项破坏性操作。
## 实现与限制
共用规范源为 `installer/backend/uninstall.py` 和新增 `install_evidence.py`,同步到 MU300。无原记录的计划使用内部卸载 schema 3;保留 schema 1 已下发操作及 schema 2 原记录计划的恢复能力。
固定文件通过电脑上的纯 Python ext4 只读解析器读取。目录、inode、块及 extent 均校验长度和界限;有元数据读取预算,拒绝符号链接、稀疏或异常 extent、未正常卸载及不支持的文件系统。不会挂载/修复根分区、执行其中的脚本,也不新增用户环境依赖。二进制元数据传输继续使用已校验的设备临时文件和 ADB pull,没有 Base64 分支。
E5 使用对应 boot 路由、当前磁盘的 `etc/e5/part-root` 和 OpenWrt 身份;MU300 使用 native `part`/已完成的 `install-part` ramdisk 路由、容器启动标记、`openwrt/etc/mu300/desktop-mode=part` 和 OpenWrt 身份。TF、userdata 镜像、未列入 GPT 的旧隐藏区域及未知自定义布局不冒充独立分区安装。
执行前重新核验证据。导入/重启后从已保存的当前快照重新计算允许变更,重新算哈希也不能扩大范围或修改 NV 等无关条目。设备证据加入格式化选择指纹。启动准备中断时,原 Linux 证明可从本次卸载的已校验 boot 备份读取;实际 GPT、misc、Android 槽及当前根分区证据仍须复核。已经下发的任务不再依赖即将删除的根分区标记,不重放缩放、格式化或完成的写入。
## 自动化验证
- 两仓库完整 Python 测试各 195 项:E5 跳过 11 项,MU300 跳过 13 项,其余通过。
- 新增设备证据测试 18 项,覆盖空电脑记录、损坏旧备份、原记录优先/冲突拒绝、E5 与 MU300 Android A/B、相邻归还/非相邻释放、额外尾部空间保留、同名伪标记、占用/错误节点/脏文件系统/错误 boot 拒绝、格式化不能绕过证据、导入越界/无关分区/节点篡改拒绝、重新打开续作、启动准备的真实请求生成和备份顺序。
- WSL 执行卸载相关 52 项,51 项通过,1 项因本机旧 F2FS 工具跳过。包含实际 BusyBox 在临时普通稀疏文件上的 GPT/BCB/boot 读写、保数据 ext4 扩容及最终容量检查。
- 新只读解析器另用 `mke2fs` 创建的真实 ext4 普通文件验证 1 KiB/4 KiB 块、64 位描述符、metadata checksum、索引/多块目录、标记和符号链接拒绝;前后整文件 SHA256 相同。挂载/映射占用检测也用真实 POSIX shell 和临时 sys/proc 文件验证,错误或不可读元数据不会判空闲。
- 只读检查现有 E5/M8/T551M boot 资产;MU300 7.2 现有载荷在内存中生成 Android A/B 的 `part` 及 `install-part` 路由,证据识别通过,不写回发布包。
- TypeScript 无输出类型检查通过。源代码 Vite/Playwright 六组卸载场景通过,覆盖中文/英文、浅色/深色、有/无原记录、保留/释放/重置、取消和一次最终确认、最小 800×650 窗口及 Android 完成页。截图新增 `uninstall-plan-device-zh.png`、`uninstall-plan-device-gap-en.png`。
**此次没有连接或修改实机,没有实机验证内核分区重读、扩容或原厂 Recovery。没有编译 EXE/APP、打包或改动发布载荷。已有安装包不会自动包含这些源码改动。**
@@ -2,6 +2,8 @@
日期:2026-10-17。此页为开发验证报告。用户步骤见 `installer/GUIDE.md` 和帮助页“卸载并归还空间”。
**后续修订:原安装记录已不再是硬性条件。无旧记录时的设备端证据、相邻分区边界及新增验证见 [无原安装记录卸载](INSTALLER-UNINSTALL-EVIDENCE-20261017.zh-CN.md)。本文下述“原记录缺失仍停止”只描述本修订前的限制;保数据及明确格式化选择规则继续适用。**
## 处理规则
- 可靠确认当前 Android 未加密、`/data` 直接位于 userdata、文件系统身份和容量可读、所带检查/扩容工具兼容时:删除独立 OpenWrt 分区,离线检查并扩大 userdata,保留 Android 文件系统和数据。
+10 -6
View File
@@ -66,13 +66,15 @@ Linux、Intel Mac 或需要 Python 命令行入口时,可使用 **OpenWrt-Inst
### 卸载内置 OpenWrt 并归还空间
先在 OpenWrt 管理页面导出需要保留的配置,再通过设备的系统切换功能回到 Android,开启调试并授予 root。在安装器的“高级选项”中选择“卸载并归还空间”,检查设备并查看卸载计划。需要电脑上最初创建该分区的安装记录和完整备份;换过电脑时,先从“继续未完成的安装”导入原备份目录。记录不匹配或缺失时,安装器会停止,请保留现有分区,不要用旧版卸载脚本尝试。
先在 OpenWrt 管理页面导出需要保留的配置,再通过设备的系统切换功能回到 Android,开启调试并授予 root。在安装器的“高级选项”中选择“卸载并归还空间”,检查设备并查看卸载计划。有原安装记录和完整备份时,优先按原记录归还空间;换过电脑时可以先导入原备份目录。
**没有原安装记录也可以检查卸载。** 安装器会核验当前分区表、启动镜像和设备上的安装标记。核验通过后,仅将紧邻 userdata 的 OpenWrt 分区容量归还 Android,不合并其他空闲空间;不相邻的 OpenWrt 分区只释放为空闲,不扩大 Android。请以计划中的“Android 容量”“归还 Android 的空间”和“释放为空闲的空间”为准。无法核实安装归属或分区边界时会停止,不能只凭分区名称删除。执行前会为本次卸载新建记录和备份,请保留。
卸载时会重新检查当前 Android 的加密状态、data 所在设备和文件系统工具。**确认未加密、data 直接位于 userdata 且工具支持时,离线检查并扩容 userdata,保留 Android 数据。** OpenWrt 系统及配置仍会删除,请先备份需要保留的内容。
无法确认可保留 Android 数据时,安装器先报出具体原因,再询问“无法保留 Android 数据卸载,是否格式化?”。取消不会写入设备;同意后仅生成新的卸载计划。**格式化会清空 Android 应用、账号、照片和内部存储。** 请备份个人文件,并在最终计划中核对数据影响及容量后再确认执行。缺失原安装记录、布局不符等错误不能通过同意格式化绕过。
无法确认可保留 Android 数据时,安装器先报出具体原因,再询问“无法保留 Android 数据卸载,是否格式化?”。取消不会写入设备;同意后仅生成新的卸载计划。**格式化会清空 Android 应用、账号、照片和内部存储。** 请备份个人文件,并在最终计划中核对数据影响及容量后再确认执行。安装归属不明、布局不符等错误不能通过同意格式化绕过。
原本装在未分配空间中的 OpenWrt,卸载后该空间恢复为空闲;不会额外扩大 Android,也不要求重置 Android。TF 卡和 userdata 镜像不使用此内置分区卸载入口。TF 卡安装请先回到 Android 并设为默认启动,卸载对应 Magisk 模块(如有),再自行格式化安装 OpenWrt 的目标分区;不必整卡格式化,其他分区的文件可以保留。
有原记录证明 OpenWrt 装在未分配空间时,卸载后该空间恢复为空闲,不额外扩大 Android,也不要求重置。没有原记录时不会猜测历史用途,而按上面的相邻分区规则生成计划。TF 卡、userdata 镜像和未列入 GPT 的旧版隐藏区域安装不使用此内置分区卸载入口。TF 卡安装请先回到 Android 并设为默认启动,卸载对应 Magisk 模块(如有),再自行格式化安装 OpenWrt 的目标分区;不必整卡格式化,其他分区的文件可以保留。
确认后保持供电,等待离线卸载及自动重启。如果设备一直停留在原来的 Android,请手动重启一次;已经开始重启时不要反复重启。需要重置时,完成 Android 初始设置、重新启用调试并授权电脑。root 仍可用时直接继续;否则恢复 Magisk 并允许 root 请求。安装器确认同一设备、Android 启动状态和实际容量后才显示完成。
@@ -188,13 +190,15 @@ If the device has started but the installer keeps waiting, check the connected n
### Remove internal OpenWrt and return space
First export needed configuration from the OpenWrt management page, then return to rooted Android using the device’s system switch, enable debugging and authorize this computer. Under Advanced options, choose Uninstall and return space, inspect the device and review the plan. Keep the original record and full backups from the installation that created this partition. On another computer, import that recovery folder through Continue an unfinished installation first. If evidence is missing or does not match, stop and keep the partition; do not try legacy uninstall scripts.
First export needed configuration from the OpenWrt management page, then return to rooted Android using the device’s system switch, enable debugging and authorize this computer. Under Advanced options, choose Uninstall and return space, inspect the device and review the plan. Matching original installation records and full backups are preferred; they can be imported on another computer.
**Original installation records are not mandatory.** Without usable original backups, the installer verifies the current partition table, boot image and installed-system markers. Only an OpenWrt partition immediately after userdata can return its capacity to Android; other free space is not merged. A nonadjacent partition becomes unallocated without enlarging Android. Review Android capacity, Space returned to Android and Space released as unallocated. Uncertain ownership or boundaries stop removal; a partition name alone is insufficient. A new removal record and backups are created before execution. Keep them for recovery.
Removal rechecks current Android encryption, the data device and filesystem tools. **Confirmed unencrypted data directly on userdata with supported tools is checked and grown offline while preserving Android data.** OpenWrt and its settings are still deleted. Back up what you need first.
If preservation cannot be confirmed, the installer reports the reason and asks “Cannot preserve Android data. Format instead?”. Cancel writes nothing to the device. Agreeing only creates a new removal plan. **Formatting erases Android apps, accounts, photos and internal storage.** Back up personal files, review the capacity and data impact, then confirm the final plan. Missing original records or mismatched layouts cannot be bypassed by agreeing to format.
If preservation cannot be confirmed, the installer reports the reason and asks “Cannot preserve Android data. Format instead?”. Cancel writes nothing to the device. Agreeing only creates a new removal plan. **Formatting erases Android apps, accounts, photos and internal storage.** Back up personal files, review the capacity and data impact, then confirm the final plan. Uncertain installation ownership or mismatched layouts cannot be bypassed by agreeing to format.
For an installation in previously unallocated space, only OpenWrt is removed. That space becomes free again; Android is not enlarged or reset. This internal-partition option does not remove TF-card or userdata-image installations. For TF, return to Android, set Android as the default, remove the related Magisk module if installed, then format the OpenWrt target partition yourself; other card partitions can be kept.
If original records prove that OpenWrt used previously unallocated space, it becomes free again without enlarging or resetting Android. Without those records, the adjacent-partition rule above applies instead of guessing the historical layout. This option does not remove TF-card, userdata-image or old hidden-area installations outside GPT. For TF, return to Android, set Android as the default, remove the related Magisk module if installed, then format the OpenWrt target partition yourself; other card partitions can be kept.
Keep power connected after confirmation and wait for offline removal and automatic restart. If the original Android session never restarts, restart it once. Avoid repeated restarts once removal has begun. After a required reset, finish Android setup, enable debugging and authorize the computer. Existing working root is accepted; restore Magisk only when necessary. Completion requires verification of the same device, Android boot and actual capacity.
+11 -3
View File
@@ -4,9 +4,11 @@ The canonical implementation is `e5-linux/installer`. `sync.py <mu300-repository
Protocol 1: one JSON object per line on stdin/stdout. A request is `{"protocol":1,"id":1,"command":"hello","params":{}}`. Responses contain the same `id`, `type:"response"` and `data:{ok,result}` or `{ok:false,error}`. Events use `type:"transaction"`, `"transfer"`, `"log"`. No terminal-text matching. Legacy stdout/stderr becomes sanitized diagnostic log events, independently of named state/effect callbacks.
`probe` and `plan` accept `choices.method: "uninstall"` (the probe uses its existing `method` parameter). Removal applies only to an installer-created `e5root`/`mu300root` partition with matching original installation journal and checksummed GPT backups. Planning compares disk GUID, partition identities and all unrelated entries; it distinguishes userdata shrink from factory unallocated space. It records `previous_android_bytes`, `android_bytes`, `openwrt_bytes`, `reclaimed_bytes`, `wipe` and the source transaction. Missing/conflicting evidence stops before writes. The frontend cannot supply GPT snapshots or command text.
`probe` and `plan` accept `choices.method: "uninstall"` (the probe uses its existing `method` parameter). Removal applies only to a verified internal `e5root`/`mu300root` partition. Matching original installation journals and checksummed GPT backups take priority; they prove shrink reversal versus original unallocated-space installation. Without a usable original record, the backend verifies current GPT copies, Linux partition type/identity/alignment, exact kernel node geometry, idle/unmapped state, installed opposite boot/ramdisk route, clean ext4 metadata and the family's fixed installation markers. A bounded host reader reads metadata only: no filesystem mount, helper executable or repair is run. A partition name or boot command line alone is insufficient. Unverified/ambiguous evidence and conflicting valid originals stop before writes. The frontend cannot supply GPT snapshots or command text.
Removal uses the existing `start` confirmation, device mutex, backup transport, cancel boundary, journal export/import and `resume`/`retry` commands. Snapshots are persisted under the new transaction's `uninstall/` directory before boot writes. A one-shot ramdisk overlay retains the packaged kernel and board driver initialization, then runs the shared offline worker before root mounting/install/update. It checks both GPT copies against the recorded before/after bytes, commits backup first with flush/readback, copies the running Android slot's boot to the inactive slot and selects Android. Shrink reversal arms stock recovery's data reset; factory-gap reversal does not resize or reset userdata. `uninstall_armed` warns that pausing the computer cannot withdraw an already staged device action.
Plans record `previous_android_bytes`, `android_bytes`, `openwrt_bytes`, `reclaimed_bytes`, `released_unallocated_bytes`, `wipe`, `layout_source` (`original_record` or `device`) and nullable `source_transaction`. Device-based plans do not reconstruct historical capacity: if the known root starts at userdata end + 1, only that root's range can enlarge userdata, ending exactly at the current root end. A nonadjacent root becomes unallocated without resizing Android. Unlisted gaps, trailing space and unrelated entries are never merged. The UI explains this rule and displays both returned-to-Android and released-unallocated capacity.
Removal uses the existing `start` confirmation, device mutex, backup transport, cancel boundary, journal export/import and `resume`/`retry` commands. A new removal transaction is always required even when no old installation transaction exists. Snapshots are persisted under its `uninstall/` directory before boot writes. A one-shot ramdisk overlay retains the packaged kernel and board driver initialization, then runs the shared offline worker before root mounting/install/update. It checks both GPT copies against the recorded before/after bytes, commits backup first with flush/readback, copies the running Android slot's boot to the inactive slot and selects Android. Userdata enlargement uses the preservation/reset policy below; release-only removal neither resizes nor resets userdata. `uninstall_armed` warns that pausing the computer cannot withdraw an already staged device action.
Stages include `uninstall_prepare`, `uninstall_offline`, existing Android setup/debugging/root waits, `verify_android` and optional `uninstall_restore_boot`. Waiting has no initialization deadline. Completed GPT restoration never re-arms reset on reconnect/restart. Interrupted boot staging is resumed only after exact GPT/misc/Android readback; unknown layouts and partial GPT mismatches stop for offline recovery. A staged `openwrt.uninstall=1` boot marker and local unfinished journals block new installation/trial plans, including after the computer record is lost. Temporary-boot recognition also rejects this marker. Final completion verifies the restored GPT, absence of the OpenWrt partition, Android filesystem/mapping capacity, consumed recovery request and Android boot selection. `result.uninstalled` distinguishes removal from OpenWrt install/update results; diagnostics include `android_capacity_check`.
@@ -53,4 +55,10 @@ When preservation is unavailable, `plan` returns `{confirmation_required:"format
Schema 2 persists the data action, reset authorization, filesystem identity and maintenance-tool hashes. Execution rechecks current preservation eligibility and tools. Tool incompatibility, filesystem check errors and short final capacity never fall through to formatting. Shrink-only F2FS `-s` is not used for growth. The offline worker checks the unmounted data first, commits the verified GPT, requires a kernel partition-table reread and verifies the exact restored userdata start/size before growing its partition node, rechecks filesystem identity/capacity and only then restores Android boot. Growth retries check identity and the same worker image and re-arm only misc; they do not replay partition edits or arm Recovery. No artificial progress percentage is reported for fsck/resize.
Unconfirmed schema 1 removal plans must be regenerated. Already armed schema 1 transactions retain the originally confirmed reset/gap contract; no policy is silently changed during resume. Geometry/identity/original-backup failures are not eligible for reset fallback. Once offline execution has begun, an error stops that transaction for verification/recovery; it cannot turn a preservation transaction into a reset transaction without a new reviewed operation.
Unconfirmed schema 1 removal plans must be regenerated. Already armed schema 1 transactions retain the originally confirmed reset/gap contract; no policy is silently changed during resume. Geometry/identity/installation-evidence failures are not eligible for reset fallback. Once offline execution has begun, an error stops that transaction for verification/recovery; it cannot turn a preservation transaction into a reset transaction without a new reviewed operation.
## Removal without the original record (journal schema 3)
Schema 3 extends schema 2 with `installation_evidence`: hashes of the installed boot header, ramdisk, ext4 superblock and exact fixed marker files. Evidence is rechecked before preparing device writes. The reset-choice fingerprint also includes it. E5 requires its internal-root boot route, `etc/e5/part-root` naming this disk and OpenWrt distribution identity. MU300 requires the native `part`/completed `install-part` ramdisk route, container boot selector, `openwrt/etc/mu300/desktop-mode=part` and OpenWrt identity. Prepared roots, unknown boot routes, symlinks, unclean/unsupported ext4 and mounted/mapped roots are rejected. The host reader supports bounded regular files/directories with direct blocks or initialized extents and checks partition/filesystem bounds; it never evaluates their content as code.
On import/restart, before/after snapshots are recomputed from the saved **current** layout using the adjacent-root rule. Hash changes cannot authorize a wider target or alter unrelated entries. Once armed, resume uses the new uninstall record, not any original installation record or deleted root markers. Recovery from an interrupted inactive-boot write still requires exact saved GPT/misc/Android checks; when boot staging alone must be retried, the original Linux boot proof comes from its checksummed **new uninstall backup** while root evidence is checked live. Completed GPT work and formatting are never replayed. If this new record is lost while `openwrt.uninstall=1` is staged, the existing pending-operation guard still stops new plans; absence of an old installation record is not permission to guess an interrupted removal.
+18 -14
View File
@@ -5,10 +5,10 @@
".gitignore": "a5773f83330fc9adddfd159fe0391bccffbf7663dccb2b873f6b2d1b2d2eca11",
"backend_entry.py": "238a3534a790ce46ae396040623117299f78b9fc9fc89fe152bfdd5788f7b664",
"build.py": "f84fd40d9db9b39a0f8a35cee32dafc08f7dc774e17d76b060f49df73b5c8a10",
"GUIDE.md": "4d2aa30e0b956a0bf0e223be8d3cee430a289f16e5c372e34ed06fa41b84696c",
"GUIDE.md": "5bc67ffa85be488f487b44ca2ba6bdb4c191a223254a49eed6298743dd6b6cd9",
"package_gui.py": "bcc61763c43b02c45cae27a7452516dd0d76c871a11ded98a04c4711becd1b62",
"platform-tools.json": "d8fcf938e150bc314b5e6b2660c540976bb12ea6108fa75a8fb183115ebbd01e",
"PROTOCOL.md": "78cc8235acb436673cf5697952ae3591313bc6c44ea23e1a7e7718fd19c82ab8",
"PROTOCOL.md": "d4e5ba7b946023649769ea5de514df548c871ca082b54d9b2040ceecdad8ac4e",
"README.md": "fb8ed271afbc38d7a569fb5b701e48c2659eb5a42be7808950ca725f65f2a5db",
"release.py": "852e75824bd64178943d9725790a2ad8739826bf8b5c1bba3413012ffeb44123",
"requirements-build.txt": "762ee573a22c790eb3c5ccba4616632373d947dc88eb91fc85f3c678ac7b2259",
@@ -19,7 +19,7 @@
"backend/gpt.py": "4eca5ccf458ef86b9dfcea6388da61defe61af6389565cadf2fda6616e28b791",
"backend/helpers.py": "ac5422e60bcdd0273baa5d5796d64aa5b1e0687a709afc5bdf9c8501a7154d36",
"backend/package.py": "5c55e91f2c348ac957d7803810e6396edf3aae573da401ecf46e773ac75e70ee",
"backend/service.py": "ebfabf9f09cb04f62065325c138e0351136e9ffa85512aaf81939e5c133008b4",
"backend/service.py": "318fd389eb11766e414d743bf66d607b0b1fcc1a3ed225375353479a62d01877",
"backend/state.py": "bc17eac46b099524b2f2ad687d9fd6fcd3d867929487ef4a80d528992d6b3d48",
"backend/transport.py": "27b57661820ba74ef86336a93d08ab43c1ea49eafae1edafb12a324e30bb0d3c",
"backend/__init__.py": "4227d63763e764fd2de7fc2bc13e474ae5de33176fb57aa0fd51cbb4ad80b88c",
@@ -159,9 +159,9 @@
"verification/windows-packages.json": "2527a520a27d9eb0f9243aa9e2ed05b0e4b90caefc8257ea3afe76acdb75a19d",
"ui/src/help-data.ts": "19fa8dd35fcef0ebc2726c16c641e5c357dfefe1342f9460c8da848339fb146b",
"ui/src/help-i18n.ts": "041a7fa8ac2c3f0adfc3d2f25331801e907915ad58d08eaa464d4165f0a6e5f1",
"ui/src/i18n.ts": "e235286c4bcbc1613d46f558ec8694a13cc0eb25fd4190ea7e786433b9fde289",
"ui/src/main.tsx": "448f41c3fcafe5115fc5d9a109e33ea4014206a0d871bda0d2838da4a6484647",
"ui/src/protocol.ts": "af018d272e544fc80b5f506a7280702b18ed03dd014efcd9d3aa33818a99d8cf",
"ui/src/i18n.ts": "61901828bde3ac669161049dd3aa3b85eb9e5d3a986f5b58489cee40f59cc515",
"ui/src/main.tsx": "7c8072749473464cdbf36b429e82fba1b810b56533d4e5cab5b3d06d64923192",
"ui/src/protocol.ts": "de30687657a75e06498fdcfd03727c8a1c6b09eadbb5e189ad62d7db8865ef17",
"ui/src/style.css": "9cc7a11d7d484842d6e2ec48b0ff24d16949305217585ff11620edcd5e6c0921",
"ui/src/utils.ts": "dd51582c0905c3507bd5dc3d32215a43fc156f6432042a7deb393fe4258b05ba",
"ui/src/vite-env.d.ts": "65996936fbb042915f7b74a200fcdde7e410f32a669b1ab9597cfaa4b0faddb5",
@@ -259,19 +259,23 @@
"tests/test_macos_integration.py": "9b42dd66e6a8ede7e1d404ea61ca17a959e6767749ce63c63596f8b982f78cc8",
"tests/test_release_archive.py": "bcf31454768873206e27a52221749dc58b5265c37857dae23c7625157faf4288",
"tests/test_capacity_recovery.py": "ba5412707ba6727f485f02de2ed34d9cbc92a2841f45ea9ab2281b4587017450",
"backend/uninstall.py": "687c15ffa046eb936ef8c670464ee25b060c7480e3404a9410c68f25cd38613b",
"backend/uninstall.py": "4fde2d394bd1b9f1bf4c067546339c786493e6283c7f8220da4a231de3c83496",
"backend/uninstall_boot.py": "0ceae95463f845856edcfffacb12b8845a9f3c848e0bd42b2af45a930ac2ee74",
"backend/uninstall_worker.py": "aacc0c7d5d03dc337e2117961f0b56e45ef3c5c18c200568949d00c7fb7b1af5",
"tests/test_uninstall.py": "b9b7e7774eb978b576e8e2fa89664ecd29a41787a5c047d34f4eb2c29b97f051",
"tests/uninstall_smoke.py": "69f7d8318fdf1f4b46fb69044cc84d44212a88da94ce74999139e43856b5b7ed",
"screenshots/uninstall-plan-reset-zh.png": "bd699c24973917a1943fecabdebd5d6ba4ef11ca9993b8a7598e4545473b8d91",
"screenshots/uninstall-plan-gap-en.png": "1d7fa4ba9b6a4c4021aa6faaddcc6ecc4af3e85c0703a10ee9fd3ef92e8470c5",
"screenshots/uninstall-complete-zh.png": "5221a2d982573c70a8bdb415e5545190493708fc48f72bf30334420db9ad5793",
"tests/test_uninstall.py": "86dc427aafe0e3bd842315d8a718216382acd80d20828176106648a8ca8754c8",
"tests/uninstall_smoke.py": "fd7a7b6a4c7438277f3f256d99d5705570b3f10d470e943ec3dc405c45639563",
"screenshots/uninstall-plan-reset-zh.png": "1e95fae698221291deff9609b48c03f45b60ae75b13ab8ebd8e7f93dd7e2ffdd",
"screenshots/uninstall-plan-gap-en.png": "f2a697038f1d7bda324ff287ee92b2c87270a5d539d3181fafc6d7528ac495ab",
"screenshots/uninstall-complete-zh.png": "941b60d13e9ee87c497c97d8f8968e91d63bb8cf54c8acc4d7caa3c18e613f08",
"backend/uninstall_growth.py": "c71dcb3d52b18226c8698dd2363f1c934cc1e4910de67b0769987f283535f896",
"tests/test_uninstall_growth.py": "f445e80870a314020e890333afd377cccb786184aaa15e8be165b507af5448c4",
"screenshots/uninstall-plan-preserve-zh.png": "8e696021ec4fe4d3294a79f325fed87c7aa6c18e40df8bb4816bd5567f0f6280",
"screenshots/uninstall-plan-reset-en.png": "4891c60c45f1515df2a950aa553528c800cb646e4a8dab757e917a8850787192",
"screenshots/uninstall-reset-choice-zh.png": "dd5ec89ccd5e2ca34ad56d0289ed07a8e25a0c1fbf251f7a3493deec4904bd64"
"screenshots/uninstall-plan-reset-en.png": "25cc5c94d0b1598d30988e1d613e30ad24924120a440fe23f5e8051599751700",
"screenshots/uninstall-reset-choice-zh.png": "dd5ec89ccd5e2ca34ad56d0289ed07a8e25a0c1fbf251f7a3493deec4904bd64",
"backend/install_evidence.py": "27931749624bf6bcdc376e04b4bfbdadee73fc7c8e9013e1665ce16d30d56cd3",
"tests/test_uninstall_evidence.py": "2727c5816b0e3e39cf3a85e4b276510735933fbfb97f0f0716c3606fa46189f8",
"screenshots/uninstall-plan-device-zh.png": "1a34bd76f4b554ff7496d0745f3ee6ffa3785ce59769662254d046b5501c9807",
"screenshots/uninstall-plan-device-gap-en.png": "005eb55faacdaa4f4fcdc3d50de25f4358d482ea8efcd704cb08ef90915e92d9"
},
"compatibility_files": {
"desktop/binary_io.py": "25e30cf4f3b23e960b05ae512f06d617dd958835125678ea4c07a2fbc4d3420f",
+232
View File
@@ -0,0 +1,232 @@
"""Bounded read-only evidence for removing an installation without its old journal.
Only fixed, small files are read from an idle ext4 partition. No mount, repair,
device-side helper, executable from the installed system or filesystem write.
This proves a known installation, not the historical size of Android userdata.
"""
import hashlib
import re
import stat
import struct
from .boot_image import inspect_linux_boot
from .state import RecoveryRequired
from .uninstall_boot import archives, entries
class Ext4Evidence:
"""Minimal ext4 reader for regular marker files and their directories only."""
def __init__(self, read, capacity):
self.read = read
self.capacity = capacity
self.remaining = 4 << 20
self.cache = {}
self.super = sb = self.raw(1024, 1024)
if sb[56:58] != b'\x53\xef':
raise ValueError('OpenWrt partition is not ext4')
log = struct.unpack_from('<I', sb, 24)[0]
incompat = struct.unpack_from('<I', sb, 96)[0]
state = struct.unpack_from('<H', sb, 58)[0]
# Reject recovery-needed, meta_bg, inline data, encryption, compression
# and other layouts this deliberately small reader does not implement.
if log > 2 or incompat & ~(0x2 | 0x40 | 0x80 | 0x200 | 0x2000) or state != 1:
raise ValueError('OpenWrt filesystem is unclean or unsupported; boot and shut it down cleanly first / OpenWrt 文件系统未正常卸载或布局不受支持,请先启动 OpenWrt 并正常切回 Android')
self.block_size = 1024 << log
self.blocks = struct.unpack_from('<I', sb, 4)[0]
if incompat & 0x80:
self.blocks |= struct.unpack_from('<I', sb, 336)[0] << 32
self.inodes, = struct.unpack_from('<I', sb, 0)
self.per_group, = struct.unpack_from('<I', sb, 40)
self.inode_size, = struct.unpack_from('<H', sb, 88)
self.desc_size = struct.unpack_from('<H', sb, 254)[0] if incompat & 0x80 else 32
if (not self.blocks or self.blocks*self.block_size > capacity or not self.inodes or
not self.per_group or not 128 <= self.inode_size <= self.block_size or
self.inode_size & (self.inode_size-1) or self.desc_size not in (32,64) or
sb[104:120] == bytes(16)):
raise ValueError('Invalid OpenWrt filesystem geometry or identity')
self.filesystem_limit = self.blocks*self.block_size
def raw(self, offset, size):
if offset < 0 or size <= 0 or offset+size > getattr(self,'filesystem_limit',self.capacity):
raise ValueError('Filesystem read exceeds the OpenWrt partition')
key = (offset,size)
if key not in self.cache:
self.remaining -= size
if self.remaining < 0:
raise ValueError('Installation evidence exceeds the metadata read limit')
data = self.read(offset,size)
if len(data) != size:
raise ValueError('Incomplete OpenWrt metadata read')
self.cache[key] = data
return self.cache[key]
def block(self, number):
if not 0 < number < self.blocks:
raise ValueError('Invalid OpenWrt metadata block')
return self.raw(number*self.block_size,self.block_size)
def inode(self, number):
if not 1 <= number <= self.inodes:
raise ValueError('Invalid OpenWrt inode')
group, index = divmod(number-1,self.per_group)
offset = (2 if self.block_size == 1024 else 1)*self.block_size+group*self.desc_size
desc = self.raw(offset,self.desc_size)
table = struct.unpack_from('<I',desc,8)[0]
if self.desc_size == 64:
table |= struct.unpack_from('<I',desc,40)[0] << 32
if not 0 < table < self.blocks:
raise ValueError('Invalid OpenWrt inode table')
return self.raw(table*self.block_size+index*self.inode_size,self.inode_size)
def contents(self, inode, kind, limit):
mode = struct.unpack_from('<H',inode,0)[0]
if stat.S_IFMT(mode) != kind or not struct.unpack_from('<H',inode,26)[0]:
raise ValueError('Installation evidence must use regular files and directories, without symlinks / 安装标记路径必须是普通目录和文件,不能是符号链接')
size = struct.unpack_from('<I',inode,4)[0] | struct.unpack_from('<I',inode,108)[0] << 32
if not 0 < size <= limit:
raise ValueError('Installation evidence file is empty or too large')
count = (size+self.block_size-1)//self.block_size
pointers = {}
flags = struct.unpack_from('<I',inode,32)[0]
if flags & (0x4 | 0x800 | 0x100000 | 0x10000000):
raise ValueError('Unsupported OpenWrt evidence inode flags')
if not flags & 0x80000: # old files may use direct block pointers
if count > 12:
raise ValueError('Unsupported indirect evidence file')
pointers = dict(enumerate(struct.unpack_from('<12I',inode,40)[:count]))
else:
visited = set()
def extents(raw, expected=None):
magic, used, maximum, depth = struct.unpack_from('<HHHH',raw,0)
if (magic != 0xf30a or not 0 < used <= maximum <= (len(raw)-12)//12 or
depth > 4 or expected is not None and depth != expected):
raise ValueError('Invalid OpenWrt extent tree')
for at in range(12,12+used*12,12):
logical, = struct.unpack_from('<I',raw,at)
if depth:
low, high = struct.unpack_from('<IH',raw,at+4)
block = low | high << 32
if block in visited:
raise ValueError('Repeated OpenWrt extent node')
visited.add(block)
extents(self.block(block),depth-1)
else:
length, high, low = struct.unpack_from('<HHI',raw,at+4)
if not 0 < length <= 32768:
raise ValueError('Unwritten OpenWrt evidence extent')
physical = low | high << 32
if physical <= 0 or physical+length > self.blocks:
raise ValueError('OpenWrt extent exceeds the filesystem')
for n in range(logical,min(logical+length,count)):
if n in pointers:
raise ValueError('Overlapping OpenWrt extents')
pointers[n] = physical+n-logical
extents(inode[40:100])
if set(pointers) != set(range(count)):
raise ValueError('Installation evidence contains sparse or missing blocks')
return b''.join(self.block(pointers[n]) for n in range(count))[:size]
def file(self, path):
node = self.inode(2)
for component in path.split('/'):
content = self.contents(node,stat.S_IFDIR,256 << 10)
found = []
at = 0
while at < len(content):
if len(content)-at < 8:
raise ValueError('Truncated OpenWrt directory')
number, length, namelen = struct.unpack_from('<IHB',content,at)
if (length < 8 or length % 4 or length > self.block_size-at%self.block_size or
at+length > len(content) or namelen > length-8):
raise ValueError('Invalid OpenWrt directory entry')
if number and content[at+8:at+8+namelen] == component.encode():
found.append(number)
at += length
if len(found) != 1:
raise ValueError('Missing or ambiguous installed-system marker / 安装标记缺失或存在重名: '+path)
node = self.inode(found[0])
return self.contents(node,stat.S_IFREG,4096)
def inspect_installation(adapter, device, root, *, boot_backup=None):
"""Return fresh, device-bound evidence. Caller has already validated both GPTs."""
try:
adb = adapter.adb
storage = device['storage']; disk = storage['NODE'].split('p')[0]
node = disk+'p'+str(root['n']); capacity = (root['end']-root['start']+1)*512
if (not re.fullmatch(r'mmcblk\d+p\d+',node) or storage.get('ROOT') != node or
storage.get('ROOT_START') != root['start'] or storage.get('ROOT_SIZE')*512 != capacity):
raise ValueError('Kernel OpenWrt node differs from verified GPT; reboot Android / 内核分区节点与 GPT 不符,请重启 Android')
# Android must not have the target mounted or mapped. Only metadata in
# this partition is read; neither userdata nor an unlisted gap is scanned.
idle = adb.shell('set -e; n='+node+'; h=$(ls -A /sys/class/block/$n/holders); '
'd=$(cat /sys/class/block/$n/dev); '
'm=$(awk -v n="$d" \'$3==n {print "BUSY"}\' /proc/self/mountinfo); '
'if [ -z "$h$m" ]; then echo IDLE; else echo BUSY; fi',root=True)
if idle.strip() != 'IDLE':
raise ValueError('OpenWrt partition is mounted or mapped / OpenWrt 分区仍被挂载或映射,请先释放占用')
slot = device['slot'].removeprefix('_'); other = 'b' if slot == 'a' else 'a'
read_boot = adb.read
if boot_backup is None:
boot_size = int(adb.shell('blockdev --getsize64 /dev/block/by-name/boot_'+other,root=True).strip())
else:
# An interrupted, verified inactive-boot write can replace the live
# signature. Recovery has checked that write; use its checksummed
# original boot backup for the installation proof, never an old GPT.
boot_size = len(boot_backup)
def read_boot(command):
match = re.fullmatch(r'dd if=/dev/block/by-name/boot_[ab] bs=(\d+)(?: skip=(\d+))? count=(\d+) 2>/dev/null',command)
if not match:
raise ValueError('Unsupported backup metadata read')
bs, skip, count = int(match[1]),int(match[2] or 0),int(match[3])
return boot_backup[bs*skip:bs*(skip+count)]
boot = inspect_linux_boot(read_boot,boot_size,adapter.kind,other)
start = 4096+((boot['kernel_bytes']+4095)&~4095)
size = boot['ramdisk_bytes']; count = (size+4095)//4096
ram = read_boot(f'dd if=/dev/block/by-name/boot_{other} bs=4096 skip={start//4096} count={count} 2>/dev/null')
if len(ram) != count*4096:
raise ValueError('Incomplete installed ramdisk')
files = {}
wanted = {'init','etc/mu300-desktop-root-mode','etc/mu300-desktop-identity','etc/mu300-desktop-prepare'}
for archive in archives(ram[:size]):
for name, content, mode in entries(archive):
if name in wanted:
if stat.S_IFMT(mode) != stat.S_IFREG or len(content) > 256 << 10:
raise ValueError('Unsupported installed boot evidence')
files[name] = content
if adapter.kind == 'e5':
if b'/etc/e5/part-root' not in files.get('init',b''):
raise ValueError('Installed E5 boot does not recognize internal partitions / 已安装的 E5 启动镜像不支持内置分区')
paths = {'etc/e5/part-root':None,'etc/openwrt_release':None}
else:
# install-part boots keep this mode even after a successful install;
# completed root markers below distinguish them from preparation.
if (files.get('etc/mu300-desktop-root-mode',b'').strip() not in (b'part',b'install-part') or
'etc/mu300-desktop-prepare' in files or
b'/etc/mu300-desktop-storage.sh' not in files.get('init',b'')):
raise ValueError('Installed MU300 boot has no completed internal-partition route / 已安装的 MU300 启动镜像未确认完成内置分区安装')
paths = {'openwrt/etc/mu300/desktop-mode':b'part', '.mu300/boot-os':None,'openwrt/etc/openwrt_release':None}
def read(offset,length):
begin = offset//512; end = (offset+length+511)//512
raw = adb.read(f'dd if=/dev/block/{node} bs=512 skip={begin} count={end-begin} 2>/dev/null')
if len(raw) != (end-begin)*512:
raise ValueError('Incomplete OpenWrt partition read')
return raw[offset%512:offset%512+length]
fs = Ext4Evidence(read,capacity)
for path, expected in paths.items():
value = fs.file(path).strip()
if expected is not None and value != expected:
raise ValueError('Installed marker differs / 安装标记内容不符: '+path)
if path.endswith('openwrt_release') and not re.search(rb"(?m)^DISTRIB_ID=['\"]OpenWrt['\"]$",value):
raise ValueError('OpenWrt distribution identity is missing / 缺少 OpenWrt 系统身份信息')
if path.endswith('part-root') and value not in (('e5root /dev/'+disk).encode(),('e5root /dev/block/'+disk).encode()):
raise ValueError('E5 partition marker names a different disk / E5 安装标记指向另一块磁盘')
if path == '.mu300/boot-os' and value not in (b'android',b'openwrt'):
raise ValueError('MU300 boot selector is unsupported / MU300 启动选择标记不受支持')
paths[path] = hashlib.sha256(value).hexdigest()
return {'version':1,'boot_header_sha256':boot['header_sha256'],
'ramdisk_sha256':hashlib.sha256(ram[:size]).hexdigest(),
'superblock_sha256':hashlib.sha256(fs.super).hexdigest(),'markers':paths}
except (ValueError,KeyError,TypeError,struct.error) as error:
raise RecoveryRequired('Cannot verify the installed OpenWrt partition without original backups / '
'没有原备份,且无法核实设备上的 OpenWrt 安装;已停止: '+str(error)) from error
+1 -1
View File
@@ -32,7 +32,7 @@ def plan_install(package, device, choices):
if device.get('readiness') != 'ready':
raise ValueError('Device is not ready / 设备尚未就绪')
if method == 'uninstall':
raise ValueError('Uninstall requires verified original installation backups / 卸载需要验证原安装备份')
raise ValueError('Uninstall requires device evidence planning / 卸载需要专用的设备证据检查与卸载计划')
if method == 'update':
return {'method': method, 'wipe': False, 'openwrt_bytes': device['capacity'], 'two_stage': False,
'preserves_settings': True, 'host': choices['host'], 'grow': True}
+91 -20
View File
@@ -1,4 +1,4 @@
"""Journaled removal of a proven installer-created internal partition.
"""Journaled removal of a verified internal OpenWrt partition.
No device writes during planning. All GPT changes run in the existing model's
initramfs, with stock recovery owning Android reset and encryption.
@@ -12,6 +12,7 @@ import struct
import subprocess
import time
import zlib
import uuid
from . import gpt
from .boot_image import inspect_linux_boot, trial_control
@@ -19,6 +20,7 @@ from .state import Cancelled, RecoveryRequired, atomic_json, sha
from .transport import push_chunks
from .uninstall_boot import build
from .uninstall_growth import PreservationUnavailable, eligible, growth_tools, base_boot
from .install_evidence import inspect_installation
def partition(info, name):
@@ -33,6 +35,45 @@ def table(first):
return first[at*512:at*512+count*128]
def with_table(current, updated, sectors):
output = []
for raw, header, offset in ((current[0], 512, struct.unpack_from('<Q', current[0], 584)[0]*512),
(current[1], len(current[1])-512, 0)):
raw = bytearray(raw); raw[offset:offset+len(updated)] = updated
struct.pack_into('<I', raw, header+88, zlib.crc32(updated))
struct.pack_into('<I', raw, header+16, 0)
length = struct.unpack_from('<I', raw, header+12)[0]
struct.pack_into('<I', raw, header+16, zlib.crc32(raw[header:header+length]))
output.append(bytes(raw))
gpt.gpt_space(*output,sectors)
return output
def device_layout(current, sectors, name):
"""Remove only this root; extend userdata only into its contiguous extent.
This is a new, bounded allocation, never a reconstruction of historical GPT.
Unlisted space and any partition before/after the root remain untouched.
"""
info = gpt.gpt_space(*current,sectors)
data, root = partition(info,'userdata'), partition(info,name)
updated = bytearray(table(current[0]))
entry = updated[(root['n']-1)*128:root['n']*128]
if (entry[:16] != uuid.UUID('0fc63daf-8483-4772-8e79-3d69d8477de4').bytes_le or
entry[16:32] == bytes(16) or entry[48:56] != bytes(8) or
root['start'] % 2048 or (root['end']+1) % 2048 or
root['end']-root['start']+1 < 4194304):
raise RecoveryRequired('Unsupported OpenWrt partition type, identity or alignment / OpenWrt 分区类型、身份或对齐方式不受支持')
if any(updated[(p['n']-1)*128+16:(p['n']-1)*128+32] == entry[16:32]
for p in info['parts'] if p['n'] != root['n']):
raise RecoveryRequired('OpenWrt partition GUID is duplicated / OpenWrt 分区 GUID 存在重复')
expands = root['start'] == data['end']+1
target = {**data,'end':root['end']} if expands else data
updated[(root['n']-1)*128:root['n']*128] = bytes(128)
struct.pack_into('<Q',updated,(data['n']-1)*128+40,target['end'])
return with_table(current,updated,sectors), target, root, expands
def restored_layout(original, current, sectors, name):
"""Reverse proven entry edits. The final bool means growth, not reset consent."""
old = gpt.gpt_space(*original, sectors)
@@ -63,15 +104,7 @@ def restored_layout(original, current, sectors, name):
updated = bytearray(newtable)
updated[(root['n']-1)*128:root['n']*128] = oldtable[(root['n']-1)*128:root['n']*128]
struct.pack_into('<Q', updated, (data['n']-1)*128+40, prior['end'])
output = []
for raw, header, offset in ((current[0], 512, struct.unpack_from('<Q', current[0], 584)[0]*512),
(current[1], len(current[1])-512, 0)):
raw = bytearray(raw); raw[offset:offset+len(updated)] = updated
struct.pack_into('<I', raw, header+88, zlib.crc32(updated))
struct.pack_into('<I', raw, header+16, 0)
length = struct.unpack_from('<I', raw, header+12)[0]
struct.pack_into('<I', raw, header+16, zlib.crc32(raw[header:header+length]))
output.append(bytes(raw))
output = with_table(current,updated,sectors)
verified = gpt.gpt_space(*output, sectors)
if any(p['name'] == name for p in verified['parts']):
raise RecoveryRequired('Root entry was not removed')
@@ -135,12 +168,16 @@ def prepare(adapter, store, device, authorize_reset=None):
matches.append((source, after, data, root, wipe))
except (OSError, ValueError, KeyError, RecoveryRequired):
continue
if not matches:
raise RecoveryRequired('No matching original installation record and verified GPT backup. Import the original recovery folder; do not use legacy uninstall scripts. / 缺少匹配的原安装记录和已校验 GPT 备份。请导入原安装备份目录;不要运行旧卸载脚本。')
# Conflicting historical layouts must be reviewed rather than guessed.
if any(item[1] != matches[0][1] for item in matches[1:]):
if matches and any(item[1] != matches[0][1] for item in matches[1:]):
raise RecoveryRequired('Original records disagree about Android capacity / 原安装记录对 Android 容量的记载冲突')
source, after, data, root, expands = matches[0]
proof = None
if matches:
source, after, data, root, expands = matches[0]
else:
after, data, root, expands = device_layout(current,total,name)
proof = inspect_installation(adapter,device,root)
source = None
node = storage['NODE'].split('p')[0]
if (storage['ROOT'] != node+'p'+str(root['n']) or storage['START'] != data['start'] or
storage['SIZE']*512 != device['userdata_bytes']):
@@ -167,6 +204,7 @@ def prepare(adapter, store, device, authorize_reset=None):
reason = str(error)
evidence = {'cid':device['cid'],'slot':device['slot'],'profile':device['profile'],
'layout':[hashlib.sha256(raw).hexdigest() for raw in current],
'installation':proof,
'encryption':[device.get(k) for k in ('encrypted','encryption_state','encryption_type')],
'volume':volume,'reason':reason}
fingerprint = hashlib.sha256(json.dumps(evidence,sort_keys=True).encode()).hexdigest()
@@ -180,12 +218,16 @@ def prepare(adapter, store, device, authorize_reset=None):
'android_bytes':(data['end']-data['start']+1)*512,
'previous_android_bytes':device['userdata_bytes'],
'reclaimed_bytes':(data['end']-data['start']+1)*512-device['userdata_bytes'],
'source_transaction':source['id']}
metadata = {'version':2,'action':action,'reset_authorized':wipe,'total':total,'front':space['front'],'tail':space['tail'],
'source_transaction':source['id'] if source else None,
'layout_source':'original_record' if source else 'device',
'released_unallocated_bytes':0 if expands else (root['end']-root['start']+1)*512}
metadata = {'version':2 if source else 3,'action':action,'reset_authorized':wipe,'total':total,'front':space['front'],'tail':space['tail'],
'tool_hashes':{name:hashlib.sha256(content).hexdigest() for name,content in tools.items()},
'root_start':root['start'],'root_size':root['end']-root['start']+1,
'nodes':{p['name']:node+'p'+str(p['n']) for p in space['parts']
if p['name'] in ('userdata',name,'misc','boot_a','boot_b')}, 'volume':volume}
if proof:
metadata['installation_evidence'] = proof
files = dict(zip(('before-first','before-last','after-first','after-last'), (*current,*after)))
return plan, metadata, files
@@ -218,17 +260,33 @@ class Uninstaller:
"""Imported journals must prove the same limited edits, not just hashes."""
required = {'before-first','before-last','after-first','after-last'}
version = self.meta.get('version')
if set(self.files) != required or version not in (1,2) or self.r['plan'].get('method') != 'uninstall':
if set(self.files) != required or version not in (1,2,3) or self.r['plan'].get('method') != 'uninstall':
raise RecoveryRequired('Incomplete uninstall journal / 卸载记录不完整')
storage = self.r['device']['storage']
if (self.r['package'].get('adapter') not in ('e5','mu300') or
not re.fullmatch(r'mmcblk[0-9]p[1-9][0-9]*',storage.get('NODE',''))):
raise RecoveryRequired('Invalid uninstall disk node / 卸载记录中的磁盘节点无效')
total = storage['DISK_SIZE']
before = (self.files['before-first'],self.files['before-last'])
after = (self.files['after-first'],self.files['after-last'])
family = self.r['package']['adapter']
name = 'e5root' if family == 'e5' else 'mu300root'
calculated, prior, root, expands = restored_layout(after,before,total,name)
if version == 3:
calculated, prior, root, expands = device_layout(before,total,name)
proof = self.meta.get('installation_evidence',{})
paths = {'etc/e5/part-root','etc/openwrt_release'} if family == 'e5' else {
'openwrt/etc/mu300/desktop-mode','.mu300/boot-os','openwrt/etc/openwrt_release'}
hashes = [proof.get(key,'') for key in ('boot_header_sha256','ramdisk_sha256','superblock_sha256')]
hashes += list(proof.get('markers',{}).values())
if (self.r['plan'].get('layout_source') != 'device' or self.r['plan'].get('source_transaction') is not None or
proof.get('version') != 1 or set(proof.get('markers',{})) != paths or
any(not isinstance(value,str) or not re.fullmatch('[a-f0-9]{64}',value) for value in hashes) or
self.r['plan'].get('released_unallocated_bytes') != (0 if expands else (root['end']-root['start']+1)*512)):
raise RecoveryRequired('Device installation evidence is incomplete / 设备端安装证据不完整')
else:
calculated, prior, root, expands = restored_layout(after,before,total,name)
wipe = expands
if version == 2:
if version >= 2:
action = self.meta.get('action')
if action != self.r['plan'].get('data_action') or action not in ('gap','reset','grow-ext4','grow-f2fs'):
raise RecoveryRequired('Uninstall data action differs / 卸载数据处理方式不一致')
@@ -282,6 +340,19 @@ class Uninstaller:
def arm(self, device):
from .adapter import debug_output
adb = self.adapter.adb
if self.meta['version'] == 3:
info = gpt.gpt_space(self.files['before-first'],self.files['before-last'],self.meta['total'])
root = partition(info,'e5root' if self.adapter.kind == 'e5' else 'mu300root')
original_boot = None
if self.r.get('uninstall_retry_linux_sha256'):
other = 'b' if device['slot'] == '_a' else 'a'
path = self.ctx.directory/'backup'/('boot_'+other+'.bin')
sums = json.loads((path.parent/'checksums.json').read_text())
if path.stat().st_size != 64 << 20 or sha(path) != sums.get(path.name):
raise RecoveryRequired('Original Linux boot backup is damaged / 原 Linux 启动备份已损坏')
original_boot = path.read_bytes()
if inspect_installation(self.adapter,device,root,boot_backup=original_boot) != self.meta['installation_evidence']:
raise RecoveryRequired('Installed OpenWrt changed; create a new removal plan / 设备上的 OpenWrt 已变化,请重新生成卸载计划')
tools = {}
if self.meta.get('action','').startswith('grow-'):
volume = android_volume(adb,device)
@@ -326,7 +397,7 @@ class Uninstaller:
nodes['misc'],nodes['boot_'+slot],nodes['boot_'+other]]
request += [self.meta[k] for k in ('total','front','tail','root_start','root_size')]
request += [int(self.r['plan']['wipe']),boot_bytes,android_sha]
if self.meta['version'] == 2:
if self.meta['version'] >= 2:
volume = self.meta['volume']
request += [self.meta['action'],device['storage']['START'],self.r['plan']['android_bytes']//512,
volume['filesystem_bytes'],volume.get('uuid','0'*32)]
Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

After

Width:  |  Height:  |  Size: 86 KiB

+2 -2
View File
@@ -187,7 +187,7 @@ class Journal(unittest.TestCase):
context=Context(self.store,record,lambda *_:None);persist(context,metadata,files)
return context
def test_plan_is_read_only_and_requires_verified_original_backups(self):
def test_plan_is_read_only_and_damaged_backups_need_device_evidence(self):
context=self.plan()
self.assertTrue(context.record['plan']['wipe'])
self.assertEqual(context.record['plan']['reclaimed_bytes'],4*GIB)
@@ -206,7 +206,7 @@ class Journal(unittest.TestCase):
self.assertEqual(context.record['plan']['reclaimed_bytes'],0)
self.assertEqual(context.record['plan']['openwrt_bytes'],4*GIB)
def test_missing_original_record_stops_before_device_volume_reads(self):
def test_missing_original_record_and_missing_device_evidence_stop_before_volume_reads(self):
with tempfile.TemporaryDirectory() as directory:
with self.assertRaisesRegex(RecoveryRequired,'original'):
prepare(self.adapter,Store(directory),self.device)
+356
View File
@@ -0,0 +1,356 @@
"""No-original-record removal: real metadata parsing, bounded GPT and recovery."""
import hashlib
import json
from pathlib import Path
import re
import shutil
import stat
import struct
import subprocess
import sys
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import Mock, patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
import test_uninstall as fx
from backend import gpt
from backend.install_evidence import Ext4Evidence, inspect_installation
from backend.state import Store, Context, RecoveryRequired
from backend.uninstall import prepare, persist, Uninstaller, device_layout
from backend.uninstall_growth import PreservationUnavailable
from backend.uninstall_boot import overlay, archives, entries
def marker_files(family):
release = b"DISTRIB_ID='OpenWrt'\nDISTRIB_RELEASE='test'\n"
return {'etc/e5/part-root':b'e5root /dev/mmcblk0\n','etc/openwrt_release':release} if family == 'e5' else {
'openwrt/etc/mu300/desktop-mode':b'part\n','.mu300/boot-os':b'android\n','openwrt/etc/openwrt_release':release}
def image(files, block_size=4096, extents=True):
"""Small synthetic, nonmountable metadata image; never a block device."""
data = bytearray(1 << 20); sb = memoryview(data)[1024:2048]
struct.pack_into('<I',sb,0,128);struct.pack_into('<I',sb,4,len(data)//block_size)
struct.pack_into('<I',sb,24,{1024:0,2048:1,4096:2}[block_size])
struct.pack_into('<I',sb,40,128);sb[56:58]=b'\x53\xef';struct.pack_into('<H',sb,58,1)
struct.pack_into('<H',sb,88,256);struct.pack_into('<I',sb,96,0x42 if extents else 2)
sb[104:120]=b'U'*16
descriptor=2 if block_size==1024 else 1
struct.pack_into('<I',data,descriptor*block_size+8,8)
dirs = {'':{}};nodes={'':2};allfiles={}
for path,content in files.items():
parts=path.split('/')
for i,name in enumerate(parts):
parent='/'.join(parts[:i]);full='/'.join(parts[:i+1])
if full not in nodes:
nodes[full]=len(nodes)+2;dirs[parent][name]=nodes[full]
if i<len(parts)-1:dirs.setdefault(full,{})
allfiles[path]=content
block=64
for path,number in nodes.items():
directory=path in dirs
if directory:
content=bytearray(block_size);at=0
values=list(dirs[path].items())
for i,(name,child) in enumerate(values):
name=name.encode();length=(8+len(name)+3)&~3
if i==len(values)-1:length=block_size-at
struct.pack_into('<IHBB',content,at,child,length,len(name),0)
content[at+8:at+8+len(name)]=name;at+=length
else:content=allfiles[path]
offset=8*block_size+(number-1)*256
struct.pack_into('<H',data,offset,(stat.S_IFDIR if directory else stat.S_IFREG)|0o755)
struct.pack_into('<I',data,offset+4,len(content));struct.pack_into('<H',data,offset+26,1)
if extents:
struct.pack_into('<I',data,offset+32,0x80000)
struct.pack_into('<HHHHI',data,offset+40,0xf30a,1,4,0,0)
struct.pack_into('<IHHI',data,offset+52,0,1,0,block)
else:struct.pack_into('<I',data,offset+40,block)
data[block*block_size:block*block_size+len(content)]=content;block+=1
return bytes(data)
def linux_boot(family, mode=b'part\n'):
base=fx.boot(family)
init=b'#!/bin/busybox sh\n# /etc/e5/part-root\n' if family=='e5' else b'#!/bin/busybox sh\n. /etc/mu300-desktop-storage.sh\n'
files={'init':init}
if family=='mu300':files['etc/mu300-desktop-root-mode']=mode
ram=overlay(files);header=bytearray(base[:4096]);struct.pack_into('<I',header,12,len(ram))
body=bytes(header)+base[4096:8192]+ram;body=body.ljust((len(body)+4095)&~4095,b'\0')
footer=bytearray(base[-64:]);struct.pack_into('>QQQ',footer,12,len(body),len(body),128)
return (body+b'V'*128).ljust(len(base)-64,b'\0')+footer
class NoOriginalRecord(unittest.TestCase):
def setUp(self):
self.fixture=fx.Journal();self.fixture.setUp();self.configure()
def tearDown(self):self.fixture.tearDown()
def configure(self,family='e5',slot='a',adjacent=True):
f=self.fixture;f.configure(family,slot)
self.store=Store(Path(f.temp.name)/('fresh-'+family+'-'+slot))
self.before=f.before
if not adjacent:
table=bytearray(f.before[0][1024:])
start,end=struct.unpack_from('<QQ',table,4*128+32)
struct.pack_into('<QQ',table,4*128+32,start+2*fx.GIB//512,end+2*fx.GIB//512)
self.before=fx.copies(table)
space=gpt.gpt_space(*self.before,fx.SECTORS);root=next(p for p in space['parts'] if p['name'].endswith('root'))
f.adapter.read_gpt=Mock(return_value={**space,'first':self.before[0],'last':self.before[1]})
f.device['storage'].update(ROOT_START=root['start'],ROOT_SIZE=root['end']-root['start']+1)
f.device.update(encrypted=False,encryption_state='unencrypted',encryption_type='')
self.fs=image(marker_files(family));self.boot=linux_boot(family)
self.idle='IDLE';self.root=root
self.other='b' if slot=='a' else 'a'
def shell(command,**_):
if 'echo IDLE' in command:return self.idle
if command.startswith('blockdev '):return str(64 << 20)
if command.startswith('readlink '):return '/dev/block/mmcblk0p4'
if command.startswith('cat /sys/class/block/mmcblk0p4/size'):return str(28*fx.GIB//512)
raise AssertionError(command)
def read(command):
match=re.fullmatch(r'dd if=(\S+) bs=(\d+)(?: skip=(\d+))? count=(\d+) 2>/dev/null',command)
if not match:raise AssertionError(command)
path,bs,skip,count=match[1],int(match[2]),int(match[3] or 0),int(match[4])
if path.endswith('boot_'+self.other):source=self.boot
elif path.endswith('mmcblk0p5'):source=self.fs
elif path.endswith('mmcblk0p4'):source=bytes(1024)+fx.superblock(28*fx.GIB)
else:raise AssertionError(command)
return source[bs*skip:bs*(skip+count)]
f.adb.shell=Mock(side_effect=shell);f.adb.read=Mock(side_effect=read)
def plan(self,reset=None):
f=self.fixture
with patch('backend.uninstall.growth_tools',return_value={'openwrt-uninstall/tools/fixture':b'tool'}),patch('backend.uninstall.base_boot'),patch('backend.uninstall.build'):
plan,meta,files=prepare(f.adapter,self.store,f.device,reset)
r=self.store.create(f.package,f.device,{'method':'uninstall'},plan)
context=Context(self.store,r,lambda *_:None);persist(context,meta,files)
return context
def test_empty_computer_store_checks_real_markers_and_grows_only_adjacent_root(self):
for family,slot in (('e5','a'),('mu300','a'),('mu300','b')):
self.configure(family,slot);ctx=self.plan();r=ctx.record
self.assertEqual(r['uninstall']['version'],3)
self.assertEqual(r['plan']['layout_source'],'device');self.assertIsNone(r['plan']['source_transaction'])
self.assertEqual(r['plan']['reclaimed_bytes'],4*fx.GIB)
self.assertEqual(r['plan']['android_bytes'],32*fx.GIB)
self.assertFalse(r['plan']['wipe']);self.assertEqual(r['plan']['data_action'],'grow-ext4')
Uninstaller(None,ctx,self.fixture.adapter)
# Sparse synthetic disk leaves >30 GiB after the root. It is not reclaimed.
after=gpt.gpt_space((ctx.directory/'uninstall/after-first').read_bytes(),(ctx.directory/'uninstall/after-last').read_bytes(),fx.SECTORS)
self.assertEqual(next(p for p in after['parts'] if p['name']=='userdata')['end'],self.root['end'])
for call in self.fixture.adb.read.call_args_list:self.assertNotIn('of=',call.args[0])
for call in self.fixture.adb.shell.call_args_list:
self.assertNotIn('of=',call.args[0]);self.assertNotIn('mount ',call.args[0])
def test_nonadjacent_root_is_released_without_growing_or_resetting_userdata(self):
self.configure('mu300',adjacent=False);ctx=self.plan()
self.assertEqual(ctx.record['plan']['data_action'],'gap')
self.assertEqual(ctx.record['plan']['reclaimed_bytes'],0)
self.assertEqual(ctx.record['plan']['released_unallocated_bytes'],4*fx.GIB)
self.assertEqual(ctx.record['plan']['android_bytes'],28*fx.GIB)
Uninstaller(None,ctx,self.fixture.adapter)
def test_matching_original_backup_is_preferred(self):
self.fixture.device.update(encrypted=True,encryption_state='encrypted')
with patch('backend.uninstall.inspect_installation',side_effect=AssertionError('unnecessary evidence scan')):
ctx=self.fixture.plan()
self.assertEqual(ctx.record['plan']['layout_source'],'original_record')
def test_conflicting_valid_originals_cannot_be_bypassed_by_device_fallback(self):
f=self.fixture
source=f.store.list()[0];folder=f.store.directory(source['id'])/'backup'
changed=bytearray(f.original[0][1024:]);end=struct.unpack_from('<Q',changed,3*128+40)[0]
struct.pack_into('<Q',changed,3*128+40,end+1)
for name,data in zip(('gpt-first.bin','gpt-last.bin'),fx.copies(changed)):(folder/name).write_bytes(data)
sums=json.loads((folder/'checksums.json').read_text())
for name in ('gpt-first.bin','gpt-last.bin'):sums[name]=hashlib.sha256((folder/name).read_bytes()).hexdigest()
(folder/'checksums.json').write_text(json.dumps(sums))
with patch('backend.uninstall.inspect_installation',side_effect=AssertionError('conflict bypass')),self.assertRaisesRegex(RecoveryRequired,'disagree'):
prepare(f.adapter,f.store,f.device)
def test_damaged_original_backup_can_use_fresh_verified_device_evidence(self):
f=self.fixture
for source in f.store.list():
(f.store.directory(source['id'])/'backup/gpt-first.bin').write_bytes(b'damaged')
with patch('backend.uninstall.growth_tools',return_value={'tool':b'fixture'}),patch('backend.uninstall.base_boot'),patch('backend.uninstall.build'):
plan,meta,_=prepare(f.adapter,f.store,f.device)
self.assertEqual(plan['layout_source'],'device');self.assertEqual(meta['version'],3)
def test_missing_foreign_symlinked_or_unclean_markers_and_mounted_roots_are_refused(self):
for failure in ('missing','foreign','symlink','unclean','mounted','wrong-node','wrong-start','wrong-boot','pending'):
self.configure()
files=marker_files('e5')
if failure=='missing':del files['etc/e5/part-root']
if failure=='foreign':files['etc/e5/part-root']=b'e5root /dev/mmcblk1\n'
self.fs=image(files)
if failure=='symlink':
raw=bytearray(self.fs);struct.pack_into('<H',raw,8*4096+(5-1)*256,stat.S_IFLNK|0o777);self.fs=bytes(raw)
if failure=='unclean':
raw=bytearray(self.fs);struct.pack_into('<H',raw,1024+58,2);self.fs=bytes(raw)
if failure=='mounted':self.idle=''
if failure=='wrong-node':self.fixture.device['storage']['ROOT']='mmcblk1p5'
if failure=='wrong-start':self.fixture.device['storage']['ROOT_START']+=1
if failure in ('wrong-boot','pending'):
raw=bytearray(self.boot);value=b'androidboot.test=1' if failure=='wrong-boot' else b'e5.part_v=2 e5.part_prepare=request'
raw[44:1580]=value.ljust(1536,b'\0');self.boot=bytes(raw)
with self.subTest(failure=failure),self.assertRaises(RecoveryRequired):self.plan(reset=lambda _:True)
self.assertFalse(self.store.list())
def test_encrypted_data_asks_before_reset_but_consent_cannot_override_bad_root_evidence(self):
self.fixture.device.update(encrypted=True,encryption_state='encrypted',encryption_type='file')
with self.assertRaises(PreservationUnavailable):self.plan()
self.assertFalse(self.store.list())
ctx=self.plan(reset=lambda _:True)
self.assertEqual(ctx.record['plan']['data_action'],'reset');self.assertTrue(ctx.record['plan']['wipe'])
self.fs=image({'etc/openwrt_release':b"DISTRIB_ID='OpenWrt'\n"})
with self.assertRaises(RecoveryRequired):self.plan(reset=lambda _:True)
def test_mu300_preparation_tf_and_legacy_boot_routes_cannot_authorize_partition_removal(self):
for mode in (b'prepare\n',b'sd\n',b'legacy\n',b'data-image\n'):
self.configure('mu300');self.boot=linux_boot('mu300',mode)
with self.subTest(mode=mode),self.assertRaises(RecoveryRequired):self.plan(reset=lambda _:True)
self.assertFalse(self.store.list())
def test_forged_target_cannot_swallow_unallocated_space_or_an_unrelated_partition(self):
for foreign in (False,True):
self.configure();ctx=self.plan();folder=ctx.directory/'uninstall'
table=bytearray((folder/'after-first').read_bytes()[1024:])
if foreign:table[5*128+16]^=1
else:
end=struct.unpack_from('<Q',table,3*128+40)[0]
struct.pack_into('<Q',table,3*128+40,end+2*fx.GIB//512)
for name,raw in zip(('after-first','after-last'),fx.copies(table)):
(folder/name).write_bytes(raw);ctx.record['uninstall']['checksums'][name]=hashlib.sha256(raw).hexdigest()
with self.assertRaises(RecoveryRequired):Uninstaller(None,ctx,self.fixture.adapter)
self.configure();ctx=self.plan()
ctx.record['device']['storage']['NODE']='mmcblk0;invalid;p4'
with self.assertRaisesRegex(RecoveryRequired,'disk node'):Uninstaller(None,ctx,self.fixture.adapter)
def test_changed_installation_stops_before_backup_or_boot_writes(self):
ctx=self.plan();self.fixture.adapter.backup=Mock()
self.fs=image({**marker_files('e5'),'etc/e5/part-root':b'e5root /dev/mmcblk1\n'})
with self.assertRaises(RecoveryRequired):Uninstaller(None,ctx,self.fixture.adapter).arm(self.fixture.device)
self.fixture.adapter.backup.assert_not_called();self.assertFalse(ctx.record['effects'])
def test_restart_after_armed_effect_never_requires_original_record_or_repeats_writes(self):
ctx=self.plan();r=ctx.record;r['effects']['uninstall-arm']={'state':'done'};self.store.save(r)
adapter=self.fixture.adapter
adapter.probe=Mock(return_value={**self.fixture.device,'boot_id':'after','existing':False,'userdata_bytes':32*fx.GIB})
resumed=Context(self.store,self.store.load(r['id']),lambda *_:None)
worker=Uninstaller(SimpleNamespace(stop=Mock()),resumed,adapter)
with patch.object(worker,'layout_state',return_value='after'),patch.object(worker,'finish') as finish,patch.object(worker,'arm',side_effect=AssertionError('replayed')),patch('backend.uninstall.inspect_installation',side_effect=AssertionError('root no longer exists')):
worker.run()
finish.assert_called_once()
def test_interrupted_boot_retry_uses_verified_original_boot_backup_for_evidence(self):
proof=inspect_installation(self.fixture.adapter,self.fixture.device,self.root)
saved=self.boot;self.boot=bytes(len(saved))
self.assertEqual(inspect_installation(self.fixture.adapter,self.fixture.device,self.root,boot_backup=saved),proof)
def test_wrong_type_attributes_duplicate_guid_and_alignment_are_rejected_before_reads(self):
for case in ('type','attributes','guid','alignment'):
table=bytearray(self.before[0][1024:]);at=4*128
if case=='type':table[at:at+16]=b'X'*16
if case=='attributes':struct.pack_into('<Q',table,at+48,1)
if case=='guid':table[at+16:at+32]=table[3*128+16:3*128+32]
if case=='alignment':
start,end=struct.unpack_from('<QQ',table,at+32);struct.pack_into('<QQ',table,at+32,start+1,end)
with self.subTest(case=case),self.assertRaises(RecoveryRequired):device_layout(fx.copies(table),fx.SECTORS,'e5root')
def test_schema3_arm_carries_the_preserving_action_and_creates_backups_before_any_boot_write(self):
f=self.fixture;ctx=self.plan()
# Use the real worker image builder on a tiny synthetic boot, no release
# build or device commands. Only the transport and tools are fixtures.
base=fx.boot('e5');package=Path(f.temp.name)/'package';(package/'files').mkdir(parents=True)
(package/'files/boot.img').write_bytes(base);f.adapter.root=package
def backup(_):
folder=ctx.directory/'backup';folder.mkdir()
android=bytearray(base);android[44:1580]=bytes(1536)
(folder/'boot_a.bin').write_bytes(android);(folder/'boot_b.bin').write_bytes(self.boot)
(folder/'misc.bin').write_bytes(bytes(2048)+fx.android_bc()+bytes(2016))
f.adapter.backup=Mock(side_effect=backup)
original_read=f.adb.read.side_effect
f.adb.read=Mock(side_effect=lambda command:self.before[0] if 'count=34 ' in command else self.before[1] if 'skip='+str(fx.SECTORS-33) in command else original_read(command))
original_shell=f.adb.shell.side_effect;critical=[]
def shell(command,**kwargs):
if command.startswith('set -eu;'):
self.assertTrue((ctx.directory/'backup/boot_a.bin').is_file())
self.assertTrue((ctx.directory/'uninstall/after-first').is_file());critical.append(command)
self.assertIsNone(kwargs['timeout']);return ''
if command.startswith('umask '):return ''
return original_shell(command,**kwargs)
f.adb.shell=Mock(side_effect=shell);f.adb.call=Mock()
with patch('backend.uninstall.growth_tools',return_value={'openwrt-uninstall/tools/fixture':b'tool'}),patch('backend.uninstall.push_chunks'):
Uninstaller(None,ctx,f.adapter).arm(f.device)
self.assertEqual(len(critical),1);self.assertEqual(ctx.record['effects']['uninstall-arm']['state'],'done')
generated=(ctx.directory/'uninstall/boot-uninstall.img').read_bytes();size=struct.unpack_from('<I',generated,12)[0]
files={name:body for archive in archives(generated[8192:8192+size]) for name,body,_ in entries(archive)}
self.assertIn(b':grow-ext4:',files['openwrt-uninstall/request'])
self.assertNotIn(b'--wipe_data',files['openwrt-uninstall/recovery-bcb'])
self.assertNotIn('of=/dev/block/mmcblk',critical[0]);f.adb.call.assert_called_once_with('reboot')
class MetadataReader(unittest.TestCase):
def test_block_sizes_extents_and_old_direct_pointers(self):
for blocksize in (1024,2048,4096):
for extents in (False,True):
files=marker_files('mu300');raw=image(files,blocksize,extents)
reader=Ext4Evidence(lambda at,n:raw[at:at+n],len(raw))
for name,value in files.items():self.assertEqual(reader.file(name),value)
def test_out_of_range_extents_and_truncated_reads_stop(self):
raw=bytearray(image(marker_files('e5')))
struct.pack_into('<I',raw,8*4096+(2-1)*256+60,99999999)
reader=Ext4Evidence(lambda at,n:bytes(raw[at:at+n]),len(raw))
with self.assertRaises(ValueError):reader.file('etc/e5/part-root')
with self.assertRaises(ValueError):Ext4Evidence(lambda at,n:b'bad',len(raw))
@unittest.skipUnless(sys.platform!='win32' and shutil.which('sh'),'requires a POSIX shell; regular files only')
def test_idle_check_rejects_mounts_holders_and_unreadable_metadata(self):
f=NoOriginalRecord();f.setUp()
try:
inspect_installation(f.fixture.adapter,f.fixture.device,f.root)
command=next(call.args[0] for call in f.fixture.adb.shell.call_args_list if 'echo IDLE' in call.args[0])
finally:f.tearDown()
with tempfile.TemporaryDirectory() as folder:
root=Path(folder);node=root/'sys/mmcblk0p5';(node/'holders').mkdir(parents=True)
(node/'dev').write_text('179:5\n');mounts=root/'mountinfo';mounts.write_text('')
command=command.replace('/sys/class/block',str(root/'sys')).replace('/proc/self/mountinfo',str(mounts))
def run():return subprocess.run(['sh','-c',command],capture_output=True,text=True)
self.assertEqual(run().stdout.strip(),'IDLE')
mounts.write_text('1 2 179:5 / /mounted rw - ext4 /dev/mmcblk0p5 rw\n')
self.assertEqual(run().stdout.strip(),'BUSY')
mounts.write_text('');(node/'holders/dm-0').write_text('')
self.assertEqual(run().stdout.strip(),'BUSY')
mounts.unlink();self.assertNotEqual(run().returncode,0)
@unittest.skipUnless(shutil.which('mke2fs') and shutil.which('debugfs'),'requires Linux filesystem tools, regular files only')
class RealMetadata(unittest.TestCase):
def test_populated_ext4_with_real_directory_indexes_64bit_and_metadata_checksums(self):
for blocksize in (1024,4096):
with self.subTest(blocksize=blocksize),tempfile.TemporaryDirectory() as folder:
root=Path(folder);tree=root/'tree';tree.mkdir()
files=marker_files('mu300')
for name,content in files.items():
p=tree/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(content)
# More than one directory block, and a real symlink rejection.
for n in range(400):(tree/'openwrt/etc'/f'other-{n:04d}').write_text('other')
(tree/'alias').symlink_to('openwrt/etc/openwrt_release')
path=root/'root.ext4'
subprocess.run(['mke2fs','-q','-t','ext4','-F','-b',str(blocksize),'-d',str(tree),str(path),'64M'],check=True,capture_output=True)
result=subprocess.run(['e2fsck','-fyD',str(path)],capture_output=True)
self.assertIn(result.returncode,(0,1),result.stderr)
before=hashlib.sha256(path.read_bytes()).hexdigest()
with path.open('rb') as stream:
def read(at,n):stream.seek(at);return stream.read(n)
reader=Ext4Evidence(read,path.stat().st_size)
for name,value in files.items():self.assertEqual(reader.file(name),value)
with self.assertRaises(ValueError):reader.file('alias')
self.assertEqual(hashlib.sha256(path.read_bytes()).hexdigest(),before)
if __name__=='__main__':unittest.main()
+10 -5
View File
@@ -25,7 +25,8 @@ window.__TAURI_INTERNALS__.invoke=async(command,args={})=>{
const preserve=window.__fixture.removePreserve;
const plan={...result.plan,method:'uninstall',wipe,data_action:preserve?'grow-ext4':wipe?'reset':'gap',two_stage:true,offline:true,grow:false,
target:'mmcblk0p5',previous_android_bytes:28*1073741824,android_bytes:((wipe||preserve)?32:28)*1073741824,
openwrt_bytes:4*1073741824,reclaimed_bytes:(wipe||preserve)?4*1073741824:0};
openwrt_bytes:4*1073741824,reclaimed_bytes:(wipe||preserve)?4*1073741824:0,
layout_source:window.__fixture.layoutSource,released_unallocated_bytes:(wipe||preserve)?0:4*1073741824};
window.__fixture.tx.plan=plan;result.plan=plan;
}
if(command==='backend_request' && args.command==='start'){
@@ -40,12 +41,12 @@ window.__TAURI_INTERNALS__.invoke=async(command,args={})=>{
def main(url='http://127.0.0.1:1420'):
with sync_playwright() as p:
browser=p.chromium.launch()
for language,wipe,theme,preserve in (('zh',True,'dark',False),('en',False,'light',False),('zh',False,'light',True),('en',True,'light',False)):
for language,wipe,theme,preserve,basis in (('zh',True,'dark',False,'original_record'),('en',False,'light',False,'original_record'),('zh',False,'light',True,'original_record'),('en',True,'light',False,'original_record'),('zh',False,'light',True,'device'),('en',False,'dark',False,'device')):
context=fixture_context(browser,viewport={'width':1120,'height':900},device_scale_factor=1)
context.add_init_script(BRIDGE+UNINSTALL+
'localStorage.setItem("language",'+json.dumps(language)+');'+
'localStorage.setItem("theme",'+json.dumps(theme)+');'+
'window.__fixture.removeWipe='+json.dumps(wipe)+';window.__fixture.removePreserve='+json.dumps(preserve)+';')
'window.__fixture.removeWipe='+json.dumps(wipe)+';window.__fixture.removePreserve='+json.dumps(preserve)+';window.__fixture.layoutSource='+json.dumps(basis)+';')
page=context.new_page();errors=[]
page.set_default_timeout(10000)
page.on('pageerror',lambda error:errors.append(str(error)))
@@ -83,6 +84,10 @@ def main(url='http://127.0.0.1:1420'):
assert button.is_disabled()
assert page.locator('.plan-list').get_by_text('4.00 GiB',exact=True).count()>=1
assert page.locator('.confirmation').count()==1
if basis=='device':
page.get_by_text('未找到可用的原安装备份' if zh else 'No usable original installation backup',exact=False).wait_for()
if not wipe and not preserve:
page.locator('.plan-list').get_by_text('释放为空闲的空间' if zh else 'Space released as unallocated',exact=True).wait_for()
assert page.get_by_text('保留 Android 数据' if preserve else '全部清空' if zh else 'All Android apps' if wipe else 'Android userdata is not enlarged',exact=False).count()>=1
layout(page)
page.set_viewport_size({'width':800,'height':650});settle(page)
@@ -91,7 +96,7 @@ def main(url='http://127.0.0.1:1420'):
assert impact and impact['y']+impact['height']<650
page.set_viewport_size({'width':1120,'height':900});settle(page)
output=ROOT/'screenshots';output.mkdir(exist_ok=True)
page.screenshot(path=str(output/('uninstall-plan-preserve-zh.png' if preserve else 'uninstall-plan-reset-zh.png' if zh else 'uninstall-plan-reset-en.png' if wipe else 'uninstall-plan-gap-en.png')))
page.screenshot(path=str(output/(('uninstall-plan-device-zh.png' if zh else 'uninstall-plan-device-gap-en.png') if basis=='device' else 'uninstall-plan-preserve-zh.png' if preserve else 'uninstall-plan-reset-zh.png' if zh else 'uninstall-plan-reset-en.png' if wipe else 'uninstall-plan-gap-en.png')))
page.locator('.confirmation input').check();button.click();settle(page)
page.get_by_text('不会撤回设备上的卸载或已确认的重置' if zh else 'does not withdraw device removal or an approved reset',exact=False).wait_for()
assert 'verify_openwrt' not in page.evaluate('window.__fixture.requests')
@@ -119,7 +124,7 @@ def main(url='http://127.0.0.1:1420'):
assert not errors,errors
context.close()
browser.close()
print('PASS: reset consent/cancel before plan, preservation/gap/reset impacts, bilingual UI, Android completion, bounded layout; simulated backend only')
print('PASS: reset consent/cancel, original-record and device-evidence plans, preservation/release/reset impacts, bilingual UI, Android completion, bounded layout; simulated backend only')
def source():
+14 -10
View File
@@ -5,16 +5,18 @@ export const strings = {
uninstallChooseReset:'选择格式化并查看计划', uninstallPreserve:'删除内置 OpenWrt 及其设置,在离线环境检查并扩容未加密 userdata,保留 Android 数据。请仍备份重要文件;检查失败会停止,不会自动格式化。',
uninstallUncertain:'上次卸载写入尚未确认完成。请保留备份并重连复核;暂停或关闭安装器不能保证撤回设备上的操作。',
uninstallArmedWarning:'卸载请求已写入,重启后会执行。暂停或关闭安装器只停止电脑上的等待,不会撤回设备上的卸载或已确认的重置。请保持供电。',
uninstall:'卸载并归还空间', uninstallDesc:'移除内置 OpenWrt,恢复安装前的 Android 容量。需要原安装记录与备份。',
uninstallHelp:'请先切回 Android,开启调试并授予 root。确认未加密且可直接扩容时保留 Android 数据。无法确认时先报错并询问是否格式化;未同意不会生成重置计划。原未分配空间只移除 OpenWrt。',
uninstallWipe:'删除内置 OpenWrt 及全部设置,把原来缩出的空间还给 Android。Android 应用、账号、照片和内部存储全部清空,请先自行备份。',
uninstallKeep:'删除内置 OpenWrt 及全部设置。原本使用的未分配空间恢复为空闲,不额外扩大 userdata,Android 用户数据保留。',
uninstall:'卸载并归还空间', uninstallDesc:'移除内置 OpenWrt,检查可归还给 Android 或释放为空闲的空间。',
uninstallHelp:'请先切回 Android,开启调试并授予 root。没有原安装记录时会检查设备上的安装信息。确认未加密且可直接扩容时保留 Android 数据;无法保留时先说明原因,再询问是否格式化。',
uninstallDeviceBounds:'未找到可用的原安装备份,已核实设备上的 OpenWrt 安装。仅将紧邻 userdata 的 OpenWrt 分区容量归还 Android;不相邻时释放为空闲,不合并其他空闲空间。请核对下方容量。',
unallocatedRelease:'释放为空闲的空间',
uninstallWipe:'删除内置 OpenWrt 及全部设置,按计划扩大 Android 空间。Android 应用、账号、照片和内部存储全部清空,请先自行备份。',
uninstallKeep:'删除内置 OpenWrt 及全部设置,将该分区释放为空闲,不额外扩大 userdata,Android 用户数据保留。',
uninstallFirstBoot:'重启后执行离线卸载,完成后自动进入 Android。需要重置时会进入原厂恢复流程,可能重启多次,请勿断电。',
uninstallWaiting:'正在等待离线卸载及 Android 返回。若设备一直停留在原 Android,请手动重启一次;已经重启时请继续等待。重置后完成初始设置、启用调试并恢复 root,安装器会核实容量。',
reconnectDevice:'更换卸载设备的连接(可选)', keepRecordedDevice:'沿用记录中的设备连接', reconnectHelp:'仅用于继续卸载。地址变化或改接 USB 时,先完成 Android 初始化、调试与 root,刷新并明确选择同一台设备;安装器会验证硬件身份。连接未变时无需选择。',
uninstallPlanReady:'卸载计划已就绪', operationMethod:'操作方式', uninstallTarget:'移除目标', androidAllocation:'Android 容量', uninstallAccept:'我已核对设备、移除目标和数据处理方式,并备份需要保留的 Android 文件及 OpenWrt 配置。',
reviewUninstall:'确认卸载计划', planUninstall:'查看卸载计划', startUninstall:'确认卸载', continueUninstall:'继续卸载', successUninstall:'OpenWrt 已卸载并完成容量验证',
uninstallNext:'设备已恢复为 Android 启动。原本缩出的空间已归还 Android;原本未分配的空间保持空闲。电脑上的安装记录与备份仍会保留。',
uninstallNext:'设备已恢复为 Android 启动,空间已按卸载计划归还 Android 或释放为空闲。电脑上的卸载记录与备份仍会保留。',
release:'移除的 OpenWrt 分区', reclaim:'归还 Android 的空间', androidActual:'Android 文件系统实际容量',
uninstallSteps:['检查与卸载计划','准备与备份','离线卸载与重启','验证 Android 容量','完成'],
author:'作者', qqGroup:'Q群', copyGroup:'复制群号', groupCopied:'群号已复制', repositoryOpened:'已打开项目仓库', support:'赞赏支持作者', closeSupport:'关闭赞赏提示',
@@ -68,16 +70,18 @@ export const strings = {
uninstallChooseReset:'Choose format and review plan', uninstallPreserve:'Remove internal OpenWrt and its settings, then check and grow unencrypted userdata offline while preserving Android data. Back up important files. Failed checks stop the operation; they never trigger automatic formatting.',
uninstallUncertain:'The previous removal write is unconfirmed. Keep backups and reconnect for verification. Pausing or closing cannot guarantee withdrawal of the device action.',
uninstallArmedWarning:'Removal is armed and runs after restart. Pausing or closing the installer stops only the computer’s wait; it does not withdraw device removal or an approved reset. Keep power connected.',
uninstall:'Uninstall and return space', uninstallDesc:'Remove internal OpenWrt and restore the previous Android capacity. Original installation records and backups are required.',
uninstallHelp:'First boot rooted Android and authorize debugging. Confirmed unencrypted direct userdata can be grown with data preserved. Otherwise you are asked whether to format before a reset plan is created. Removing a partition in previously unallocated space preserves Android data.',
uninstallWipe:'Delete internal OpenWrt and all its settings, returning the space taken from Android. All Android apps, accounts, photos and internal storage will be erased. Back up your files first.',
uninstallKeep:'Delete internal OpenWrt and all its settings. Its previously unallocated space becomes free again. Android userdata is not enlarged and its data is preserved.',
uninstall:'Uninstall and return space', uninstallDesc:'Remove internal OpenWrt and check which space can return to Android or become unallocated.',
uninstallHelp:'Return to rooted Android and enable debugging first. Without original records, the installer verifies the installation on the device. Confirmed unencrypted data directly on userdata is preserved if tools support growth; otherwise it explains why and asks before a reset.',
uninstallDeviceBounds:'No usable original installation backup was found. The installation on the device has been verified. Only an OpenWrt partition immediately after userdata can return to Android; a nonadjacent partition becomes unallocated. Other free space is not merged. Review the capacities below.',
unallocatedRelease:'Space released as unallocated',
uninstallWipe:'Delete internal OpenWrt and all its settings and enlarge Android as planned. All Android apps, accounts, photos and internal storage will be erased. Back up your files first.',
uninstallKeep:'Delete internal OpenWrt and all its settings. The partition becomes unallocated. Android userdata is not enlarged and its data is preserved.',
uninstallFirstBoot:'Restart to perform offline removal, then automatically return to Android. A required reset runs through stock recovery and may restart several times. Keep power connected.',
uninstallWaiting:'Waiting for offline removal and Android. If the device remains in the original Android session, restart it once; if it is already restarting, keep waiting. After a reset, finish setup, authorize debugging and restore root so capacity can be verified.',
reconnectDevice:'Change removal device connection (optional)', keepRecordedDevice:'Keep the recorded device connection', reconnectHelp:'For resuming removal only. If the address changed or you switched to USB, finish Android setup, debugging and root, then refresh and select the same device. Hardware identity is checked. Leave unchanged otherwise.',
uninstallPlanReady:'Removal plan ready', operationMethod:'Operation', uninstallTarget:'Removal target', androidAllocation:'Android capacity', uninstallAccept:'I checked the device, removal target and data handling, and backed up Android files and OpenWrt configuration I need.',
reviewUninstall:'Confirm removal plan', planUninstall:'Review removal plan', startUninstall:'Confirm uninstall', continueUninstall:'Continue removal', successUninstall:'OpenWrt removed and capacity verified',
uninstallNext:'The device boots Android again. Space originally taken from Android has been returned; factory unallocated space stays free. Records and backups remain on this computer.',
uninstallNext:'The device boots Android again. Space was returned to Android or released as unallocated according to the removal plan. Removal records and backups remain on this computer.',
release:'OpenWrt partition to remove', reclaim:'Space returned to Android', androidActual:'Actual Android filesystem capacity',
uninstallSteps:['Checks and removal plan','Prepare and back up','Offline removal and restart','Verify Android capacity','Complete'],
author:'Author', qqGroup:'QQ group ', copyGroup:'Copy group number', groupCopied:'Group number copied', repositoryOpened:'Project repository opened', support:'Support the author', closeSupport:'Close support notice',
+1 -1
View File
@@ -338,7 +338,7 @@ function App() {
</section>}
</div><div className="actions"><Button disabled={busy} variant="ghost" onClick={() => navigate('home')}>{t.back}</Button><Button disabled={busy || !pkg || !device?.root} onClick={() => plan()}>{method === 'uninstall' ? t.planUninstall : t.plan}<ArrowRight size={16}/></Button></div>
</>}
{view === 'plan' && tx && <><div className="eyebrow">{tx.choices.method === 'uninstall' ? t.reviewUninstall : t.review}</div><h1 tabIndex={-1}>{tx.device.model}</h1><p className="intro">{tx.package.name} · ••••{tx.device.serial.slice(-4)}</p>{tx.choices.method === 'uninstall' && impactNotice}<div className="page-scroll scroll-area"><section><dl className="plan-list"><div><dt>{tx.choices.method === 'uninstall' ? t.operationMethod : t.installMethod}</dt><dd>{tx.choices.method === 'boot' ? t.boot : tx.choices.method === 'update' ? t.update : (t as unknown as Record<string,string>)[tx.choices.method]}</dd></div><div><dt>{tx.choices.method === 'uninstall' ? t.uninstallTarget : t.target}</dt><dd>{tx.plan.target}</dd></div><div><dt>{tx.choices.method === 'uninstall' ? t.androidAllocation : t.android}</dt><dd>{tx.choices.method === 'uninstall' && <>{gib(tx.plan.previous_android_bytes)} → </>}{gib(tx.plan.android_bytes)}</dd></div><div><dt>{tx.choices.method === 'uninstall' ? t.release : t.allocation}</dt><dd>{tx.choices.method === 'boot' ? '—' : gib(tx.plan.openwrt_bytes)}</dd></div>{tx.choices.method === 'uninstall' ? <div><dt>{t.reclaim}</dt><dd>{gib(tx.plan.reclaimed_bytes)}</dd></div> : <div><dt>{t.grow}</dt><dd>{tx.plan.grow ? <Check size={17}/> : '—'}</dd></div>}</dl></section>
{view === 'plan' && tx && <><div className="eyebrow">{tx.choices.method === 'uninstall' ? t.reviewUninstall : t.review}</div><h1 tabIndex={-1}>{tx.device.model}</h1><p className="intro">{tx.package.name} · ••••{tx.device.serial.slice(-4)}</p>{tx.choices.method === 'uninstall' && impactNotice}<div className="page-scroll scroll-area"><section>{tx.choices.method === 'uninstall' && tx.plan.layout_source === 'device' && <p className="device-hint">{t.uninstallDeviceBounds}</p>}<dl className="plan-list"><div><dt>{tx.choices.method === 'uninstall' ? t.operationMethod : t.installMethod}</dt><dd>{tx.choices.method === 'boot' ? t.boot : tx.choices.method === 'update' ? t.update : (t as unknown as Record<string,string>)[tx.choices.method]}</dd></div><div><dt>{tx.choices.method === 'uninstall' ? t.uninstallTarget : t.target}</dt><dd>{tx.plan.target}</dd></div><div><dt>{tx.choices.method === 'uninstall' ? t.androidAllocation : t.android}</dt><dd>{tx.choices.method === 'uninstall' && <>{gib(tx.plan.previous_android_bytes)} → </>}{gib(tx.plan.android_bytes)}</dd></div><div><dt>{tx.choices.method === 'uninstall' ? t.release : t.allocation}</dt><dd>{tx.choices.method === 'boot' ? '—' : gib(tx.plan.openwrt_bytes)}</dd></div>{tx.choices.method === 'uninstall' ? <><div><dt>{t.reclaim}</dt><dd>{gib(tx.plan.reclaimed_bytes)}</dd></div>{!!tx.plan.released_unallocated_bytes && <div><dt>{t.unallocatedRelease}</dt><dd>{gib(tx.plan.released_unallocated_bytes)}</dd></div>}</> : <div><dt>{t.grow}</dt><dd>{tx.plan.grow ? <Check size={17}/> : '—'}</dd></div>}</dl></section>
{tx.choices.method !== 'uninstall' && impactNotice}
{(tx.plan.offline || tx.plan.two_stage) && <div className="alert"><RefreshCw size={20}/><p>{tx.choices.method === 'uninstall' ? t.uninstallFirstBoot : t.firstBoot}</p></div>}
</div><label className="checkbox-label confirmation"><input disabled={busy} type="checkbox" checked={accepted} onChange={e => setAccepted(e.target.checked)}/>{tx.choices.method === 'uninstall' ? t.uninstallAccept : t.accept}</label>
+1 -1
View File
@@ -6,7 +6,7 @@ export interface Package {path: string; name: string; adapter: string; profile:
export interface ResetPrompt {confirmation_required: 'format_android'; reason: string; reset_token: string; model: string; serial_hint: string}
export interface Transaction {
id: string; status: string; stage: string; device: Device; package: Package;
choices: {method: string; host?: string}; plan: {wipe: boolean; data_action?: string; preservation_error?: string; two_stage: boolean; offline?: boolean; openwrt_bytes: number; android_bytes?: number; previous_android_bytes?: number; reclaimed_bytes?: number; target: string; grow?: boolean; experimental?: boolean; gap_start?: number};
choices: {method: string; host?: string}; plan: {wipe: boolean; data_action?: string; preservation_error?: string; layout_source?: 'original_record' | 'device'; released_unallocated_bytes?: number; two_stage: boolean; offline?: boolean; openwrt_bytes: number; android_bytes?: number; previous_android_bytes?: number; reclaimed_bytes?: number; target: string; grow?: boolean; experimental?: boolean; gap_start?: number};
uninstall_armed?: boolean; completed: string[]; unsafe: boolean; updated: number; revision?: number;
stage_started_at?: number; stage_finished_at?: number;
details?: {host?: string; tool?: string; reboot_manually?: boolean; boot_confirmed?: boolean; verification_error?: string; connection_state?: string}; error?: {message: string; retryable: boolean; code: string};
@@ -3,8 +3,8 @@
case ${1:-} in 0|1) slot=$1 ;; *) exit 2 ;; esac
LIB=${MU300_DASH_BIN:-/usr/libexec/unisoc-modem}
out=$(MU300_SIM_SLOT=$slot "$LIB/at" -t 3 'AT+CCID' 2>/dev/null) || exit 1
iccid=$(printf '%s\n' "$out" | tr -d '\r' | sed -n 's/^+CCID:[[:space:]]*"\{0,1\}\([0-9]*\)"\{0,1\}[[:space:]]*$/\1/p' | head -n1)
case "$iccid" in ''|*[!0-9]*) exit 1 ;; esac
iccid=$(printf '%s\n' "$out" | tr -d '\r' | sed -n 's/^+CCID:[[:space:]]*"\{0,1\}\([A-Za-z0-9]*\)"\{0,1\}[[:space:]]*$/\1/p' | head -n1)
case "$iccid" in ''|*[!A-Za-z0-9]*) exit 1 ;; esac
[ ${#iccid} -ge 18 ] && [ ${#iccid} -le 22 ] || exit 1
umask 077
json=$(printf '{"iccid":"%s"}' "$iccid")
@@ -18,7 +18,8 @@ function credentials(p) {
return type(user)=='string' && type(password)=='string' && length(user)<=64 && length(password)<=64 &&
!match(user+password,/["\\[:cntrl:]]/) && !match(user+password,/[^ -~]/);
}
export function valid_identity(p) { return type(p)=='object' && match(p.iccid || '',/^[0-9]{18,22}$/); };
// Preserve the modem's identifier, including vendor/card letters and padding.
export function valid_identity(p) { return type(p)=='object' && type(p.iccid)=='string' && match(p.iccid,/^[A-Za-z0-9]{18,22}$/); };
function options(p) { return {apn:p.apn || '',pdptype:p.pdptype || 'IP',auth:auth(p),username:p.username || '',password:p.password || '',roaming:p.roaming || p.pdptype || 'IP',attach:p.attach=='1'?'1':'0'}; }
function same(a,b) { return sprintf('%J',options(a))==sprintf('%J',options(b)); }
function binding(c,identity) {
@@ -456,7 +456,7 @@ if [ "$MODE" = full ]; then
i_fw=$(at 'AT+CGMR' 2 | grep -v '^OK' | head -n1)
i_imei=$(at 'AT+CGSN' 2 | tr -cd '0-9' | cut -c1-15)
i_imsi=$(at 'AT+CIMI' 2 | tr -cd '0-9' | cut -c1-15)
i_iccid=$(at 'AT+CCID' 2 | tr -cd '0-9' | cut -c1-20)
i_iccid=$(at 'AT+CCID' 2 | tr -d '\r' | sed -n 's/^+CCID:[[:space:]]*"\{0,1\}\([A-Za-z0-9]*\)"\{0,1\}[[:space:]]*$/\1/p' | head -n1)
if [ -n "$i_imei$i_imsi$i_iccid" ]; then
# Persist static identity only; legacy caches with an own-number
# field are rebuilt once so they cannot leak a stale number.
+2 -2
View File
@@ -614,8 +614,8 @@ resolve_apn_selection() {
identity='{}'
if [ "$needed" = 1 ]; then
identity=$(at 'AT+CCID' 3 2>/dev/null) || { echo 'SIM identity unavailable for APN selection' >&2; return 1; }
iccid=$(printf '%s\n' "$identity" | tr -d '\r' | sed -n 's/^+CCID:[[:space:]]*"\{0,1\}\([0-9]*\)"\{0,1\}[[:space:]]*$/\1/p' | head -n1)
[[ "$iccid" =~ ^[0-9]{18,22}$ ]] || { echo 'SIM identity unavailable for APN selection' >&2; return 1; }
iccid=$(printf '%s\n' "$identity" | tr -d '\r' | sed -n 's/^+CCID:[[:space:]]*"\{0,1\}\([A-Za-z0-9]*\)"\{0,1\}[[:space:]]*$/\1/p' | head -n1)
[[ "$iccid" =~ ^[A-Za-z0-9]{18,22}$ ]] || { echo 'SIM identity unavailable for APN selection' >&2; return 1; }
identity=$(printf '{"iccid":"%s"}' "$iccid")
fi
# Query IMSI only when this card actually has automatic selection enabled.
+22
View File
@@ -77,3 +77,25 @@ check(!a.automatic('garbage'),'invalid IMSI');
check(a.change(c,'save',{id:privateId,name:'Private cleared',apn:'private.apn',pdptype:'IPV4V6',auth:'chap',username:'account',password:''},reload).ok,'explicit password clear');
check(!a.resolve(c,card1,{}).settings.password,'cleared secret persisted');
printf('apn extended: %d checks passed\n',n);
// Vendor identifiers are opaque alphanumeric card keys, never digit-filtered.
for(let value in ['898604E112345678901F','898604Z11234567890af'])
check(a.valid_identity({iccid:value}),'letter ICCID accepted intact');
for(let value in ['', 'short', 'x12345678901234567890123', '898604/112345678901F', '898604Z11234567890af\n', 1234567890123456789, null, {}, '卡卡卡卡卡卡卡卡卡卡卡卡卡卡卡卡卡卡卡卡'])
check(!a.valid_identity({iccid:value}),'malformed ICCID rejected');
let letterCard={iccid:'898604Z112345678901F',imsi:'460001234567890'};
let otherLetterCard={iccid:'898604Y112345678901F',imsi:'460001234567890'};
c=cursor(dir,dir+'/delta');
let letterProfile=a.change(c,'save',{name:'Letter card',apn:'letter.apn',pdptype:'IP'},reload);
check(letterProfile.ok,'letter card profile saved');
c=cursor(dir,dir+'/delta');
check(a.change(c,'apply',{id:letterProfile.id,remember:true},reload,letterCard).ok,'letter card binding applied');
c=cursor(dir,dir+'/delta');
check(a.get(c,letterCard).identity_ready && a.get(c,letterCard).remembered,'letter identity visible and bound');
check(a.resolve(c,letterCard,{}).settings.apn=='letter.apn','letter binding used by dialer');
check(a.resolve(c,otherLetterCard,{apn:'other.apn',pdptype:'IP'}).settings.apn=='other.apn','different letter is a different SIM');
check(a.change(c,'auto',{},reload,otherLetterCard).ok,'letter card automatic selection applied');
c=cursor(dir,dir+'/delta');
check(a.resolve(c,otherLetterCard,{}).settings.apn=='cmnet','letter auto binding survives reload');
check(a.resolve(c,letterCard,{}).settings.apn=='letter.apn','other letter binding unchanged');
printf('alphanumeric APN identities: %d checks passed\n',n);
+48
View File
@@ -7,6 +7,54 @@ APP=TOP/'openwrt/luci-app-mu300'
LIB=APP/'root/usr/libexec/unisoc-modem'
class APN(ShellTest):
def test_alphanumeric_identity_adapter_preserves_key(self):
import json
source=(LIB/'apn-identity').read_text().replace('/run/unisoc-apn-sim',str(self.tmp/'sim'))
path=self.tmp/'identity';path.write_text(source)
adapter=self.tmp/'adapter';adapter.mkdir()
at=adapter/'at'
at.write_text('#!/bin/sh\nprintf \'%s\\r\\n\' "${TEST_REPLY}"\n')
at.chmod(0o755)
for shell in self.each_shell():
for value in ('898604E112345678901F','898604Z11234567890af'):
for reply in ('+CCID: '+value, '+CCID: "'+value+'"'):
r=self.script(shell,path,'1',MU300_DASH_BIN=adapter,TEST_REPLY=reply)
self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(json.loads(r.stdout)['iccid'],value)
self.assertEqual(json.loads((self.tmp/'sim1.json').read_text())['iccid'],value)
for value in ('short','898604/112345678901F','x'*23,'卡'*20):
r=self.script(shell,path,'1',MU300_DASH_BIN=adapter,TEST_REPLY='+CCID: '+value)
self.assertNotEqual(r.returncode,0)
self.assertEqual(r.stdout,'')
def test_dialer_reads_letter_identity_without_losing_characters(self):
source=(TOP/'rootfs/overlay/opt/mu300/bin/mobile-data').read_text()
function=source[source.index('resolve_apn_selection() {'):source.index('\nconfigure_initial_apn() {')]
helper=self.tmp/'apn'
helper.write_text('''#!/bin/sh
if [ "$1" = needs-identity ]; then echo 1; exit; fi
cat > "$STUBLOG/resolved-identity"
echo '{"ok":1,"source":"sim","settings":{"apn":"letter.apn","pdptype":"IP","auth":"none","username":"","password":"","roaming":"IP","attach":"0"}}'
''')
helper.chmod(0o755)
filter_path=self.stubs/'jsonfilter'
filter_path.write_text('''#!/usr/bin/env python3
import json,sys
value=json.load(sys.stdin)
for key in sys.argv[2].split('.')[1:]: value=value[key]
print(value)
''')
filter_path.chmod(0o755)
path=self.tmp/'dialer.sh'
path.write_text('set -eu\n'+function.replace('/usr/libexec/unisoc-modem/apn',str(helper)).replace('/run/unisoc-apn-sim',str(self.tmp/'sim'))+'''
at() { printf '%s\\n' '+CCID: "898604Z11234567890af"'; }
resolve_apn_selection
[ "$RESOLVED_APN:$MU300_PDP_TYPE" = 'letter.apn:IP' ]
''')
r=self.script(['bash'],path,MU300_SIM_SLOT='1')
self.assertEqual(r.returncode,0,r.stderr)
self.assertEqual(json.loads((self.tmp/'resolved-identity').read_text())['iccid'],'898604Z11234567890af')
def test_hot_global_settings_without_identity_queries(self):
source=(TOP/'rootfs/overlay/opt/mu300/bin/mobile-data').read_text()
function=source[source.index('resolve_apn_selection() {'):source.index('\nconfigure_initial_apn() {')]