mirror of
https://github.com/dikeckaan/mu300-linux.git
synced 2026-12-05 08:02:40 +00:00
Complete encrypted Android F2FS growth during uninstall and remove switch model gates
This commit is contained in:
1 parent
6e61104c0f
commit
474e801808
11 files changed
+720
-29
No files matched your search
@@ -1,7 +1,7 @@
|
||||
//<script>
|
||||
/*
|
||||
* OpenWrt system switch v6 — Minikano
|
||||
* Android web-panel plugin; all supported E5-family and MU300-family models.
|
||||
* OpenWrt system switch v7 — Minikano
|
||||
* Android web-panel plugin; detect installed boot format without a model whitelist.
|
||||
* Select the installed OpenWrt for the next boot, preserving default policy.
|
||||
* Write only misc[2048:2080]. No root mount, boot flash or boot-chain sync.
|
||||
* Shared with mu300-linux/android/magisk/webui-plugins/mu300-system-switch.js.
|
||||
@@ -72,6 +72,9 @@
|
||||
const raw = head.slice(44, 1580), end = raw.indexOf(0);
|
||||
if (end < 0) throw new Error('OpenWrt 启动参数不完整');
|
||||
const args = ascii(raw.slice(0, end)).split(/\s+/);
|
||||
// The installed image identifies its format; Android model names are
|
||||
// neither an installation marker nor a reliable compatibility gate.
|
||||
if (family === undefined) family = args.includes('e5.part_v=2') ? 'e5' : 'mu300';
|
||||
const recognized = family === 'e5' ? args.includes('e5.part_v=2') : args.includes('loglevel=5') && !args.some(arg => arg.startsWith('e5.'));
|
||||
if (!recognized) throw new Error('另一槽未识别到对应机型系列的 OpenWrt 镜像,请用安装器检查');
|
||||
if (args.some(arg => arg.startsWith('e5.part_prepare=')) || args.includes('openwrt.uninstall=1')) {
|
||||
@@ -83,11 +86,11 @@
|
||||
const length = qword(28), limit = (family === 'e5' ? 56 : 48) * 1048576;
|
||||
if (ascii(footer.slice(0, 4)) !== 'AVBf' || qword(12) !== payloadEnd || qword(20) !== payloadEnd ||
|
||||
!length || payloadEnd + length > limit) throw new Error('OpenWrt 启动镜像范围或尾部校验失败');
|
||||
return family;
|
||||
};
|
||||
const probe = async () => {
|
||||
const result = await run('set -e; [ "$(id -u)" = 0 ]; [ -n "$(getprop ro.build.version.release)" ]; ' +
|
||||
'echo SLOT=$(getprop ro.boot.slot_suffix); echo MODEL=$(getprop ro.product.model); ' +
|
||||
'echo DEVICE=$(getprop ro.product.device); echo PLATFORM=$(getprop ro.board.platform)');
|
||||
'echo SLOT=$(getprop ro.boot.slot_suffix)');
|
||||
if (!result.ok) throw new Error('请在 Android 中打开插件,并授予网页管理面板 root 权限');
|
||||
const values = {};
|
||||
for (const line of result.text.split(/\r?\n/)) {
|
||||
@@ -95,14 +98,7 @@
|
||||
if (at > 0) values[line.slice(0, at)] = line.slice(at + 1).trim();
|
||||
}
|
||||
if (!/^_[ab]$/.test(values.SLOT || '')) throw new Error('无法确定当前 Android 槽位,已取消;不会使用 misc 猜测');
|
||||
const slot = values.SLOT.slice(1), names = [values.MODEL || '', values.DEVICE || ''].map(name => name.toUpperCase());
|
||||
let family;
|
||||
if (['E5', 'T551M', 'VIPME M8', 'T512N', 'ZTE 7546N', 'ANGELCARE K1'].some(model => names.includes(model))) family = 'e5';
|
||||
else if (names.includes('V50') || names.includes('MU3351')) {
|
||||
if (!names.includes('V50') || !names.includes('MU3351') || values.PLATFORM !== 'ums9620') throw new Error('V50 的型号或平台信息不匹配');
|
||||
family = 'mu300';
|
||||
} else if (/U30.?AIR|MU300|F50/i.test(names.join('\n'))) family = 'mu300';
|
||||
else throw new Error('此机型不在两个项目支持范围内,未切换');
|
||||
const slot = values.SLOT.slice(1);
|
||||
const live = await readHex(MISC, 2048, 32);
|
||||
control(live, slot);
|
||||
const other = slot === 'a' ? 'b' : 'a', target = '/dev/block/by-name/boot_' + other;
|
||||
@@ -111,7 +107,7 @@
|
||||
const size = Number(sizeResult.text);
|
||||
if (size !== 64 * 1048576) throw new Error('目标启动分区容量不受支持');
|
||||
const head = await readHex(target, 0, 1, 4096), tail = await readHex(target, size / 512 - 1, 1, 512);
|
||||
inspectBoot(head, tail, size, family);
|
||||
const family = inspectBoot(head, tail, size);
|
||||
const current = await readHex('/dev/block/by-name/boot_' + slot, 0, 1, 4096);
|
||||
if (ascii(unhex(current, 4096).slice(0, 8)) !== 'ANDROID!') throw new Error('当前 Android 启动镜像头不完整,未切换');
|
||||
if (head === current) throw new Error('两槽启动镜像头相同,未识别到独立 OpenWrt 镜像');
|
||||
|
||||
@@ -70,6 +70,8 @@ unset MU300_DEPLOY_ROOT
|
||||
shutil.copyfile(TOP/'desktop/README.md',stage/'docs/DESKTOP-INSTALL.md')
|
||||
shutil.copyfile(TOP/'desktop/START-HERE.md',stage/'START-HERE.md')
|
||||
shutil.copyfile(TOP/'desktop/installer.py',stage/'OpenWrt-Installer.py')
|
||||
extras=stage/'extras/android';extras.mkdir(parents=True,exist_ok=True)
|
||||
shutil.copyfile(TOP/'android/magisk/webui-plugins/mu300-system-switch.js',extras/'openwrt-system-switch-plugin.js')
|
||||
# Python source runs from the archive root, so resolve its support files there.
|
||||
if exe and not Path(exe).is_dir():
|
||||
fingerprint=json.loads(Path(str(exe)+'.json').read_text())
|
||||
|
||||
@@ -1,5 +1,21 @@
|
||||
# Android → OpenWrt 网页插件 misc 写入复查
|
||||
|
||||
## 2026-10-30:v7 移除机型限制
|
||||
|
||||
两仓库 JS 插件内容一致,不再读取型号或平台作白名单判断,避免新增机型、
|
||||
定制固件改名导致切换被拒绝。根据备用槽 boot 中的启动参数识别 E5/MU300
|
||||
镜像格式,Android 当前槽仍来自 `ro.boot.slot_suffix`,支持 A/B 双向。
|
||||
|
||||
保留镜像头、范围、AVB footer、安装/卸载待办、misc CRC 及回读校验;
|
||||
仅写 misc 偏移 2048 的 32 字节,不挂载 OpenWrt,不修改 boot/GPT/默认启动策略。
|
||||
去掉名称限制不表示替设备安装 OpenWrt,也不表示已验证任意硬件的启动兼容性。
|
||||
|
||||
新增回归覆盖未知型号、新平台、名称与镜像系列不一致时按实际镜像识别,
|
||||
以及未知型号携带原厂、损坏或待安装镜像时拒绝写入。未执行实机切换。
|
||||
下方为 2026-10-16 历史记录,其中旧机型限制已被本节取代。
|
||||
|
||||
## 2026-10-16 历史复查
|
||||
|
||||
日期:2026-10-16。开发诊断及验证报告;没有对设备执行命令,没有编译或打包。
|
||||
|
||||
## 已确认的问题
|
||||
|
||||
@@ -45,3 +45,55 @@ F50 的确认卸载已完成备份,但原 misc 的 command 是 bootonce-bootlo
|
||||
现在按 C 字符串语义识别 command;真正的 Recovery、未知命令或带 Recovery/OTA 载荷的请求仍然阻止操作。用户确认卸载、备份完成且备用启动镜像写入核验后,允许交接无 Recovery/OTA 载荷的一次性 bootloader 命令:对比完整 2048 字节 BCB 的原值或已处理值,仅将前 32 字节 command 清零并回读。其余 BCB、A/B 控制、userdata、NV 不在这一步修改。未确认卸载时不执行清理。
|
||||
|
||||
BCB 原值继续保存在已有校验过的 misc 备份中,恢复启动准备允许识别原值或已处理值,旧失败事务可继续。最终回 Android 的核验也使用同一语义,避免在最后阶段再次误报。临时普通文件回归检查其他字节及 A/B 控制完全不变,Recovery/未知请求不被覆盖。
|
||||
|
||||
|
||||
## 2026-10-30:原厂存在 resizer 不等于已完成扩容
|
||||
|
||||
用户 F50 的实际续接日志确认,卸载后的 GPT 与单层解密映射都已达到
|
||||
24,985,468,928 字节,但 F2FS 仍为 16,395,534,336 字节,缺少 8 GiB。
|
||||
原 UUID 和数据仍可读取。不能把这一状态报成卸载完成,也不能靠反复重启
|
||||
保证原厂自动扩容。先前仅凭 ELF 中存在 resize.f2fs 路径推断执行能力不充分。
|
||||
|
||||
修正后的 grow-android-f2fs 在实际容量不足时安排一次挂载前维护:
|
||||
|
||||
- 使用本机 Magisk 工具生成临时 Android ramdisk,核对原 kernel、命令行及
|
||||
OS/header 字段没有被替换。缺少这些工具时在计划阶段说明无法提供该路径。
|
||||
- 保持原 Android 槽。不能用另一槽启动 Android 来偷换这一步:另一槽的
|
||||
logical system/vendor 可能缺失或版本不同。该路径会临时修改原 Android
|
||||
boot,计划说明已明确这一点;电脑与设备各保留校验过的原件。
|
||||
- Magisk overlay.d 在 post-fs、late-fs 之前安装临时的 fsck/resize 包装器。
|
||||
只接受属于本机 userdata 的完整解密映射,核对 GPT、存储身份、原 UUID、
|
||||
目标范围及未挂载状态,再调用本机原生 fsck/resize;不导出密钥。
|
||||
- F2FS 的 -t 参数按实际逻辑扇区换算,兼容 512/4096 字节;sysfs/GPT
|
||||
公共接口的单位仍为 512 字节。E5 的 UFS 路径携带同一身份读取 helper。
|
||||
- post-fs-data 保存实际工具输出并恢复原 Android boot,回读成功后才重启。
|
||||
若返回过程中中断,电脑仅在原件与已安装维护镜像的精确哈希匹配时续接恢复。
|
||||
boot 写入失败会当场尝试恢复已校验原件;无法确认时保留错误和备份。
|
||||
- 不修改 misc、GPT、NV 或 metadata;不在线强改已挂载的 F2FS,不执行格式化。
|
||||
最后仍要求原 UUID、分区、解密映射和文件系统容量全部匹配才完成卸载。
|
||||
- 成功后删除本次设备侧维护镜像与解包临时文件。失败保留日志;电脑安装备份
|
||||
按原事务保留,不会自动删除。不会无限重复后台重启或无限累积恢复目录。
|
||||
|
||||
验证边界:本轮对实机只读取状态、在普通临时文件中生成并检查了维护启动镜像,
|
||||
没有刷入该镜像、重启或执行实际扩容。模拟回归覆盖挂载拒绝、错误 UUID/映射、
|
||||
fsck/resize 失败、工具未真正扩容、512/4K 参数、Android A/B 和启动恢复。
|
||||
这不是 F50 或全机型免擦扩容的实机验收;尤其不能将原厂工具存在或测试通过
|
||||
表述为已完成设备扩容。现有已扩大的 GPT 和数据不应为了重试而重新缩容/格式化。
|
||||
|
||||
|
||||
## F50 实机完成验收(2026-10-30)
|
||||
|
||||
用户明确要求手动完成后打包,本轮已实际执行上述挂载前维护。使用原卸载事务
|
||||
204eceecb5ef49d3bad7b4cb332dd137 的已校验备份和 GPT 快照,在 CID 与原 UUID
|
||||
匹配、Android A、GPT 已恢复的前提下执行;没有再次删除/改写 GPT,没有格式化。
|
||||
|
||||
原厂 fsck/resize 实际通过 dm-39 执行并回报 GROWTH_VERIFIED。本机 dm 的实际
|
||||
逻辑扇区为 4096 字节,工具目标为 6,099,968 个逻辑扇区,不能传 512-byte 计数。
|
||||
返回正常 Android 后确认:
|
||||
|
||||
- userdata 分区、解密映射、F2FS 均为 24,985,468,928 字节(约 23.2695 GiB)。
|
||||
- 原 F2FS 为 16,395,534,336 字节,实际归还并扩入 8,589,934,592 字节(8 GiB)。
|
||||
- UUID 不变,原 Android boot 回读与备份一致,维护 ramdisk 已退出。
|
||||
- 原卸载事务已完成;设备侧临时 boot、解包文件和脚本已清理,电脑原备份保留。
|
||||
|
||||
这验证的是该台 F50 的 eMMC+4K 解密映射路径,不代表其他固件或 UFS 的硬件验收。
|
||||
@@ -0,0 +1,364 @@
|
||||
"""One-shot Android pre-mount F2FS maintenance; keys never leave Android.
|
||||
|
||||
The same Android slot temporarily boots its own verified maintenance ramdisk.
|
||||
Magisk's documented overlay.d installs a wrapper before late-fs. Only the
|
||||
verified decrypted mapper is resized, before it is mounted. The original slot
|
||||
is restored from its verified backup before returning. No key, GPT or misc is written.
|
||||
"""
|
||||
import hashlib
|
||||
import re
|
||||
import shlex
|
||||
import struct
|
||||
import subprocess
|
||||
|
||||
from . import storage
|
||||
from .state import RecoveryRequired, sha
|
||||
from .transport import push_chunks
|
||||
from .binary_io import pull_binary
|
||||
|
||||
|
||||
MAGISKBOOT = '/data/adb/magisk/magiskboot'
|
||||
|
||||
|
||||
def capability(adb):
|
||||
value = adb.shell('if [ -x '+MAGISKBOOT+' ]; then sha256sum '+MAGISKBOOT+
|
||||
'; else echo MAGISKBOOT_UNAVAILABLE; fi',root=True).split()
|
||||
if not value or not re.fullmatch('[a-f0-9]{64}', value[0]):
|
||||
raise ValueError('Cannot prepare Android pre-mount growth: Magisk boot tools unavailable / 无法准备 Android 挂载前扩容:缺少 Magisk 启动工具')
|
||||
return value[0]
|
||||
|
||||
|
||||
def identity_helper(record, adapter):
|
||||
if adapter.kind == 'e5' and storage.disk_node(record['device']['storage']['NODE']).startswith('sd'):
|
||||
path = adapter.root/'files/e5-ufs-id'
|
||||
data = path.read_bytes()
|
||||
if len(data)<20 or data[:6]!=b'\x7fELF\x02\x01' or struct.unpack_from('<H',data,18)[0]!=183:
|
||||
raise ValueError('Package lacks the Android UFS identity executable / 安装包缺少 Android UFS 身份校验程序')
|
||||
return data
|
||||
return None
|
||||
|
||||
|
||||
def verify_image(original, updated):
|
||||
"""Permit a ramdisk edit, not a different kernel/command line/OS version."""
|
||||
if len(original) != 64 << 20 or len(updated) != len(original):
|
||||
raise ValueError('Android maintenance boot size differs')
|
||||
for data in (original, updated):
|
||||
if data[:8] != b'ANDROID!' or struct.unpack_from('<I', data, 40)[0] not in (3, 4):
|
||||
raise ValueError('Unsupported Android maintenance boot header')
|
||||
a, b = bytearray(original[:4096]), bytearray(updated[:4096])
|
||||
# Only the ramdisk length and v4 boot signature size may change.
|
||||
for header in (a, b):
|
||||
header[12:16] = bytes(4)
|
||||
if struct.unpack_from('<I', header, 40)[0] == 4:
|
||||
header[1580:1584] = bytes(4)
|
||||
size = struct.unpack_from('<I', original, 8)[0]
|
||||
end = 4096 + ((size + 4095) & ~4095)
|
||||
ramdisk = struct.unpack_from('<I', updated, 12)[0]
|
||||
if a != b or not size or not ramdisk or original[4096:end] != updated[4096:end] or end+ramdisk > len(updated)-4096:
|
||||
raise ValueError('Android maintenance boot changed outside its ramdisk')
|
||||
if original == updated:
|
||||
raise ValueError('Android maintenance hook was not added')
|
||||
|
||||
|
||||
WRAPPER = r'''#!/system/bin/sh
|
||||
set -eu
|
||||
base=@BASE@
|
||||
name=${0##*/}
|
||||
case "$name" in fsck.f2fs|resize.f2fs) ;; *) exit 70 ;; esac
|
||||
# Preserve stock invocation for other filesystems/devices. The real program
|
||||
# lives under its original basename, including separate resize executables.
|
||||
device=
|
||||
for arg do device=$arg; done
|
||||
case "$device" in /*) device=$(readlink -f "$device") ;; esac
|
||||
node=${device##*/}
|
||||
if ! [ -d "/sys/class/block/$node/dm" ] ||
|
||||
[ "$(ls /sys/class/block/$node/slaves)" != @NODE@ ]; then
|
||||
exec "$base/$name" "$@"
|
||||
fi
|
||||
exec >>"$base/worker.log" 2>&1
|
||||
echo "Android pre-mount: $name $node"
|
||||
fail() { echo "FAILED: $*" > "$base/result"; exit 71; }
|
||||
[ "$(blockdev --getsize64 "$device")" = @TARGET@ ] || fail mapper-size
|
||||
number=$(cat "/sys/class/block/$node/dev")
|
||||
for mounts in /proc/self/mountinfo /proc/1/mountinfo; do
|
||||
! awk -v n="$number" '$3==n {found=1} END {exit !found}' "$mounts" || fail mapper-mounted
|
||||
done
|
||||
measure() {
|
||||
dd if="$device" of="$base/super" bs=1024 skip=1 count=1 2>/dev/null
|
||||
[ "$(wc -c < "$base/super")" = 1024 ] || fail short-super
|
||||
[ "$(od -An -tx1 -N4 "$base/super" | tr -d ' \n')" = 1020f5f2 ] || fail magic
|
||||
[ "$(od -An -tx1 -j108 -N16 "$base/super" | tr -d ' \n')" = @UUID@ ] || fail filesystem-identity
|
||||
[ "$(od -An -tu4 -j16 -N4 "$base/super" | tr -d ' \n')" = 12 ] || fail block-size
|
||||
set -- $(od -An -tu4 -j36 -N8 "$base/super")
|
||||
bytes=$(( ($1 + ($2 << 32))*4096 ))
|
||||
[ "$bytes" -ge @BEFORE@ ] && [ "$bytes" -le @TARGET@ ] || fail filesystem-size
|
||||
}
|
||||
measure
|
||||
if [ "$name" = fsck.f2fs ]; then
|
||||
"$base/fsck.f2fs" "$@" || { rc=$?; fail "stock-fsck-$rc"; }
|
||||
fi
|
||||
measure
|
||||
if [ "$bytes" -lt @MINIMUM@ ]; then
|
||||
# Explicit size; never inherit a caller's safe-shrink or reserved-size flags.
|
||||
sector=$(blockdev --getss "$device")
|
||||
case "$sector" in 512|4096) ;; *) fail logical-sector-size ;; esac
|
||||
[ "$((@TARGET@ % sector))" = 0 ] || fail target-alignment
|
||||
"$base/resize.f2fs" -t "$((@TARGET@ / sector))" "$device" </dev/null || { rc=$?; fail "stock-resize-$rc"; }
|
||||
fi
|
||||
measure
|
||||
[ "$bytes" -ge @MINIMUM@ ] || fail filesystem-not-grown
|
||||
sync
|
||||
echo GROWTH_VERIFIED > "$base/result"
|
||||
'''
|
||||
|
||||
|
||||
SETUP = r'''#!/system/bin/sh
|
||||
set -eu
|
||||
base=@BASE@
|
||||
mkdir -p "$base"
|
||||
chmod 700 "$base"
|
||||
exec >>"$base/setup.log" 2>&1
|
||||
@STORAGE@
|
||||
@UFS_ENV@
|
||||
[ "$(e5_storage_identity @DISK@)" = @CID@ ]
|
||||
[ "$(getprop ro.boot.slot_suffix)" = _@SLOT@ ]
|
||||
[ "$(cat /sys/class/block/@NODE@/size)" = @SECTORS@ ]
|
||||
@GPT_CHECKS@
|
||||
# Copy both native executables before binding either target. They can be the
|
||||
# same symlink target; distinct inodes are handled too. Never modify /system.
|
||||
cp /system/bin/fsck.f2fs "$base/fsck.f2fs"
|
||||
cp /system/bin/resize.f2fs "$base/resize.f2fs"
|
||||
[ "$(sha256sum "$base/fsck.f2fs" | cut -d' ' -f1)" = @FSCK_SHA@ ]
|
||||
[ "$(sha256sum "$base/resize.f2fs" | cut -d' ' -f1)" = @RESIZE_SHA@ ]
|
||||
cp "$1" "$base/wrapper"
|
||||
chmod 755 "$base/fsck.f2fs" "$base/resize.f2fs" "$base/wrapper"
|
||||
chcon u:object_r:magisk_file:s0 "$base/wrapper" "$base/fsck.f2fs" "$base/resize.f2fs"
|
||||
fsck=$(readlink -f /system/bin/fsck.f2fs)
|
||||
resizer=$(readlink -f /system/bin/resize.f2fs)
|
||||
mount -o bind "$base/wrapper" "$fsck"
|
||||
[ "$fsck" = "$resizer" ] || mount -o bind "$base/wrapper" "$resizer"
|
||||
echo 'Wrapper installed; waiting for stock decrypted pre-mount check'
|
||||
'''
|
||||
|
||||
|
||||
FINISH = r'''#!/system/bin/sh
|
||||
set -eu
|
||||
base=@BASE@
|
||||
[ "$(getprop ro.boot.slot_suffix)" = _@SLOT@ ]
|
||||
# Preserve the actual pre-mount result across the return to original Android.
|
||||
dir=/data/local/tmp/openwrt-uninstall-@ID@-android-growth
|
||||
mkdir -p "$dir"
|
||||
chmod 700 "$dir"
|
||||
for file in setup.log worker.log result; do
|
||||
[ ! -f "$base/$file" ] || cp "$base/$file" "$dir/$file"
|
||||
done
|
||||
[ -f "$dir/result" ] || echo 'FAILED: stock pre-mount wrapper was not invoked' > "$dir/result"
|
||||
# Restore the original Android image even when growth failed; keep the
|
||||
# maintenance receipts. Only our exact installed image may be replaced.
|
||||
[ "$(sha256sum "$dir/android.img" | cut -d' ' -f1)" = @ANDROID_SHA@ ]
|
||||
current=$(sha256sum /dev/block/by-name/boot_@SLOT@ | cut -d' ' -f1)
|
||||
wanted=$(sha256sum "$dir/maintenance.img" | cut -d' ' -f1)
|
||||
[ "$current" = "$wanted" ] || [ "$current" = @ANDROID_SHA@ ]
|
||||
if [ "$current" != @ANDROID_SHA@ ]; then
|
||||
dd if="$dir/android.img" of=/dev/block/by-name/boot_@SLOT@ bs=1048576 conv=fsync
|
||||
fi
|
||||
[ "$(sha256sum /dev/block/by-name/boot_@SLOT@ | cut -d' ' -f1)" = @ANDROID_SHA@ ]
|
||||
sync
|
||||
setprop sys.powerctl reboot
|
||||
'''
|
||||
|
||||
|
||||
def scripts(record, adapter, volume, android_sha):
|
||||
slot = record['device']['slot'].removeprefix('_')
|
||||
other = 'b' if slot == 'a' else 'a'
|
||||
identity = record['id']
|
||||
if not re.fullmatch('[a-zA-Z0-9-]{1,80}', identity):
|
||||
raise ValueError('Invalid maintenance transaction ID')
|
||||
node = record['device']['storage']['NODE']
|
||||
disk = storage.disk_node(node)
|
||||
target = record['plan']['android_bytes']
|
||||
before = record['uninstall']['volume']['filesystem_bytes']
|
||||
uuid = record['uninstall']['volume']['uuid']
|
||||
if not re.fullmatch('[a-f0-9]{32}', uuid) or target % 512 or before <= 0 or target <= before:
|
||||
raise ValueError('Invalid Android growth geometry')
|
||||
proof = volume['android_growth']
|
||||
# Both are copied from the live stock firmware, not package maintenance
|
||||
# binaries with potentially different vendor feature support.
|
||||
fsck_sha = adapter.adb.shell('sha256sum /system/bin/fsck.f2fs', root=True).split()[0]
|
||||
if not re.fullmatch('[a-f0-9]{64}', fsck_sha):
|
||||
raise ValueError('Cannot verify stock F2FS checker')
|
||||
meta = record['uninstall']
|
||||
checks = []
|
||||
for name, offset, count in [('after-first', 0, meta['front']), ('after-last', meta['tail'], meta['total']-meta['tail'])]:
|
||||
checks.append('[ "$(dd if=/dev/block/'+disk+' bs=512 skip='+str(offset)+' count='+str(count)+
|
||||
' 2>/dev/null | sha256sum | cut -d\' \''+' -f1)" = '+meta['checksums'][name]+' ]')
|
||||
library = storage.library(adapter.root)
|
||||
identity_function = 'mu300_storage_identity' if adapter.kind == 'mu300' else 'e5_storage_identity'
|
||||
values = {'BASE':'/dev/openwrt-grow-'+identity, 'NODE':node, 'DISK':disk,
|
||||
'ID':identity, 'SLOT':slot, 'OTHER':other, 'TARGET':str(target),
|
||||
'SECTORS':str(target//512), 'BEFORE':str(before), 'MINIMUM':str(target-(4 << 20)),
|
||||
'UUID':uuid, 'CID':record['device']['cid'], 'ANDROID_SHA':android_sha,
|
||||
'FSCK_SHA':fsck_sha, 'RESIZE_SHA':proof['resizer_sha256'],
|
||||
'GPT_CHECKS':'\n'.join(checks),
|
||||
'STORAGE':library, 'UFS_ENV':'export E5_UFS_ID_HELPER="$2"' if identity_helper(record,adapter) else ':'}
|
||||
def render(source):
|
||||
for key, value in values.items():
|
||||
source = source.replace('@'+key+'@', value)
|
||||
if re.search(r'@[A-Z_]+@', source):
|
||||
raise ValueError('Unexpanded Android growth template')
|
||||
return source.replace('e5_storage_identity', identity_function).encode()
|
||||
prefix = 'openwrt-grow-'+identity
|
||||
helper = identity_helper(record,adapter)
|
||||
rc = ('on post-fs\n setprop sys.openwrt.growth '+identity+'\n'+
|
||||
' exec u:r:magisk:s0 root root -- /system/bin/sh ${MAGISKTMP}/'+prefix+
|
||||
'-setup.sh ${MAGISKTMP}/'+prefix+'-wrapper.sh'+(' ${MAGISKTMP}/'+prefix+'-ufs-id' if helper else '')+'\n\non post-fs-data\n'+
|
||||
' exec u:r:magisk:s0 root root -- /system/bin/sh ${MAGISKTMP}/'+prefix+'-finish.sh\n')
|
||||
files = {prefix+'.rc':rc.encode(), prefix+'-setup.sh':render(SETUP),
|
||||
prefix+'-wrapper.sh':render(WRAPPER), prefix+'-finish.sh':render(FINISH)}
|
||||
if helper:
|
||||
files[prefix+'-ufs-id'] = helper
|
||||
return files
|
||||
|
||||
|
||||
def prepare_image(adb, ctx, remote, local, source, files, tool_sha):
|
||||
"""Only ordinary staging files are written; this never arms or boots it."""
|
||||
adb.shell('umask 077; mkdir -p '+remote+'; chmod 700 '+remote+'; chown 2000:2000 '+remote, root=True)
|
||||
for name, content in files.items():
|
||||
path = local/name; path.write_bytes(content)
|
||||
push_chunks(adb.call, lambda s:adb.shell(s, root=True), path, remote+'/'+name, ctx)
|
||||
current = adb.shell('if [ -f '+remote+'/android.img ]; then sha256sum '+remote+'/android.img; fi',root=True).split()
|
||||
if not current or current[0] != sha(source):
|
||||
push_chunks(adb.call, lambda s:adb.shell(s, root=True), source, remote+'/android.img', ctx)
|
||||
build = ('set -eu; cd '+remote+'; [ "$(sha256sum '+MAGISKBOOT+
|
||||
' | cut -d\' \''+' -f1)" = '+tool_sha+' ]; '+MAGISKBOOT+' unpack android.img; ')
|
||||
build += 'if '+MAGISKBOOT+' cpio ramdisk.cpio test; then rc=0; else rc=$?; fi; [ "$rc" = 1 ]; '
|
||||
build += MAGISKBOOT+' cpio ramdisk.cpio "mkdir 0750 overlay.d" "mkdir 0750 overlay.d/sbin"; '
|
||||
for name in files:
|
||||
dest = 'overlay.d/'+('' if name.endswith('.rc') else 'sbin/')+name
|
||||
build += MAGISKBOOT+' cpio ramdisk.cpio '+shlex.quote('add '+('0644' if name.endswith('.rc') else '0755')+' '+dest+' '+name)+'; '
|
||||
build += MAGISKBOOT+' repack android.img maintenance.img; chmod 644 maintenance.img'
|
||||
adb.shell(build, root=True, timeout=None)
|
||||
output = local/'maintenance.img'
|
||||
pull_binary(adb.call,adb.shell,'cat '+remote+'/maintenance.img',output,expected_size=64 << 20)
|
||||
updated = output.read_bytes()
|
||||
verify_image(source.read_bytes(), updated)
|
||||
return updated
|
||||
|
||||
|
||||
def stage(worker, device, volume):
|
||||
"""Build/verify the temporary Android image; arm it within a journal effect."""
|
||||
adb, ctx, record = worker.adapter.adb, worker.ctx, worker.r
|
||||
ctx.log('正在准备 Android 挂载前扩容,完成后恢复原启动镜像 / Preparing stock Android pre-mount growth with boot restoration',scope='android-growth')
|
||||
if worker.layout_state() != 'after' or device['userdata_bytes'] != record['plan']['android_bytes']:
|
||||
raise RecoveryRequired('Android growth requires the verified restored partition layout')
|
||||
tool_sha = capability(adb)
|
||||
slot = device['slot'].removeprefix('_')
|
||||
remote = '/data/local/tmp/openwrt-uninstall-'+record['id']+'-android-growth'
|
||||
local = ctx.directory/'uninstall/android-growth'
|
||||
local.mkdir(parents=True, exist_ok=True)
|
||||
boot_path = '/dev/block/by-name/boot_'+slot
|
||||
source = local/'android.img'
|
||||
pull_binary(adb.call,adb.shell,'dd if='+boot_path+' bs=1048576 count=64 2>/dev/null',source,expected_size=64 << 20)
|
||||
boot = source.read_bytes()
|
||||
android_sha = hashlib.sha256(boot).hexdigest()
|
||||
# Keep the current working Android image, independently of any earlier
|
||||
# pre-reset backup. Only its ramdisk changes temporarily; the stock kernel
|
||||
# and the actual Android slot (including logical system/vendor) are kept.
|
||||
files = scripts(record, worker.adapter, volume, android_sha)
|
||||
updated = prepare_image(adb,ctx,remote,local,source,files,tool_sha)
|
||||
patched = local/'maintenance.img'; patched.write_bytes(updated)
|
||||
patched_sha = sha(patched)
|
||||
record.update(uninstall_android_growth_sha256=patched_sha,
|
||||
uninstall_android_growth_source_sha256=android_sha,
|
||||
uninstall_android_growth_attempted=True,
|
||||
uninstall_growth_pending=True,
|
||||
uninstall_wait_boot_id=device['boot_id'])
|
||||
ctx.store.save(record)
|
||||
if worker.layout_state() != 'after':
|
||||
raise RecoveryRequired('Layout changed during Android growth preparation')
|
||||
script = ('set -eu; set -o pipefail; [ "$(getprop ro.boot.slot_suffix)" = _'+slot+' ]; '+
|
||||
'[ "$(sha256sum '+boot_path+' | cut -d\' \''+' -f1)" = '+android_sha+' ]; '+
|
||||
'[ "$(sha256sum '+remote+'/android.img | cut -d\' \''+' -f1)" = '+android_sha+' ]; '+
|
||||
'[ "$(sha256sum '+remote+'/maintenance.img | cut -d\' \''+' -f1)" = '+patched_sha+' ]; '+
|
||||
'chown -R 0:0 '+remote+'; chmod 700 '+remote+'; '+
|
||||
'if dd if='+remote+'/maintenance.img of='+boot_path+' bs=1048576 conv=fsync && '+
|
||||
'[ "$(sha256sum '+boot_path+' | cut -d\' \''+' -f1)" = '+patched_sha+' ]; then :; else '+
|
||||
'dd if='+remote+'/android.img of='+boot_path+' bs=1048576 conv=fsync; '+
|
||||
'[ "$(sha256sum '+boot_path+' | cut -d\' \''+' -f1)" = '+android_sha+' ]; '+
|
||||
'echo ANDROID_GROWTH_BOOT_RESTORED; exit 1; fi')
|
||||
ctx.stage('uninstall_prepare')
|
||||
key = 'uninstall-android-growth-arm'
|
||||
if record['effects'].get(key):
|
||||
record['effects'].pop(key)
|
||||
ctx.store.save(record)
|
||||
ctx.effect(key, lambda:adb.shell(script, root=True, timeout=None))
|
||||
ctx.stage('uninstall_offline', 'waiting_device', reboot_manually=False)
|
||||
try:
|
||||
adb.call('reboot')
|
||||
except (ConnectionError, OSError, TimeoutError, subprocess.TimeoutExpired):
|
||||
ctx.log('Expected ADB loss during one-shot Android pre-mount growth', scope='uninstall')
|
||||
|
||||
|
||||
def report(worker):
|
||||
remote = '/data/local/tmp/openwrt-uninstall-'+worker.r['id']+'-android-growth'
|
||||
text = worker.adapter.adb.shell('for f in result setup.log worker.log; do '
|
||||
'[ ! -f '+remote+'/$f ] || tail -c 12000 '+remote+'/$f; done', root=True)
|
||||
worker.ctx.log(text, scope='android-growth')
|
||||
return text
|
||||
|
||||
|
||||
def restore(worker, device):
|
||||
"""Recover an interrupted hook/restore by exact boot readback, never GPT."""
|
||||
record, adb, ctx = worker.r, worker.adapter.adb, worker.ctx
|
||||
if not record.get('uninstall_android_growth_attempted'):
|
||||
return
|
||||
expected = record.get('uninstall_android_growth_source_sha256')
|
||||
patched = record.get('uninstall_android_growth_sha256')
|
||||
source = ctx.directory/'uninstall/android-growth/android.img'
|
||||
if (not re.fullmatch('[a-f0-9]{64}',expected or '') or
|
||||
not re.fullmatch('[a-f0-9]{64}',patched or '') or
|
||||
not source.is_file() or source.stat().st_size != 64 << 20 or sha(source) != expected):
|
||||
raise RecoveryRequired('Android growth boot backup is damaged / Android 扩容启动备份损坏,请保留备份')
|
||||
if device['slot'] != record['device']['slot'] or worker.layout_state() != 'after':
|
||||
raise RecoveryRequired('Android growth recovery identity/layout changed')
|
||||
slot = device['slot'].removeprefix('_'); target='/dev/block/by-name/boot_'+slot
|
||||
current = adb.shell('sha256sum '+target,root=True).split()[0]
|
||||
if current == expected:
|
||||
# ADB may have disconnected after the device-side commit. Exact boot
|
||||
# readback proves this step independently of its host-side receipt.
|
||||
entry=record['effects'].get('uninstall-android-growth-arm')
|
||||
if entry:
|
||||
entry.update(state='done',result='original Android restored by readback')
|
||||
record['unsafe']=False;ctx.store.save(record)
|
||||
return adb.shell('getprop sys.openwrt.growth',root=True).strip() == record['id']
|
||||
if current != patched:
|
||||
raise RecoveryRequired('Android growth boot is neither the backup nor our maintenance image / Android 启动镜像与扩容备份不符,不会覆盖')
|
||||
remote='/data/local/tmp/openwrt-uninstall-'+record['id']+'-growth-restore'
|
||||
adb.shell('umask 077; mkdir -p '+remote+'; chown 2000:2000 '+remote+'; chmod 700 '+remote,root=True)
|
||||
push_chunks(adb.call,lambda s:adb.shell(s,root=True),source,remote+'/android.img',ctx)
|
||||
script=('set -eu; set -o pipefail; [ "$(getprop ro.boot.slot_suffix)" = _'+slot+' ]; '+
|
||||
'[ "$(sha256sum '+target+' | cut -d\' \''+' -f1)" = '+patched+' ]; '+
|
||||
'[ "$(sha256sum '+remote+'/android.img | cut -d\' \''+' -f1)" = '+expected+' ]; '+
|
||||
'dd if='+remote+'/android.img of='+target+' bs=1048576 conv=fsync; '+
|
||||
'[ "$(sha256sum '+target+' | cut -d\' \''+' -f1)" = '+expected+' ]')
|
||||
key='uninstall-android-growth-restore'
|
||||
if record['effects'].get(key):
|
||||
record['effects'].pop(key);ctx.store.save(record)
|
||||
ctx.effect(key,lambda:adb.shell(script,root=True,timeout=None))
|
||||
return True
|
||||
|
||||
|
||||
def cleanup(worker):
|
||||
"""Remove only this successful transaction's ordinary staging files."""
|
||||
record=worker.r
|
||||
if not record.get('uninstall_android_growth_attempted'):
|
||||
return
|
||||
report(worker)
|
||||
prefix='openwrt-grow-'+record['id']
|
||||
remote='/data/local/tmp/openwrt-uninstall-'+record['id']+'-android-growth'
|
||||
names=['android.img','maintenance.img','kernel','ramdisk.cpio','header','dtb',
|
||||
'kernel_dtb','extra','second','recovery_dtbo','result','setup.log','worker.log',
|
||||
prefix+'.rc',prefix+'-setup.sh',prefix+'-wrapper.sh',prefix+'-finish.sh',prefix+'-ufs-id']
|
||||
restore_dir='/data/local/tmp/openwrt-uninstall-'+record['id']+'-growth-restore'
|
||||
worker.adapter.adb.shell('rm -f '+' '.join(remote+'/'+name for name in names)+' '+
|
||||
restore_dir+'/android.img; rmdir '+remote+' '+restore_dir+' 2>/dev/null || true',root=True)
|
||||
@@ -23,6 +23,7 @@ from .uninstall_boot import build
|
||||
from .uninstall_growth import (PreservationUnavailable, eligible, growth_tools, base_boot,
|
||||
inspect_android_growth, preservation_eligible)
|
||||
from .install_evidence import inspect_installation
|
||||
from . import android_growth_boot
|
||||
|
||||
|
||||
def partition(info, name):
|
||||
@@ -236,6 +237,8 @@ def prepare(adapter, store, device, authorize_reset=None):
|
||||
if reason:
|
||||
raise ValueError(reason)
|
||||
if device.get('encrypted') is True and volume['filesystem'] == 'f2fs':
|
||||
android_growth_boot.capability(adapter.adb)
|
||||
android_growth_boot.identity_helper({'device':device},adapter)
|
||||
volume = inspect_android_growth(adapter,device,volume)
|
||||
action = 'grow-android-f2fs'
|
||||
else:
|
||||
@@ -243,6 +246,9 @@ def prepare(adapter, store, device, authorize_reset=None):
|
||||
tools = growth_tools(adapter,volume['filesystem'])
|
||||
action = 'grow-'+volume['filesystem']
|
||||
build(base_boot(adapter),adapter.kind,tools)
|
||||
except (ConnectionError,TimeoutError,subprocess.TimeoutExpired):
|
||||
# A lost ADB connection cannot establish that preservation is impossible.
|
||||
raise
|
||||
except (ValueError,OSError,KeyError) as error:
|
||||
reason = str(error)
|
||||
evidence = {'cid':device['cid'],'slot':device['slot'],'profile':device['profile'],
|
||||
@@ -545,10 +551,29 @@ class Uninstaller:
|
||||
raise Cancelled()
|
||||
# No reboot is expected during final checks/boot cleanup. A command or
|
||||
# write failure here must be reported, rather than hidden in a wait loop.
|
||||
if self.r.get('uninstall_android_growth_attempted'):
|
||||
if android_growth_boot.restore(self,device):
|
||||
self.r['uninstall_wait_boot_id']=device['boot_id'];self.ctx.store.save(self.r)
|
||||
self.ctx.stage('uninstall_offline','waiting_device',reboot_manually=False)
|
||||
try:
|
||||
self.adapter.adb.call('reboot')
|
||||
except (ConnectionError,OSError,TimeoutError,subprocess.TimeoutExpired):
|
||||
self.ctx.log('Expected ADB loss returning from Android growth maintenance',scope='uninstall')
|
||||
return self.run()
|
||||
if self.resume_growth:
|
||||
self.resume_growth = False
|
||||
if self.rearm_growth(device):
|
||||
return self.run()
|
||||
if (self.meta.get('action') == 'grow-android-f2fs' and
|
||||
not self.r.get('uninstall_android_growth_attempted')):
|
||||
volume = android_volume(self.adapter.adb,device,allow_small=True)
|
||||
if volume['mapped_bytes']-volume['filesystem_bytes'] > 4 << 20:
|
||||
volume = inspect_android_growth(self.adapter,device,volume)
|
||||
preservation_eligible(device,volume,self.meta['action'])
|
||||
if volume['uuid'] != self.meta['volume']['uuid']:
|
||||
raise RecoveryRequired('Android filesystem identity changed / Android 文件系统身份已变化')
|
||||
android_growth_boot.stage(self,device,volume)
|
||||
return self.run()
|
||||
return self.finish(device)
|
||||
|
||||
def rearm_growth(self, device):
|
||||
@@ -566,15 +591,7 @@ class Uninstaller:
|
||||
self.r['uninstall_growth_pending']=False;self.ctx.store.save(self.r)
|
||||
return False
|
||||
if self.meta['action'] == 'grow-android-f2fs':
|
||||
# The restored partition is already correct. Retry only Android's
|
||||
# normal pre-mount growth, never GPT removal, raw fsck or recovery.
|
||||
self.r['uninstall_wait_boot_id']=device['boot_id']
|
||||
self.ctx.store.save(self.r)
|
||||
self.ctx.stage('uninstall_offline','waiting_device',reboot_manually=False)
|
||||
try:
|
||||
adb.call('reboot')
|
||||
except (ConnectionError,OSError,subprocess.TimeoutExpired):
|
||||
self.ctx.log('Expected reconnect while Android resumes native F2FS growth',scope='uninstall')
|
||||
android_growth_boot.stage(self,device,volume)
|
||||
return True
|
||||
slot = device['slot'].removeprefix('_'); other = 'b' if slot == 'a' else 'a'
|
||||
values = adb.shell('sha256sum /dev/block/by-name/boot_'+slot+' /dev/block/by-name/boot_'+other,root=True).splitlines()
|
||||
@@ -693,6 +710,9 @@ class Uninstaller:
|
||||
raise RecoveryRequired('Preserved Android filesystem identity differs / 保留的 Android 文件系统身份不符')
|
||||
if volume['mapped_bytes']-volume['filesystem_bytes'] > 4 << 20:
|
||||
self.r['uninstall_growth_pending']=True;self.ctx.store.save(self.r)
|
||||
if self.meta['action'] == 'grow-android-f2fs' and self.r.get('uninstall_android_growth_attempted'):
|
||||
details = android_growth_boot.report(self)
|
||||
raise RecoveryRequired('Android pre-mount F2FS growth did not complete; data was not formatted. / Android 挂载前 F2FS 扩容未完成,未格式化数据。请查看扩容日志: '+details[-3000:])
|
||||
raise RecoveryRequired('Offline data growth is incomplete. Retry resumes checks/growth only; it never formats. / 离线 data 扩容尚未完成。重试仅继续检查与扩容,不会格式化。')
|
||||
if abs(volume['mapped_bytes']-expected) > 4 << 20 or not expected-(4 << 20) <= volume['filesystem_bytes'] <= expected:
|
||||
raise RecoveryRequired('Android filesystem has not reached the restored allocation / Android 文件系统尚未达到恢复后的分配容量: '
|
||||
@@ -706,6 +726,7 @@ class Uninstaller:
|
||||
self.r['uninstall_growth_pending']=False
|
||||
remote = '/data/local/tmp/openwrt-uninstall-'+self.r['id']
|
||||
try:
|
||||
android_growth_boot.cleanup(self)
|
||||
# Fixed filenames in this transaction's own staging directories.
|
||||
# Never recursively remove userdata paths or other installations.
|
||||
adb.shell('rm -f '+remote+'/boot.img '+remote+'/trial.bin '+remote+'/before-boot.img '+remote+'/before-bc '+
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Pre-mount worker uses private regular-file fixtures, never real userdata."""
|
||||
from pathlib import Path
|
||||
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]))
|
||||
from backend import android_growth_boot as growth
|
||||
from backend.state import RecoveryRequired
|
||||
import test_uninstall as fx
|
||||
|
||||
|
||||
class ImageBounds(unittest.TestCase):
|
||||
def test_only_ramdisk_can_change(self):
|
||||
original = bytearray(64 << 20)
|
||||
original[:8] = b'ANDROID!'
|
||||
struct.pack_into('<III', original, 8, 4096, 4096, 0)
|
||||
struct.pack_into('<I', original, 40, 4)
|
||||
updated = bytearray(original); updated[8192] = 1
|
||||
growth.verify_image(original, updated)
|
||||
for offset in (8, 16, 40, 44, 4096):
|
||||
bad = bytearray(updated); bad[offset] ^= 1
|
||||
with self.subTest(offset=offset), self.assertRaises(ValueError):
|
||||
growth.verify_image(original, bad)
|
||||
with self.assertRaises(ValueError):growth.verify_image(original, original)
|
||||
|
||||
|
||||
class PreMount(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.fx = fx.Journal(); self.fx.setUp()
|
||||
ctx = self.fx.plan()
|
||||
self.record = ctx.record
|
||||
self.record['uninstall']['volume'].update(uuid='55'*16,filesystem_bytes=28*fx.GIB)
|
||||
self.adapter = self.fx.adapter
|
||||
self.adapter.root = Path(self.fx.temp.name)
|
||||
self.adapter.adb.shell = Mock(return_value='a'*64+' /system/bin/fsck.f2fs')
|
||||
self.adapter.adb.call = Mock()
|
||||
self.volume = {'android_growth':{'resizer_sha256':'b'*64}}
|
||||
# A successful Android A control, with an inactive low-priority slot.
|
||||
raw = bytearray(32); raw[:8]=b'_a\0\0BCAB'; raw[8]=1;raw[9]=2;raw[12]=0x9f;raw[14]=0x1e
|
||||
import zlib
|
||||
struct.pack_into('<I', raw, 28, zlib.crc32(raw[:28]))
|
||||
self.control = bytes(raw)
|
||||
|
||||
def tearDown(self):self.fx.tearDown()
|
||||
|
||||
def rendered(self):
|
||||
return growth.scripts(self.record, self.adapter, self.volume, 'c'*64)
|
||||
|
||||
def test_restore_requires_original_backup_and_exact_maintenance_image(self):
|
||||
directory=Path(self.fx.temp.name)/'restore-fixture'
|
||||
source=directory/'uninstall/android-growth/android.img'
|
||||
source.parent.mkdir(parents=True)
|
||||
with source.open('wb') as stream:stream.truncate(64 << 20)
|
||||
expected=growth.sha(source)
|
||||
device=self.record['device']
|
||||
self.record.update(uninstall_android_growth_attempted=True,
|
||||
uninstall_android_growth_source_sha256=expected,
|
||||
uninstall_android_growth_sha256='f'*64)
|
||||
ctx=SimpleNamespace(directory=directory,store=SimpleNamespace(save=Mock()),effect=Mock())
|
||||
worker=SimpleNamespace(r=self.record,adapter=self.adapter,ctx=ctx,layout_state=lambda:'after')
|
||||
self.adapter.adb.shell=Mock(return_value=expected+' boot_a')
|
||||
growth.restore(worker,device)
|
||||
ctx.effect.assert_not_called()
|
||||
self.adapter.adb.shell=Mock(return_value='f'*64+' boot_a')
|
||||
with patch('backend.android_growth_boot.push_chunks') as push:
|
||||
growth.restore(worker,device)
|
||||
push.assert_called_once()
|
||||
ctx.effect.assert_called_once()
|
||||
# Executing only the mocked shell callback proves target selection.
|
||||
ctx.effect.call_args.args[1]()
|
||||
script=self.adapter.adb.shell.call_args.args[0]
|
||||
self.assertIn('of=/dev/block/by-name/boot_a',script)
|
||||
self.assertNotIn('misc',script)
|
||||
self.assertNotIn('userdata',script)
|
||||
self.assertNotIn('of=/dev/block/by-name/boot_b',script)
|
||||
self.adapter.adb.shell=Mock(return_value='e'*64+' boot_a')
|
||||
with self.assertRaisesRegex(RecoveryRequired,'neither'):
|
||||
growth.restore(worker,device)
|
||||
source.write_bytes(b'broken')
|
||||
with self.assertRaisesRegex(RecoveryRequired,'backup'):
|
||||
growth.restore(worker,device)
|
||||
|
||||
def test_templates_keep_keys_gpt_and_raw_userdata_out_of_resize(self):
|
||||
files = self.rendered()
|
||||
joined = b'\n'.join(files.values()).decode()
|
||||
self.assertNotIn('@TARGET@',joined)
|
||||
self.assertNotIn('dmsetup',joined)
|
||||
self.assertNotIn('setenforce',joined)
|
||||
self.assertNotIn('mkfs',joined)
|
||||
wrapper = next(v.decode() for k,v in files.items() if k.endswith('-wrapper.sh'))
|
||||
self.assertIn('mapper-mounted',wrapper)
|
||||
self.assertIn('filesystem-identity',wrapper)
|
||||
self.assertIn('"$base/resize.f2fs" -t',wrapper)
|
||||
self.assertNotIn('of=/dev/',wrapper)
|
||||
|
||||
def test_e5_ufs_embeds_its_identity_tool_and_preserves_actual_slot(self):
|
||||
self.record['device']['slot']='_b'
|
||||
self.record['device']['storage']['NODE']='sda75'
|
||||
folder=self.adapter.root/'files';folder.mkdir(exist_ok=True)
|
||||
binary=bytearray(32);binary[:6]=b'\x7fELF\x02\x01';struct.pack_into('<H',binary,18,183)
|
||||
(folder/'e5-ufs-id').write_bytes(binary)
|
||||
files=self.rendered()
|
||||
self.assertEqual(next(value for name,value in files.items() if name.endswith('-ufs-id')),binary)
|
||||
setup=next(value.decode() for name,value in files.items() if name.endswith('-setup.sh'))
|
||||
self.assertIn('export E5_UFS_ID_HELPER="$2"',setup)
|
||||
self.assertIn('= _b',setup)
|
||||
rc=next(value.decode() for name,value in files.items() if name.endswith('.rc'))
|
||||
self.assertIn('-ufs-id',rc)
|
||||
(folder/'e5-ufs-id').write_bytes(b'bad')
|
||||
with self.assertRaises(ValueError):self.rendered()
|
||||
|
||||
@unittest.skipUnless(sys.platform.startswith('linux'),'Linux/Android command semantics')
|
||||
def test_real_wrapper_success_refusal_and_failure_receipts(self):
|
||||
for fault in ('none','4k','mounted','uuid','mapping','fsck','resizer','no-growth'):
|
||||
with self.subTest(fault=fault),tempfile.TemporaryDirectory() as temp:
|
||||
root=Path(temp);base=root/'base';base.mkdir();sysroot=root/'sys';node=sysroot/'dm-4'
|
||||
(node/'dm').mkdir(parents=True);(node/'slaves').mkdir()
|
||||
slave=self.record['device']['storage']['NODE']
|
||||
(node/'slaves'/('wrong' if fault=='mapping' else slave)).touch()
|
||||
(node/'dev').write_text('254:4\n')
|
||||
mounts=root/'mountinfo';mounts.write_text('1 0 254:4 / /data rw - f2fs /dev/block/dm-4 rw\n' if fault=='mounted' else '')
|
||||
device=root/'dm-4';raw=bytearray(8192)
|
||||
raw[1024:1028]=bytes.fromhex('1020f5f2');struct.pack_into('<I',raw,1040,12)
|
||||
struct.pack_into('<Q',raw,1060,28*fx.GIB//4096)
|
||||
raw[1132:1148]=bytes.fromhex(('66' if fault=='uuid' else '55')*16)
|
||||
device.write_bytes(raw)
|
||||
marker=root/'calls'
|
||||
(base/'fsck.f2fs').write_text('#!/bin/sh\necho fsck >> '+str(marker)+'\nexit '+('1' if fault=='fsck' else '0')+'\n')
|
||||
# Fixture resizer updates only the synthetic superblock count.
|
||||
(base/'resize.f2fs').write_text('#!/bin/sh\necho resize >> '+str(marker)+'\n'+
|
||||
'[ "$1" = -t ] && [ "$2" = '+str(32*fx.GIB//(4096 if fault=='4k' else 512))+' ] || exit 9\n'+
|
||||
('exit 1\n' if fault=='resizer' else '' if fault=='no-growth' else
|
||||
"printf '\\000\\000\\200\\000\\000\\000\\000\\000' | dd of="+str(device)+' bs=1 seek=1060 conv=notrunc 2>/dev/null\n'))
|
||||
for file in (base/'fsck.f2fs',base/'resize.f2fs'):file.chmod(0o755)
|
||||
files=self.rendered()
|
||||
source=next(v.decode() for k,v in files.items() if k.endswith('-wrapper.sh'))
|
||||
source=source.replace('/dev/openwrt-grow-'+self.record['id'],str(base)).replace('/sys/class/block',str(sysroot))
|
||||
source=source.replace('/proc/self/mountinfo',str(mounts)).replace('/proc/1/mountinfo',str(mounts))
|
||||
sector=4096 if fault=='4k' else 512
|
||||
source='blockdev() { if [ "$1" = --getss ]; then echo '+str(sector)+'; else echo '+str(32*fx.GIB)+'; fi; }\n'+source.partition('\n')[2]
|
||||
wrapper=root/'fsck.f2fs';wrapper.write_text(source)
|
||||
result=subprocess.run(['sh',str(wrapper),'-a',str(device)],capture_output=True,text=True)
|
||||
if fault in ('none','4k'):
|
||||
self.assertEqual(result.returncode,0,result.stderr+(base/'worker.log').read_text())
|
||||
self.assertEqual((base/'result').read_text().strip(),'GROWTH_VERIFIED')
|
||||
self.assertEqual(marker.read_text().split(),['fsck','resize'])
|
||||
elif fault=='mapping':
|
||||
# Other devices get the unchanged stock invocation only.
|
||||
self.assertEqual(result.returncode,0,result.stderr)
|
||||
self.assertEqual(marker.read_text().split(),['fsck'])
|
||||
self.assertFalse((base/'result').exists())
|
||||
else:
|
||||
self.assertNotEqual(result.returncode,0)
|
||||
self.assertIn('FAILED:',(base/'result').read_text())
|
||||
if fault in ('mounted','uuid'):self.assertFalse(marker.exists())
|
||||
|
||||
@unittest.skipIf(sys.platform=='win32','POSIX shell syntax')
|
||||
def test_rendered_scripts_parse_in_shell(self):
|
||||
for name,data in self.rendered().items():
|
||||
if name.endswith('.sh'):
|
||||
result=subprocess.run(['sh','-n'],input=data,capture_output=True)
|
||||
self.assertEqual(result.returncode,0,(name,result.stderr))
|
||||
|
||||
def test_staging_only_writes_the_actual_android_slot_and_restores_on_write_failure(self):
|
||||
for slot in ('a','b'):
|
||||
self.fx.configure('e5',slot)
|
||||
context=self.fx.plan();device={**context.record['device'],'userdata_bytes':32*fx.GIB}
|
||||
self.fx.adapter.root=Path(self.fx.temp.name)
|
||||
self.fx.adapter.adb.call=Mock()
|
||||
self.fx.adapter.adb.shell=Mock(return_value='a'*64+' fsck.f2fs')
|
||||
worker=SimpleNamespace(adapter=self.fx.adapter,ctx=context,r=context.record,layout_state=lambda:'after')
|
||||
native=bytearray(64 << 20);native[:8]=b'ANDROID!'
|
||||
struct.pack_into('<III',native,8,4096,4096,0);struct.pack_into('<I',native,40,4)
|
||||
patched=bytearray(native);patched[8192]=1
|
||||
def pull(_call,_shell,_cmd,dest,**_):
|
||||
with Path(dest).open('wb') as stream:
|
||||
stream.write(native[:4096]);stream.truncate(len(native))
|
||||
with patch('backend.android_growth_boot.capability',return_value='a'*64),\
|
||||
patch('backend.android_growth_boot.pull_binary',side_effect=pull),\
|
||||
patch('backend.android_growth_boot.prepare_image',return_value=bytes(patched)),\
|
||||
patch('backend.android_growth_boot.push_chunks'):
|
||||
growth.stage(worker,device,self.volume)
|
||||
scripts=[c.args[0] for c in self.fx.adapter.adb.shell.call_args_list]
|
||||
commit=next(s for s in scripts if 'ANDROID_GROWTH_BOOT_RESTORED' in s)
|
||||
self.assertIn('of=/dev/block/by-name/boot_'+slot,commit)
|
||||
self.assertNotIn('of=/dev/block/by-name/boot_'+('b' if slot=='a' else 'a'),commit)
|
||||
self.assertNotIn('misc',commit)
|
||||
self.assertNotIn('userdata',commit)
|
||||
self.fx.adapter.adb.call.assert_called_once_with('reboot')
|
||||
self.assertTrue(context.record['uninstall_growth_pending'])
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -47,7 +47,7 @@ class AndroidGrowth(unittest.TestCase):
|
||||
raise AssertionError('Unexpected read: '+command)
|
||||
|
||||
def plan(self):
|
||||
with patch('backend.uninstall.android_volume',return_value=self.volume),patch('backend.uninstall.base_boot'),patch('backend.uninstall.build'),patch('backend.uninstall.growth_tools',side_effect=AssertionError('raw encrypted resize')):
|
||||
with patch('backend.uninstall.android_growth_boot.capability',return_value='a'*64),patch('backend.uninstall.android_volume',return_value=self.volume),patch('backend.uninstall.base_boot'),patch('backend.uninstall.build'),patch('backend.uninstall.growth_tools',side_effect=AssertionError('raw encrypted resize')):
|
||||
plan,meta,files=prepare(self.fx.adapter,self.fx.store,self.device)
|
||||
record=self.fx.store.create(self.fx.package,self.device,{'method':'uninstall'},plan)
|
||||
context=Context(self.fx.store,record,lambda *_:None);persist(context,meta,files)
|
||||
@@ -92,6 +92,14 @@ class AndroidGrowth(unittest.TestCase):
|
||||
changed={**volume,'android_growth':{**volume['android_growth'],key:value}}
|
||||
with self.subTest(key=key),self.assertRaises(ValueError):android_eligible(self.device,changed)
|
||||
|
||||
def test_adb_loss_does_not_offer_erase_data_fallback(self):
|
||||
consent=Mock(return_value=True)
|
||||
with patch('backend.uninstall.android_volume',return_value=self.volume),\
|
||||
patch('backend.uninstall.android_growth_boot.capability',side_effect=ConnectionError('offline')):
|
||||
with self.assertRaises(ConnectionError):
|
||||
prepare(self.fx.adapter,self.fx.store,self.device,consent)
|
||||
consent.assert_not_called()
|
||||
|
||||
def test_final_capacity_and_uuid_must_match_before_boot_cleanup(self):
|
||||
context=self.plan();worker=Uninstaller(None,context,self.fx.adapter)
|
||||
device={**self.device,'existing':False,'userdata_bytes':32*fx.GIB}
|
||||
@@ -108,9 +116,10 @@ class AndroidGrowth(unittest.TestCase):
|
||||
with patch('backend.uninstall.android_volume',return_value=short),patch.object(worker,'finish_boot',side_effect=AssertionError('early cleanup')):
|
||||
with self.assertRaises(RecoveryRequired):worker.finish(device)
|
||||
self.assertTrue(context.record['uninstall_growth_pending'])
|
||||
with patch('backend.uninstall.android_volume',return_value=short),patch.object(worker,'layout_state',return_value='after'):
|
||||
with patch('backend.uninstall.android_volume',return_value=short),patch.object(worker,'layout_state',return_value='after'),patch('backend.uninstall.android_growth_boot.stage') as stage:
|
||||
self.assertTrue(worker.rearm_growth(device))
|
||||
self.fx.adb.call.assert_called_once_with('reboot')
|
||||
stage.assert_called_once()
|
||||
self.fx.adb.call.assert_not_called()
|
||||
self.assertFalse(any('of=' in c.args[0] for c in self.fx.adb.shell.call_args_list))
|
||||
|
||||
def test_changed_filesystem_uuid_cannot_finish_or_restart_growth(self):
|
||||
|
||||
@@ -4,7 +4,7 @@ export const strings = {
|
||||
mtpDisableFailed:'未能禁用设备的 MTP 接口', mtpDisableFailedDesc:'Windows 未完成操作。有线 ADB 可能仍不稳定;安装流程将继续。',
|
||||
uninstallCancel:'取消卸载', uninstallResetQuestion:'无法保留 Android 数据卸载,是否格式化?',
|
||||
uninstallResetExplanation:'格式化会清空 Android 应用、账号、照片和内部存储。取消不会修改分区或清空 Android 数据;选择格式化后会先展示新的卸载计划,不会立即执行。',
|
||||
uninstallJournalRecovery:'正在回放 OpenWrt 文件系统日志,完成后继续核验卸载计划…', uninstallPreserveAndroid:'删除内置 OpenWrt 及其设置,归还分区空间后由原厂 Android 在解密后、挂载前扩容 F2FS,保留 Android 数据。完成后会核验文件系统身份和容量;失败不会自动格式化。', uninstallChooseReset:'选择格式化并查看计划', uninstallPreserve:'删除内置 OpenWrt 及其设置,在离线环境检查并扩容未加密 userdata,保留 Android 数据。请仍备份重要文件;检查失败会停止,不会自动格式化。',
|
||||
uninstallJournalRecovery:'正在回放 OpenWrt 文件系统日志,完成后继续核验卸载计划…', uninstallPreserveAndroid:'删除内置 OpenWrt 及其设置,归还空间后通过原厂工具在解密映射挂载前扩容 F2FS,保留 Android 数据。必要时临时加入 Android 启动维护步骤,完成后恢复原启动镜像。最终核验文件系统身份和容量;失败不会自动格式化。', uninstallChooseReset:'选择格式化并查看计划', uninstallPreserve:'删除内置 OpenWrt 及其设置,在离线环境检查并扩容未加密 userdata,保留 Android 数据。请仍备份重要文件;检查失败会停止,不会自动格式化。',
|
||||
uninstallUncertain:'上次卸载写入尚未确认完成。请保留备份并重连复核;暂停或关闭安装器不能保证撤回设备上的操作。',
|
||||
uninstallArmedWarning:'卸载请求已写入,重启后会执行。暂停或关闭安装器只停止电脑上的等待,不会撤回设备上的卸载或已确认的重置。请保持供电。',
|
||||
uninstall:'卸载并归还空间', uninstallDesc:'移除内置 OpenWrt,检查可归还给 Android 或释放为空闲的空间。',
|
||||
@@ -75,7 +75,7 @@ export const strings = {
|
||||
mtpDisableFailed:'Could not disable the device MTP interface', mtpDisableFailedDesc:'Windows did not complete the operation. Wired ADB may still be unstable; installation will continue.',
|
||||
uninstallCancel:'Cancel removal', uninstallResetQuestion:'Cannot preserve Android data. Format instead?',
|
||||
uninstallResetExplanation:'Formatting erases Android apps, accounts, photos and internal storage. Cancel does not change partitions or erase Android data. Choosing format first opens a new removal plan; it does not execute it.',
|
||||
uninstallJournalRecovery:'Recovering the OpenWrt filesystem journal, then continuing uninstall checks…', uninstallPreserveAndroid:'Remove internal OpenWrt and its settings, return the space, and let stock Android grow decrypted F2FS before mounting it. Preserve Android data and verify filesystem identity and capacity afterwards. Failures never trigger formatting.', 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.',
|
||||
uninstallJournalRecovery:'Recovering the OpenWrt filesystem journal, then continuing uninstall checks…', uninstallPreserveAndroid:'Remove internal OpenWrt and its settings, return the space, and grow decrypted F2FS before mounting it with this device’s stock tools. If needed, temporarily add Android boot maintenance and restore the original boot image afterwards. Preserve Android data and verify filesystem identity and capacity. Failures never trigger formatting.', 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 check which space can return to Android or become unallocated.',
|
||||
|
||||
@@ -114,8 +114,40 @@ test('installed E5-family images do not require an orange verified-boot property
|
||||
}
|
||||
});
|
||||
|
||||
test('missing current slot never falls back to misc; unsupported models and identical boots stop', async () => {
|
||||
for (const options of [{slot: ''}, {slot: '_c'}, {model: 'FM_U20', device: 'FM_U20'}, {model: 'V50', device: 'MU3351', platform: 'wrong'}, {identical: true}]) {
|
||||
test('model and platform names never gate either installed image format or Android slot', async () => {
|
||||
for (const family of ['e5', 'mu300']) for (const slot of ['a', 'b']) {
|
||||
for (const options of [
|
||||
{model: '畅行60', device: 'unknown', platform: 'new-platform'},
|
||||
{model: 'LYM-10K', device: 'unknown'},
|
||||
{model: 'FM_U20', device: 'FM_U20'},
|
||||
{model: 'V50', device: 'MU3351', platform: 'wrong'},
|
||||
{model: 'MU300', device: 'MU300'},
|
||||
{model: 'E5', device: 'E5'},
|
||||
{model: 'unknown', device: 'unknown'}
|
||||
]) {
|
||||
const tr = transport(fixture(family, slot), options);
|
||||
const result = await load(tr.fn).probe();
|
||||
assert.equal(result.family, family); assert.equal(result.slot, slot);
|
||||
assert.ok(tr.commands.every(cmd => !cmd.includes('of=') && !cmd.includes('mount ')));
|
||||
assert.ok(tr.commands.every(cmd => !/getprop ro\.(product|board)/.test(cmd)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('unknown model with stock, corrupt or pending boot still stops before any write', async () => {
|
||||
for (const family of ['e5', 'mu300']) {
|
||||
for (const command of ['androidboot.hardware=stock', 'e5.part_v=2 e5.part_prepare=abc', 'loglevel=5 openwrt.uninstall=1']) {
|
||||
const tr = transport(fixture(family, 'a', command), {model: 'unknown', device: 'unknown'});
|
||||
await assert.rejects(load(tr.fn).probe());
|
||||
assert.ok(tr.commands.every(cmd => !cmd.includes('of=')));
|
||||
}
|
||||
const info = fixture(family); info.tail = '00'.repeat(512);
|
||||
await assert.rejects(load(transport(info, {model: 'unknown'}).fn).probe());
|
||||
}
|
||||
});
|
||||
|
||||
test('missing current slot never falls back to misc; identical boots stop', async () => {
|
||||
for (const options of [{slot: ''}, {slot: '_c'}, {identical: true}]) {
|
||||
const tr = transport(fixture(), options); await assert.rejects(load(tr.fn).probe());
|
||||
if ('slot' in options) assert.equal(tr.commands.length, 1);
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ def repack(source,target,studio,revision,repair_installer=False,refresh_native=F
|
||||
removed=set()
|
||||
if refresh_native:
|
||||
patches,removed=native['replacements'](old,studio)
|
||||
patches['extras/android/openwrt-system-switch-plugin.js']=TOP/'android/magisk/webui-plugins/mu300-system-switch.js'
|
||||
manifest=json.loads(old.read('desktop/manifest.json'))
|
||||
checks={**manifest['magisk'],**manifest['desktop']}
|
||||
for name,wanted in tool['files'].items():
|
||||
|
||||
Reference in new issue
Block a user