From 3826be8b6bd73d75f72bbdc7eb8bf6e9c97054ee Mon Sep 17 00:00:00 2001 From: kanoqwq Date: Mon, 12 Oct 2026 19:10:11 +0800 Subject: [PATCH] feat(mu300): add persistent APN management and safe mount discovery --- docs/APN-AND-BLOCK-MOUNT.md | 85 +++++ docs/F50-ANDROID-APN-RIL-RESEARCH.zh-CN.md | 361 ++++++++++++++++++ openwrt/block-mount.Dockerfile | 5 + openwrt/block-probe-guard.h | 35 ++ openwrt/build-block-mount-inner.sh | 48 +++ openwrt/build-block-mount.sh | 24 ++ openwrt/build-rootfs.sh | 13 + openwrt/luci-app-mu300/Makefile | 5 +- openwrt/luci-app-mu300/README.md | 9 + .../luci-static/resources/mu300/common.js | 48 +++ .../luci-static/resources/view/mu300/apn.js | 107 ++++++ openwrt/luci-app-mu300/lmo/mu300.en.lmo | Bin 324 -> 360 bytes openwrt/luci-app-mu300/lmo/mu300.tr.lmo | Bin 340 -> 380 bytes openwrt/luci-app-mu300/po/en/mu300.po | 3 + openwrt/luci-app-mu300/po/tr/mu300.po | 3 + .../luci-app-mu300/root/etc/config/unisoc_apn | 4 + .../root/usr/libexec/rpcd/mu300dash | 8 + .../root/usr/libexec/unisoc-modem/apn | 66 ++++ .../usr/libexec/unisoc-modem/apn-identity | 12 + .../root/usr/libexec/unisoc-modem/apn.uc | 135 +++++++ .../usr/share/luci/menu.d/luci-app-mu300.json | 6 + .../usr/share/rpcd/acl.d/luci-app-mu300.json | 2 +- openwrt/overlay/lib/netifd/proto/mu300cell.sh | 19 +- .../patches/fstools-probe-device-types.patch | 20 + rootfs/overlay/opt/mu300/bin/mobile-data | 103 ++++- tests/apn.uc | 79 ++++ tests/block_mount_runtime.sh | 34 ++ tests/block_probe_guard.c | 56 +++ tests/test_apn.py | 99 +++++ tests/test_apn_ui.py | 80 ++++ tests/test_block_probe.py | 32 ++ tests/test_mu300_i18n.py | 2 +- tools/build-openwrt-tf-magisk.sh | 3 + tools/make-release.sh | 3 + 34 files changed, 1490 insertions(+), 19 deletions(-) create mode 100644 docs/APN-AND-BLOCK-MOUNT.md create mode 100644 docs/F50-ANDROID-APN-RIL-RESEARCH.zh-CN.md create mode 100644 openwrt/block-mount.Dockerfile create mode 100644 openwrt/block-probe-guard.h create mode 100644 openwrt/build-block-mount-inner.sh create mode 100644 openwrt/build-block-mount.sh create mode 100644 openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/apn.js create mode 100644 openwrt/luci-app-mu300/root/etc/config/unisoc_apn create mode 100644 openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/apn create mode 100644 openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/apn-identity create mode 100644 openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/apn.uc create mode 100644 openwrt/patches/fstools-probe-device-types.patch create mode 100644 tests/apn.uc create mode 100644 tests/block_mount_runtime.sh create mode 100644 tests/block_probe_guard.c create mode 100644 tests/test_apn.py create mode 100644 tests/test_apn_ui.py create mode 100644 tests/test_block_probe.py diff --git a/docs/APN-AND-BLOCK-MOUNT.md b/docs/APN-AND-BLOCK-MOUNT.md new file mode 100644 index 00000000..09a3306b --- /dev/null +++ b/docs/APN-AND-BLOCK-MOUNT.md @@ -0,0 +1,85 @@ +# APN profiles and safe mount-point discovery + +## APN page + +`Cellular → Access points (APN)` uses the standalone dashboard's dialogs, +toasts, theme bridge and Chinese/English/Turkish translations. It supports +adding, editing, deleting and explicitly applying up to 32 profiles. + +Profiles live in `/etc/config/unisoc_apn` (a package conffile). Saving a profile +only changes the list. Applying defaults to remembering the choice by the current +SIM's ICCID. The platform dialer resolves this binding on every bearer setup; +switching cards does not inherit the other card's private APN or credentials. +An unbound SIM uses the global network settings. With the remember checkbox +unchecked, applying updates the global interface instead. Automatic selection +is also per SIM: a small, independently maintained Chinese public-carrier list +uses IMSI; unknown carriers fall back to an empty SIM-default APN. IoT/private +networks must be configured manually. Applying asks netifd to reload and cycle +only `unisoc_modem.main.data_interface` (default `wan`). It does not +restart the network service, USB, Wi-Fi or switch the data SIM. Existing DNS, +IPv6 and LAN settings are preserved. Configuration selection is displayed +separately from the interface's actual connected/pending state. + +The current profile is matched against the saved SIM binding or network configuration, not +an independent active-profile flag. An active or SIM-bound profile cannot be deleted. Editing +it is save-only; click Switch to apply the new settings. Empty APN means SIM +default and explicitly clears the old modem APN on the next netifd setup. + +The backend currently supports `mu300cell` and its existing IPv4/dual-stack +bearers (`IP`, `IPV4V6`). It does not advertise unsupported IPv6-only bearers. +Authentication supports none/PAP/CHAP/PAP-or-CHAP using +the Android B09 RIL's `CGDCONT → CGPCO → CGDATA` path. Optional advanced initial +attach configuration uses `SPCGAPNCFG`, is off by default, and never touches IMS +CID 11. Commands require exact OK before dial continuation; errors never include +credentials. Passwords are write-only in RPC/UI, preserved on blank edits unless +explicitly cleared; the conffile is root-only. A successful Apply means configuration was saved and +netifd accepted the request, not that the carrier has granted internet access. +Failed apply requests report whether the configuration was already saved. +Pending LuCI/UCI network edits are never silently committed or discarded. + +No AT queries or periodic polling are needed to display this page. Remembered +selection writes read ICCID once through the configured standalone AT adapter; +the dialer reads IMSI only for an automatic binding. Writes use +the existing data-SIM switch gate to exclude concurrent card changes, and defer +while an interactive modem lock operation is running. + +## Safe block-mount + +fstools scans `/dev/sd*` even for `block info /dev/specific-device`. On Unisoc, +that glob also matches communication character devices. Filtering LuCI's result +or passing an explicit disk path cannot prevent the underlying probe from +opening such a channel. + +`openwrt/patches/fstools-probe-device-types.patch` checks device type before +`probe_path()`: block devices and regular files (including swapfiles) are allowed; +character devices are allowed only if sysfs identifies their subsystem as UBI. +FIFOs, sockets, directories and other character devices are skipped without +opening them. Device names alone are not trusted to identify UBI. + +`openwrt/build-block-mount.sh` builds a real patched APK with the checksum-pinned +OpenWrt 25.12.5 ARM64 SDK and matching fstools revision. The SDK uses a separate +Docker cache; parallel rootfs builds serialize SDK access. Its output cache is +keyed by source/build-script contents and verifies the APK checksum before reuse. +The normal OpenWrt/TF/release build installs this APK (including fstab scripts +and libblkid-tiny), and verifies the required payloads. It never temporarily +installs an unsafe block binary on a live router. Package dependency checking +is retained; incompatible base libraries must fail the build. + +This adds mount-point management, not blanket auto-mount/format behavior. +Existing fstab settings are unchanged. Upgrading block-mount independently from +an unpatched package feed can remove the guard; regenerate the custom package +when updating the base fstools/SDK version. + +## Regression checks + +``` +python3 -m unittest discover -s tests -p 'test_apn*.py' -v +python3 -m unittest discover -s tests -p 'test_mu300_i18n.py' -v +python3 -m unittest discover -s tests -p 'test_block_probe.py' -v +ucode -L 'openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/*.uc' tests/apn.uc +``` + +`apn.uc` uses a temporary real libuci database. The optional Playwright test +(`MU300_BROWSER_TESTS=1`, optional `MU300_BROWSER_CHANNEL=msedge`) uses real UI +components with isolated fake RPC, never the router. Actual carrier acceptance +of a user's APN still needs testing with that carrier/SIM. diff --git a/docs/F50-ANDROID-APN-RIL-RESEARCH.zh-CN.md b/docs/F50-ANDROID-APN-RIL-RESEARCH.zh-CN.md new file mode 100644 index 00000000..f89927ad --- /dev/null +++ b/docs/F50-ANDROID-APN-RIL-RESEARCH.zh-CN.md @@ -0,0 +1,361 @@ +# F50 Android APN 服务与 RIL 静态逆向报告 + +日期:2026-10-12。对象:本地 `f50_b09` 原厂 Android 解包;对照当前 `clean-tf-7.2` 分支的 APN 管理实现。 + +## 1. 结论先行 + +当前插件的 APN 列表管理可用,但与原厂 Android 相比,拨号配置能力还不完整。建议分批补齐,而不是把 Android 的 RIL 服务搬进 OpenWrt。 + +1. **“APN 留空”不等于 Android 的“自动 APN”。** 原厂从运营商 APN 数据库选择记录,经过 SIM/运营商匹配后设置 preferred APN;还会按 ICCID 恢复手动选择。我们目前只是向调制解调器提交空 APN,让网络/模组决定默认值。 +2. **普通数据拨号的鉴权路径已找到:`AT+CGPCO`。** 不应凭其他品牌的实现直接添加 `CGAUTH`。这份 RIL 的可达拨号分支在 `CGDCONT` 之后、`CGDATA` 之前下发用户名、密码、CID 和鉴权类型。 +3. **初始附着 APN 是另一条路径:`AT+SPCGAPNCFG`。** 它包含 APN、本地协议、漫游协议与鉴权,不能和普通 PDP 配置混为一谈,也不能把其首个常量 `1` 直接当成任意业务 CID。 +4. **应按 SIM 身份保存选择,不能只保留一个全局 WAN APN。** 原厂“按 ICCID 记忆”的思路可以借鉴,但其 Web 服务存在默认订阅/单卡假设,不能照抄进我们的双卡控制逻辑。 +5. **配置提交、AT 接受、PDP 建立、互联网可达必须分开表示。** 原厂部分 RIL 分支本身也忽略 AT 发送结果;不能把 Android 回调成功当作可靠的回读确认范本。 + +本轮只做静态分析与报告:没有连接实机,没有发 AT,没有切 APN、重启服务、改网络或热部署新行为。现有已暂存的 APN/挂载点代码未改动。 + +## 2. 样本、方法和证据等级 + +解包根目录:`D:\随身WiFi\F50相关\F50_B15研究\f50_b09`。 + +方法:JADX 1.5.5 反编译 Java;pyelftools 读取 ELF 符号、重定位和 `.eh_frame` 函数边界;Capstone/AArch64 objdump 核对指令、参数装载、跳转表及调用顺序。**不是只搜索 AT 字符串后猜用途。** + +证据分为: + +- **已证实(静态)**:本样本的可读 Java 逻辑,或原生指令及调用链可直接支持。 +- **推断/建议**:结合当前 OpenWrt 实现得出的移植设计,尚未实现。 +- **待实测**:模组实际接受的命令/字符范围、不同 SIM/运营商效果,以及运行时采用的 Android 数据库内容。 + +JADX 对部分复杂方法未完整还原,包括 Provider 的 `initDatabase()` 等;生成的 `UnsupportedOperationException("Method not decompiled...")` 是反编译占位,**不是 Android 原程序真的会抛该异常**。这些方法没有被当作已闭合证据。 + +### 2.1 样本 SHA-256 + +下列路径相对于解包根目录;地址均为相应 ELF 的虚拟地址,不是 ASLR 后的运行地址。 + +| 样本 | SHA-256 | +| --- | --- | +| `system_a/system/priv-app/ZteWebServer/ZteWebServer.apk` | `738419dd8254804b0b21ea129f9eadcf6819f800cfb1fe25834cc0b2d6c6e4c1` | +| `system_a/system/priv-app/TelephonyProvider/TelephonyProvider.apk` | `bed4ef63f3fde40cfc37d0f604c80c05c43a0f735cee45504005391b017aa78f` | +| `system_a/system/framework/telephony-common.jar` | `fa83ad3e143620af01b0ef8888299a816b61d2271b004e6ab7a93894156c3be4` | +| `vendor_a/lib64/librilcore.so` | `cb68b650d52e1a2bc4f645c0db6ecf077c0044d36233d03bc1b80c9f0cf8c050` | +| `vendor_a/lib64/libimpl-ril.so` | `a0e8e71fa1f4afda302f7471abd419f9f861256ebe7a63a4421c00cdb0c8b3ec` | +| `system_a/system/etc/apns-conf.xml` | `8b4e40028675e37e7d80ddcf95158ac0b2439ea805491fd9f3628cd023668f37` | +| `product_a/etc/apns-conf.xml` | `70930b91100e0d515a58670baf630c02bfbc29accfb73dcb72f80813c9fca9a3` | + +### 2.2 本地证据索引 + +以下反编译/反汇编产物位于忽略跟踪的 `work/`,不把完整厂商代码放进 Git: + +- `work/msisdn-static/zte-web/sources/com/zte/web/module/apn/`:`ApnModule.java`、`ApnHandler.java`、`ApnAutoConfigJobService.java`、`SimCardApnRecordsContract.java`、`SimCardApnRecordsDBHelper.java`。 +- 同一 `zte-web/sources/` 下 `com/zte/web/module/network/SimStateChangedReceiver.java`。 +- `work/msisdn-static/telephony/sources/com/android/internal/telephony/`:`RIL.java`、`RILUtils.java`、`RadioDataProxy.java`、`data/DataProfileManager.java`、`dataconnection/DcTracker.java`。 +- 本轮重新反编译的 `work/apn-android-research/ApnHandler.java`,与之前缓存版本比对一致。 +- 本轮生成的 `work/apn-android-research/provider/sources/com/android/providers/telephony/TelephonyProvider.java`。 +- `work/apn-android-research/{native,core}/disassembly.txt`、`string-refs.txt`、`function-ranges.txt`,分别对应 libimpl-ril / librilcore。 +- 本轮 ELF 辅助脚本:`work/apn-ril-static.py`。自动字符串注释仅用于导航;关键分支另核对指令,不能把线性寄存器追踪当作完整反编译器。 + +## 3. 原厂调用链 + +```text +ZteWebServer 的 APN 页面请求 + → ApnModule(save / delete / set_default / auto) + → ApnHandler + → TelephonyProvider 的 carriers / preferapn / sim_apn_list + → Android 电话框架的数据配置/拨号管理 + → RIL.java → RadioDataProxy → Radio HAL + → librilcore.so(AIDL 参数转原生结构) + → libimpl-ril.so(processDataRequest) + → AT 通道 → 基带 + +SIM 状态事件 + → SimStateChangedReceiver → ApnAutoConfigJobService + → 按 ICCID 查历史选择 → 恢复 preferred APN +``` + +`vendor_a/etc/init/unisoc.rild.rc:1` 定义 `vendor.ril-daemon /vendor/bin/hw/urild`。本样本的 librilcore 含 AIDL `RadioData::setInitialAttachApn`、`setupDataCall` 等具体实现,Java `RadioDataProxy` 同时保留 AIDL/HIDL 分支。没有 Android 运行日志,因此不宣称每次启动必然走哪一个框架兼容分支。 + +**对 OpenWrt 的含义:** 数据库选择机制和 AT 参数映射值得移植,Android 的电话服务、Binder、RIL 进程不应因此一起启动;否则会和现有 AT 管理器争用通道、混淆拨号所有权。 + +## 4. Web 服务:APN 不只是一个名称 + +### 4.1 保存和应用是不同操作 + +证据:`ApnModule.java:35–86`;`ApnHandler.java:79–160,282–341`。 + +- `save`:插入/更新 `Telephony.Carriers.CONTENT_URI`。 +- `set_default`:把记录 ID 写入 `carriers/preferapn`。 +- `auto`:先挑选自动候选记录,再写 preferred APN,不是写一个空字符串。 +- `delete`:按记录 ID 删除。 +- 用户编辑项包括名称、APN、PDP 协议、用户名、密码、鉴权;原厂同时接受 `ipv6_*` 形式的兼容字段。 +- 保存时附上 SIM 的 MCC、MNC、numeric,类型设为 `default,supl`。 + +原厂字段名中出现 `ppp_username`、`ppp_passwd`,**不代表本机数据路径使用 PPP**;native 拨号可见的是 `M-ETHER`。 + +### 4.2 鉴权枚举 + +`ApnHandler.saveApn()` 将 none/pap/chap 转为 0/1/2,其他输入落到 -1;因此不能仅凭 Web 代码里声明了常量 3,就说这个入口完整支持 PAP/CHAP 自动协商。 + +原厂 `vendor.unisoc.hardware.radio.data.ApnAuthTypeExt` 则明确有 0/1/2/3;与 [AOSP Radio 的 ApnAuthType 定义](https://android.googlesource.com/platform/hardware/interfaces/+/340619c703511a09422ac77fe005f4465a835da7/radio/1.0/types.hal) 一致: + +| 值 | 含义 | +| --- | --- | +| 0 | 不进行 PAP/CHAP | +| 1 | PAP | +| 2 | CHAP | +| 3 | PAP 或 CHAP,由基带能力决定 | + +建议新配置采用显式枚举,不把数据库的“未指定”值 -1 原样当成 AT 鉴权参数。具体归一化策略需要结合用户名是否为空及兼容测试确定。 + +### 4.3 原厂自动选择的局限 + +`ApnHandler.getAutoConfigApnId():362` 查询 `SIM_APN_URI`,附加条件为: + +```sql +user_visible = 1 AND user_editable = 0 +AND type != 'ims' AND type != 'mms' +``` + +然后取第一条。这依赖 Provider 先筛选运营商;Web 层本身不是一个完整 APN 排序器。 + +`type != 'ims'` 是完整字符串比较,不能等价理解为严格的 APN 类型集合过滤。移植应明确识别 `default`/`*` 等业务类型,避免把 IMS、MMS、测试或专用承载误当上网 APN。 + +## 5. 配置来源与自动匹配 + +### 5.1 两份 XML 不能混为一份 + +实数统计(XML 记录数,包括非上网 APN): + +| 解包文件 | 总数 | IP | IPV4V6 | IPV6 | +| --- | ---: | ---: | ---: | ---: | +| `system_a/system/etc/apns-conf.xml` | 1583 | 540 | 1037 | 6 | +| `product_a/etc/apns-conf.xml` | 3193 | 355 | 2775 | 63 | + +Provider `DatabaseHelper.getApnConfFile():474–477` 的外部配置选择路径是: + +```text +/system/etc/apns-conf.xml + 被存在的 /oem/telephony/apns-conf.xml 覆盖 + 再被存在的 /data/misc/apns/apns-conf.xml 覆盖 +``` + +**该方法没有直接选择 `/product/etc/apns-conf.xml`。** 完整初始化还有 APK 资源和数据库处理,部分方法反编译不完整;未读取运行中的 Android 数据库,不能断言任一 XML 就等于用户最终使用的所有记录。 + +`system` 库里实际包含 cmiot、联通不同地域的 `unim2m.*`、测试 APN 等;与 `product` 库的候选并不一致。只按运营商品牌硬编码一个 APN,不能覆盖物联卡/专网。 + +### 5.2 Provider 不是只看 MCC/MNC + +证据:Provider `getSubscriptionMatchingAPNList()`,约 `2034–2149`;`getMvnoTypeIntFromString():2588`。 + +- 先检查订阅有效性,并按 subId 创建 TelephonyManager。 +- 读取 SIM 的 numeric 和 SIM-specific carrier ID。 +- 处理 MVNO match 类型/数据,通过 `matchesCurrentSimOperator()` 判断。 +- 优先使用匹配的 MVNO 候选,否则使用 MNO 候选;还处理 carrier ID 候选。 +- 过滤已删除等状态的数据库记录。 + +样本含 Telstra/CMI 特例分支,但开关来自 `Feature.getBoolean()`;**仅发现分支不证明 F50 当前启用了该特例**,不应直接迁移品牌特判。 + +建议 OpenWrt:SIM 身份明确时离线匹配候选;人工选择最高优先级。多条专网候选无法仅凭 numeric 判定时,让用户选择,不靠反复拨号“试遍 APN”。导入厂商整库前应确认分发许可、过滤测试/非上网条目,或维护有明确来源的精简规则库。 + +## 6. 双卡与持久化 + +证据:`SimCardApnRecordsDBHelper.java:33`、`SimCardApnRecordsContract.java:157–184,224–235`、`ApnAutoConfigJobService.java`、`SimStateChangedReceiver.java`。 + +- 原厂单独建 `ApnRecord` 表,以 ICCID 查询历史,存 auto/manual 和 APN 记录 ID。 +- 收到 SIM 状态事件后排入后台任务,SIM 状态满足条件才恢复选择。 +- 有有效手动历史则恢复相应 ID;没有记录或记录为 auto 则走自动选择。 +- 后台任务的调度窗口是 500–1000 ms,这不是 AT 重试/注册超时,不应直接翻译成 OpenWrt 的固定 `sleep`。 + +**不可直接照抄的部分:** 写历史时使用 `getDefaultSubscriptionId()`;部分 URI 不显式带 subId;状态接收器有“只剩一个槽位”的处理。可借鉴按卡记忆,但不能因此认定这套 Web 服务已满足我们的双卡要求。 + +建议绑定 ICCID 身份键并明确 slot/data-SIM: + +- profile 是可复用模板;每张 SIM 单独保存 auto/manual 和所选 profile ID。 +- 插入新卡不自动继承同槽位上一张卡的专网 APN。 +- 切上网卡时,先解析该卡配置,再交给同一次拨号事务;不能先按旧 APN 拨上,再后台改 APN。 +- 查看另一张 SIM 不改变正在拨号的 APN。 +- ICCID 不完整时保留“身份未确认”,不要把短前缀当成可靠身份;展示脱敏,不向普通日志输出完整卡号。 + +## 7. Native RIL:已闭合的 AT 路径 + +### 7.1 初始附着 APN + +`librilcore.so` 的 `RadioData::setInitialAttachApn()`:`0x64e80–0x650a4`。在 `0x64ec8/0x65030` 写请求号 111 (`0x6f`);可见复制 APN、protocol、roamingProtocol、auth、user、password 至原生结构。 + +`libimpl-ril.so` 的 `processDataRequest()`:`0x52ee0–0x53adc`。跳转表解码:请求 111 → `0x52f6c`。关键参数装载位于 `0x52fa0–0x52fdc`,格式串在 `0x15b5b`: + +```text +AT+SPCGAPNCFG=1,"","","",0,"","", +``` + +APN 为空/空指针时,`0x53824–0x53840` 组装: + +```text +AT+SPCGAPNCFG=1,"" +``` + +支持的 APN 类型位会先检查,不满足时打印 `SetInitialAttachAPN RIL_APN_TYPE_DEFAULT or RIL_APN_TYPE_IA error!`。 + +需要注意: + +- 首参数常量 1 的**命令级含义/配置槽**尚无完整厂商规格确认,不把它当作已证实的业务 CID。 +- `at_send_command` 的 socket 参数来自当前请求的 SIM/socket 上下文,并不是由上面那个 1 选择 SIM。 +- `0x539d0–0x539fc` 发送后没有依据返回值判断成功,直接走成功回调。移植不能继承这种假成功行为。 +- 未在这条已核对分支中发现“必须先关闭射频”的命令;也不能反向推断任意在线修改都不会影响驻网。 + +### 7.2 普通数据拨号与鉴权 + +`librilcore.so` 的 `RadioData::setupDataCall()` 从 `0x650b0` 开始,请求号 27 (`0x1b`)。libimpl-ril 跳转表将 27 分到 `0x53040`,其中一条普通数据路径经 `0x53714` 调用 `sub_53c00`。 + +可核对的普通 PDP 配置分支: + +```text +sub_53c00 + → sub_5cb40:组装/处理 CGDCONT,检查结果 + → sub_5cde0:先写 CGPCO 鉴权 + → CGDATA="M-ETHER",,继续检查数据连接结果 +``` + +`sub_5cb40` 的 `0x5cbc8` 引用格式串 `0x12761`: + +```text +AT+CGDCONT=,"","","",0,0,0,0,1 +``` + +`sub_5cde0` 的 `0x5ce24–0x5cea0`,格式串地址 `0x1827d`: + +```text +AT+CGPCO=0,"","",, +``` + +参数证据:用户名/密码从配置结构 `+0x20/+0x28` 加载到 x4/x5,auth 从 `+0x18` 加载到 w7,动态 CID 放 w6。随后 `0x5cf44–0x5cf74` 组装并发送 `CGDATA`。这里的前三个零/枚举等含义不能通过其他厂商 AT 手册套用。 + +该分支发送 `CGPCO` 时没有接收响应结构,也没有立刻检查返回值。我们应做有界响应检查和错误分类,但不应因此添加大段固定等待或循环重启基带。 + +本轮确认的是上述**可达分支**,不是“所有网络类型只有这一种序列”。样本另有切片、IMS、双 PDP 兼容分支,不能为图省事全盘复制。 + +### 7.3 IMS 配置不要混进上网 APN + +`processDataRequest` 请求 128(setDataProfile)入口在 `0x53108`;其中 IMS 分支在 `0x53870` 打印 `requestSetDataProfile found ims apn!`,随后用 CID **11** 配置 CGDCONT,并写 CGPCO。 + +这不表示上网 APN 应改用 CID 11。当前 OpenWrt `mobile-data` 的数据 CID 为 1;迁移 APN 管理时必须保留业务分工,避免覆盖 IMS/SMS 使用的上下文。 + +### 7.4 长度与凭据安全 + +上述若干 RIL 命令构造点使用 `0x80`(128 字节)输出缓冲区。它证明 Android 这几处实现存在缓冲长度约束,**不证明基带统一只接受 128 字节 AT**。 + +新实现需要限制完整编码后命令长度、拒绝不支持的引号/换行等注入字符、验证转义规则;不能只各自限制 APN 和密码长度后任由组合超长。APN 密码应使用受限配置文件权限,读取 API 默认掩码/只返回 has-password;日志禁止明文凭据,避免原厂 Web `ContentValues` 调试打印的做法。 + +## 8. Android 电话框架提供的额外语义 + +证据:`DataProfileManager.java:152–222,362–406`;`RILUtils.java:1177–1225`;`RadioDataProxy.java:201–255`。 + +- preferred profile、initial attach profile、所有 data profiles 是不同概念。 +- initial attach 按允许的 APN 类型筛选,preferred 影响优先级;没有变化时避免重复设置。 +- profile 保留 protocol 和 roamingProtocol,另外有 auth/user/password、APN 类型位图、MTU v4/v6 等字段。 +- `RILUtils` 对数据连接结果另外解析地址、DNS、网关、MTU、失败原因和建议重试时间;保存 APN 配置并不能保证这些结果已经有效。 + +当前框架同时包含旧 DcTracker 与新 DataProfileManager 实现;本轮不把“类存在”写成“本机一定启用新数据栈”。这里只提取两类配置职责与已找到的传参证据。 + +## 9. 与当前 OpenWrt 实现的差距 + +对照位置: + +- `openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/apn.uc` +- `openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/apn` +- `openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/apn.js` +- `openwrt/overlay/lib/netifd/proto/mu300cell.sh` +- `rootfs/overlay/opt/mu300/bin/mobile-data`,特别是 `configure_pdp_context()` 与 `up_locked()`。 + +| 项目 | 当前实现 | 建议 | +| --- | --- | --- | +| 列表管理 | 名称/APN/IP 协议,保存与应用分离 | 保留现有交互、主题、多语言 | +| 自动模式 | 空 APN,显示 SIM 默认 | 区分“网络默认(空 APN)”与“自动匹配配置库” | +| 鉴权 | 未向拨号层传递 | 增加 none/PAP/CHAP/PAP-or-CHAP、用户名/密码,映射 CGPCO | +| 初始附着 | 本插件没有 SPCGAPNCFG 集成 | 作为明确能力接入拨号生命周期,先验证在线和开机行为 | +| 分卡选择 | 一个 WAN 配置,跟随当前上网卡 | profile + 按 ICCID 的选择记录,显式 slot | +| 漫游协议 | 未独立设置 | 默认继承主协议,可选单独配置;不要与“允许漫游”混为一项 | +| IPv6-only | 页面拒绝,拨号脚本仍要求 IPv4 | 不能只放开下拉框;先补 IPv6-only 地址/路由/DNS成功条件 | +| 当前状态 | UCI 值匹配表示 current | 区分已选配置、AT 配置成功、PDP 状态及失败原因 | +| 超时与恢复 | 保存后让 netifd 应用 | 后台事务有界执行,保存失败/AT 拒绝/注册失败分开报告 | + +`up_locked()` 当前顺序为:radio_on → 选择数据卡 → 等注册 → configure_pdp_context → CGACT → 取地址 → CGDATA。**没有由本 APN 插件设置初始附着参数。** 对要求专用附着 APN 的网络,这可能是兼容性缺口;但需要实测,不能据此断言此前二十多秒空隙就是它导致。 + +目前“current”表示持久化配置匹配,不是 modem 的实时 APN 回读。页面无需为此持续轮询 AT:后台拨号阶段可发布状态快照/事件,显示时读本地结构化状态即可。 + +## 10. 建议实施顺序 + +### 第一批:鉴权与结果语义 + +1. 扩展 profile、RPC、netifd 和 mobile-data 的参数链,所有层一致支持凭据。 +2. 在正确 SIM 的同一次 PDP 配置事务中下发 CGDCONT + CGPCO,再开始业务连接;这是有依赖的数据配置,不能为“异步”把鉴权放到拨号之后。 +3. UI 保存仍不拨号;应用动作后台运行,及时返回任务 ID,不占住网页请求等待网络。 +4. 应用 none 时处理旧凭据残留,拒绝凭据未成功下发却提示已联网。安全默认值及旧配置迁移需写回归测试。 +5. 两个相同 APN/协议但鉴权不同的配置可能合法,现有去重键要同步调整。 + +### 第二批:按卡选择与自动匹配 + +1. profile 与 SIM 选择记录分离,保留现有全局配置的兼容迁移规则。 +2. 自动匹配以 SIM 归属运营商标识为基础,不拿漫游时 COPS 的访问网替代。 +3. 加入已验证的 MVNO 规则;不完整的识别信息不能强行匹配。 +4. 切卡与 APN 应用共用互斥机制,捕获任务开始时的卡身份,写入前再次检查;网络注册失败不妨碍用户选择卡/保存配置。 + +### 第三批:初始附着和漫游配置 + +1. 调制解调器已就绪、SIM 身份明确后尽早处理,绝不放到 initramfs 阶段。 +2. 验证 SPCGAPNCFG 的回读方式、在线更新影响及是否涉及持久化;未确认前不要宣称它是安全无扰动操作。 +3. 不靠延长启动等待解决时序问题,不引入无限重试或注册失败就反复 SFUN 重启。 +4. 不破坏现有异步 CEUS/CEMODE 数据优先设置和有限重试;它们与 APN 凭据的依赖关系不同。 +5. 纯 IPv6、MTU、运营商 DNS作为后续完整链路适配,不只新增表单字段。 + +插件继续通过平台适配层调用能力;Unisoc/F50 专用 AT 放在后端适配器中,LuCI 不硬编码 CID、AT 通道或 Android 服务。 + +## 11. 后续验证清单(本轮未执行) + +### 2026-10-12 移植进度 + +已在独立插件与 MU300 平台适配层实现:none/PAP/CHAP/自动鉴权、用户名及写入式密码、按 ICCID 保存手动/自动选择、国内公网运营商小型规则表、可选的初始附着 APN。未知运营商或 IMSI 暂不可读时使用 SIM 默认;专网/物联卡保留手动覆盖。不导入 Android 的 IMS/MMS 数据库,不改 IMS CID 11。 + +普通拨号接入 CGPCO,初始附着默认关闭;均检查精确 OK,不增加固定启动等待。页面只读 UCI/运行状态,没有周期 AT 查询。构建清单已加入身份读取适配器,6.x/7.x 与其他安装方式使用同一套源文件。 + +已通过真实 ARM64 ucode/libuci 的 62 项核心断言、三语言浏览器回归和 POSIX 环境全套 427 项测试(6 项跳过);覆盖凭据脱敏、保留/清除、非法输入、按卡绑定与重启持久化。拨号命令顺序使用隔离 AT 桩验证,不能代替带 PAP/CHAP 鉴权的实际运营商测试。WSL BusyBox 的直接全套运行不能正确使用部分测试桩(如 id),不计为已通过。 + +实机管理连接恢复后,已通过 `work/deploy-apn-ril.ps1` 热部署到 MU300LINUX-324950664950(Linux 7.2.8),备份为 `/etc/mu300/backup/apn-ril-OalpOb`,本地备份为 `work/apn-ril-before.tgz`。八个部署文件逐项 SHA-256 校验通过,network/wireless/unisoc_modem/unisoc_apn 四份配置内容保持原样;未重启网络、设备或切卡。真实 RPC 返回 connected=true,SIM 身份适配器实际读取成功,认证后的 APN 页面与移动端布局通过浏览器验证。没有操作实际 APN 切换或 PAP/CHAP 运营商鉴权,不能将这些项目视为实测通过。 + +- 正常公网卡:空 APN、手动 APN、切回空 APN,检查旧 APN/凭据是否残留。 +- 有鉴权的测试卡:none/PAP/CHAP/自动、正确与错误密码;应区分模组接受配置和运营商接受鉴权。 +- 同 APN 不同账户、边界长度、引号/换行等非法输入;密码不出现在日志/RPC列表/命令错误回显中。 +- 开机默认卡、SIM1→SIM2→SIM1、换一张卡、欠费卡;分别检查模板、按卡历史和实际拨号参数。 +- APN 任务中途切卡或重复点击;失败可解释、不互相覆盖、不持续空转。 +- 漫游协议、初始附着设置前后行为,以及 IPv4/双栈/纯 IPv6 的成功判据。 +- 保留上网 CID 与 IMS CID,验证短信/转发无回归;不因 APN 更新重启 USB/Wi-Fi。 +- 复测启动时间、AT 消费量和 CPU;无延长固定等待、无页面 AT 洪泛。 + +只有完成对应卡与网络的实测,才能把“静态可支持”升级成“本环境已支持”。当前网络可用的 SIM 并不能代替 PAP/CHAP 或专网卡验证。 + +## 12. 复现入口 + +### 实机 APN 验证补充 + +2026-10-12 在目标 F50(324950664950 / Linux 7.2.8)使用真实 RPC 执行保存、编辑、密码保留与清除、删除、非法输入拦截和当前配置删除保护。随后实测联通 `3gnet` 的全局 IPv4、按 SIM 绑定的 IPv4/IPv6、联通自动匹配及恢复原 SIM-default 配置;各次拨号约 3.7–5.4 秒后通过上下文回读和出站 ping,双栈场景 IPv4/IPv6 均通。测试备份 `/etc/mu300/backup/apn-live-test.pmBOcb`;network/unisoc_apn/wireless/unisoc_modem 四份配置 SHA-256 与测试前一致,无残留测试 profile/selection。 + +测试发现并修正两项:热部署后旧 netifd 参数表会忽略新鉴权选项,平台拨号改为读取保存的全局 APN 参数(无绑定时不查询 SIM);netifd 成功的 ubus 调用可能没有回复体,改按 ubus 错误码判断,避免错误显示“应用失败”。两项均同步仓库并热部署。 + +仍未验证:真实要求 PAP/CHAP 的运营商账号、初始附着高级开关及漫游网络行为、断电重启后的自动选取。当前公网卡能拨号,不证明这些场景都已通过。代理/IMS 编辑仍不在现有页面的支持范围内。 + +Windows 使用 pwsh。示例只读取本地样本并输出反编译产物,不操作设备: + +```powershell +$fw = 'D:/随身WiFi/F50相关/F50_B15研究/f50_b09' +$jadx = 'work/tools/jadx-1.5.5/lib/jadx-1.5.5-all.jar' +java -cp $jadx jadx.cli.JadxCLI --config none --disable-plugins jadx-ai-mcp ` + --no-res --single-class com.zte.web.module.apn.ApnHandler ` + --single-class-output work/apn-android-research/ApnHandler.java ` + "$fw/system_a/system/priv-app/ZteWebServer/ZteWebServer.apk" +java -cp $jadx jadx.cli.JadxCLI --config none --disable-plugins jadx-ai-mcp ` + --no-res -j 2 -d work/apn-android-research/provider ` + "$fw/system_a/system/priv-app/TelephonyProvider/TelephonyProvider.apk" +``` + +WSL 的 `aarch64-linux-gnu-objdump -d --start-address=0x52ee0 --stop-address=0x53adc ` 可核对请求分发;区间 `0x5cb40–0x5d180` 可核对普通 PDP/鉴权顺序;librilcore 的 `0x64e80–0x6541c` 可核对 AIDL 附着/拨号参数传递。 + +地址仅对上述 SHA-256 的样本有效。换固件后必须重新定位,不能把这些偏移直接当作运行时补丁地址。 diff --git a/openwrt/block-mount.Dockerfile b/openwrt/block-mount.Dockerfile new file mode 100644 index 00000000..29ab0a2d --- /dev/null +++ b/openwrt/block-mount.Dockerfile @@ -0,0 +1,5 @@ +FROM ubuntu:22.04 +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + build-essential ca-certificates curl file gawk git gettext libncurses-dev \ + libssl-dev patch python3 python3-setuptools rsync unzip wget zstd \ + && rm -rf /var/lib/apt/lists/* diff --git a/openwrt/block-probe-guard.h b/openwrt/block-probe-guard.h new file mode 100644 index 00000000..fa65829f --- /dev/null +++ b/openwrt/block-probe-guard.h @@ -0,0 +1,35 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later + * /dev/sd* on Unisoc also contains sdiag/sdiom/sd* communication channels. + * Reject them BEFORE probe_path() opens/reads anything. Keep ordinary disk + * nodes, regular files (swapfiles), and kernel-confirmed UBI character nodes. + */ +#include +#include +#include +#include +#include +#include + +static bool mu300_probe_allowed(const char *path) +{ + struct stat st; + char sysfs[96], subsystem[256]; + ssize_t len; + const char *name; + + if (stat(path, &st)) + return false; + if (S_ISBLK(st.st_mode) || S_ISREG(st.st_mode)) + return true; + if (!S_ISCHR(st.st_mode)) + return false; + + snprintf(sysfs, sizeof(sysfs), "/sys/dev/char/%u:%u/subsystem", + major(st.st_rdev), minor(st.st_rdev)); + len = readlink(sysfs, subsystem, sizeof(subsystem) - 1); + if (len <= 0 || len >= (ssize_t)sizeof(subsystem) - 1) + return false; + subsystem[len] = '\0'; + name = strrchr(subsystem, '/'); + return name && !strcmp(name + 1, "ubi"); +} diff --git a/openwrt/build-block-mount-inner.sh b/openwrt/build-block-mount-inner.sh new file mode 100644 index 00000000..57b2f0a4 --- /dev/null +++ b/openwrt/build-block-mount-inner.sh @@ -0,0 +1,48 @@ +#!/bin/sh +set -eu +sdk=openwrt-sdk-25.12.5-armsr-armv8_gcc-14.3.0_musl.Linux-x86_64 +sdk_sha=1b0316604a3e820b2b008a1baff3f9dac6716af942bef800930e58c7de98c98b +cd /cache +# Serialize the shared SDK when 6.x/7.x rootfs builds run in parallel. +exec 9>/cache/build.lock +flock 9 +if [ ! -d "$sdk" ]; then + if [ ! -s sdk.tar.zst ]; then + curl -fL --retry 3 -o sdk.tar.zst.part "https://downloads.openwrt.org/releases/25.12.5/targets/armsr/armv8/$sdk.tar.zst" + echo "$sdk_sha sdk.tar.zst.part" | sha256sum -c - + mv sdk.tar.zst.part sdk.tar.zst + fi + echo "$sdk_sha sdk.tar.zst" | sha256sum -c - + tar --zstd -xf sdk.tar.zst +fi +cd "$sdk" +export FORCE_UNSAFE_CONFIGURE=1 +if [ ! -f package/feeds/base/fstools/Makefile ]; then + ./scripts/feeds update base + ./scripts/feeds install -p base fstools +fi +# This APK is intentionally tied to the same fstools revision as 25.12.5. +# Fail on a changed feed instead of producing an unreviewed probe binary. +grep -q 'PKG_SOURCE_VERSION:=16718b6e3c0fc7db7be6ae5848db0eae88ac8a8b' package/feeds/base/fstools/Makefile +sed -i 's/^PKG_RELEASE:=.*/PKG_RELEASE:=100/' package/feeds/base/fstools/Makefile +mkdir -p package/feeds/base/fstools/patches +cp /src/patches/fstools-probe-device-types.patch package/feeds/base/fstools/patches/900-mu300-probe-device-types.patch +# Add the tested guard as a source patch too; OpenWrt applies both before CMake. +{ + printf '%s\n' '--- /dev/null' '+++ b/block-probe-guard.h' + printf '@@ -0,0 +1,%s @@\n' "$(wc -l < /src/block-probe-guard.h)" + sed 's/^/+/' /src/block-probe-guard.h +} > package/feeds/base/fstools/patches/901-mu300-probe-guard-header.patch +printf '%s\n' 'CONFIG_ALL_NONSHARED=n' 'CONFIG_ALL_KMODS=n' 'CONFIG_ALL=n' \ + 'CONFIG_BUILDBOT=n' 'CONFIG_PACKAGE_block-mount=m' 'CONFIG_SIGNED_PACKAGES=n' > .config +make defconfig +make package/fstools/clean +make -j4 package/fstools/compile V=s +apk=$(find bin -name 'block-mount-*-r100.apk' -type f) +[ -n "$apk" ] && [ "$(printf '%s\n' "$apk" | wc -l)" = 1 ] || { + echo 'expected exactly one patched block-mount APK' >&2; exit 1; +} +cp "$apk" "/out/$OUT_NAME.part" +mv "/out/$OUT_NAME.part" "/out/$OUT_NAME" +sha256sum "/out/$OUT_NAME" | cut -d' ' -f1 > "/out/$OUT_NAME.sha256" +printf '%s\n' "$BUILD_ID" > "/out/$OUT_NAME.build-id" diff --git a/openwrt/build-block-mount.sh b/openwrt/build-block-mount.sh new file mode 100644 index 00000000..4af2bb7d --- /dev/null +++ b/openwrt/build-block-mount.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# Build a patched OpenWrt APK, not an LD_PRELOAD workaround or UI-only filter. +# The SDK cache is separate from the kernel build. No kernel rebuild is needed. +set -eu +TOP=$(cd "$(dirname "$0")/.." && pwd) +OUT=${1:-$TOP/work/block-mount-mu300.apk} +mkdir -p "$(dirname "$OUT")" +OUT=$(cd "$(dirname "$OUT")" && pwd)/$(basename "$OUT") +stamp=$(cat "$TOP/openwrt/block-mount.Dockerfile" "$TOP/openwrt/build-block-mount.sh" \ + "$TOP/openwrt/build-block-mount-inner.sh" "$TOP/openwrt/block-probe-guard.h" \ + "$TOP/openwrt/patches/fstools-probe-device-types.patch" | sha256sum | cut -d' ' -f1) +if [ -s "$OUT" ] && [ -s "$OUT.build-id" ] && [ -s "$OUT.sha256" ] && + [ "$(cat "$OUT.build-id")" = "$stamp" ] && + [ "$(sha256sum "$OUT" | cut -d' ' -f1)" = "$(cat "$OUT.sha256")" ]; then + echo "block-mount: verified patched APK cache" + exit 0 +fi +docker build --platform linux/amd64 -t mu300-block-sdk-build -f "$TOP/openwrt/block-mount.Dockerfile" "$TOP/openwrt" +# A named volume keeps SDK builds off slow Windows bind mounts. An explicit +# cache directory can also be supplied by Linux/WSL developers. +cache=${MU300_BLOCK_SDK_CACHE:-mu300-block-sdk-25.12.5} +docker run --rm --platform linux/amd64 -v "$cache:/cache" -v "$TOP/openwrt:/src:ro" \ + -v "$(dirname "$OUT"):/out" -e "OUT_NAME=$(basename "$OUT")" -e "BUILD_ID=$stamp" \ + mu300-block-sdk-build sh /src/build-block-mount-inner.sh diff --git a/openwrt/build-rootfs.sh b/openwrt/build-rootfs.sh index e32c6d46..a336e861 100755 --- a/openwrt/build-rootfs.sh +++ b/openwrt/build-rootfs.sh @@ -82,6 +82,11 @@ done < "$TOP/openwrt/aurora-config-packages.sha256" TARBALL=$FLAVOUR-$VER-armsr-armv8-rootfs.tar.gz URL=$BASEURL/$VER/targets/armsr/armv8 +# Stock block-mount probes /dev/sd* (including Unisoc diagnostic channels). +# Build/install the patched APK before exposing LuCI's Mount Points page. +BLOCK_APK=$TOP/work/block-mount-mu300.apk +sh "$TOP/openwrt/build-block-mount.sh" "$BLOCK_APK" + cd "$TOP" if [ ! -f "openwrt/$TARBALL" ]; then curl -fL -o "openwrt/$TARBALL" "$URL/$TARBALL" @@ -122,6 +127,8 @@ docker run --rm --platform linux/arm64 \ $(opt busybox busybox) $(opt sing-box sing-box) $(opt xray xray) $(opt hev-socks5-tunnel hev-socks5-tunnel) $(mainline_opt modules mainline-modules) $(plugin_opt) -v "$TOP/openwrt":/out -v "$REGDB":/in/regdb:ro \ $(mainline_opt modules.builtin mainline-modules.builtin) $(mainline_opt modules.builtin.modinfo mainline-modules.builtin.modinfo) \ -v "$THEME_APK":/in/luci-theme-aurora.apk:ro \ + -v "$BLOCK_APK":/in/block-mount-mu300.apk:ro \ + -v "$BLOCK_APK.build-id":/in/block-mount.build-id:ro \ -v "$TOP/work/luci-app-aurora-config-1.2.5-r20260920.apk":/in/luci-app-aurora-config.apk:ro \ -v "$TOP/work/luci-i18n-aurora-config-zh-cn-26.262.58276.362887a.apk":/in/aurora-config-zh-cn.apk:ro \ -v "$TOP/work/luci-i18n-aurora-config-tr-26.262.58276.362887a.apk":/in/aurora-config-tr.apk:ro \ @@ -132,6 +139,7 @@ apk update >/dev/null # i2c-tools, gpiod-tools: mu300-usb (the charger of the U30 Air) and mu300-nfc (its NFC tag) apk add wpad-basic-mbedtls wifi-scripts iwinfo wireless-regdb iw bash ip-full coreutils-stty openssl-util curl ca-bundle msmtp ucode ucode-mod-fs ucode-mod-ubus ucode-mod-uci ucode-mod-uloop ucode-mod-socket \ i2c-tools gpiod-tools >/dev/null +apk add --allow-untrusted /in/block-mount-mu300.apk >/dev/null apk add --allow-untrusted /in/luci-theme-aurora.apk >/dev/null apk add --allow-untrusted /in/luci-app-aurora-config.apk /in/aurora-config-zh-cn.apk /in/aurora-config-tr.apk >/dev/null # ujail drops CAP_PERFMON (38), which this 5.4 kernel does not know: jailed services (dnsmasq, ntpd) crash-loop @@ -154,6 +162,10 @@ printf "127.0.0.1\tlocalhost\n\n::1\tlocalhost ip6-localhost ip6-loopback\nff02: printf "mu300\n" > $R/etc/hostname # the real one comes from uci (etc/uci-defaults/90-mu300) cp -a /in/opt-mu300 $R/opt/mu300 cp -a /in/overlay/. $R/ +cp /in/block-mount.build-id $R/etc/mu300/block-mount.build-id +for f in sbin/block lib/libblkid-tiny.so etc/init.d/fstab; do + [ -s "$R/$f" ] || { echo "patched block-mount required file missing: $f" >&2; exit 1; } +done chmod 0755 $R/opt/mu300/bin/cpu-voltage-platform $R/etc/init.d/mu300-cpu-driver chmod 0755 $R/opt/mu300/bin/ra-deprecate $R/opt/mu300/bin/wcn-reopen chmod 0755 $R/opt/mu300/bin/mu300-user-packages $R/etc/init.d/mu300-user-packages @@ -178,6 +190,7 @@ if [ -d /in/luci-plugin ]; then cp -a /in/luci-plugin/root/. $R/ cp -a /in/luci-plugin/htdocs/. $R/www/ chmod 0755 $R/etc/init.d/unisoc-cpu + chmod 0600 $R/etc/config/unisoc_apn chmod 0755 $R/etc/init.d/unisoc-modem-ui $R/etc/init.d/unisoc-sms-forward $R/etc/init.d/unisoc-traffic $R/etc/hotplug.d/net/90-unisoc-usb-host $R/etc/hotplug.d/iface/90-unisoc-usb-host $R/usr/libexec/rpcd/mu300dash $R/usr/libexec/unisoc-modem/* mkdir -p $R/usr/lib/lua/luci/i18n cp -a /in/luci-plugin/lmo/. $R/usr/lib/lua/luci/i18n/ diff --git a/openwrt/luci-app-mu300/Makefile b/openwrt/luci-app-mu300/Makefile index 9c6df0c0..11d7a385 100644 --- a/openwrt/luci-app-mu300/Makefile +++ b/openwrt/luci-app-mu300/Makefile @@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk PKG_NAME:=luci-app-mu300 PKG_VERSION:=1.2.0 -PKG_RELEASE:=11 +PKG_RELEASE:=13 PKG_LICENSE:=MIT PKG_MAINTAINER:=MU300 Linux contributors PKGARCH:=all @@ -25,6 +25,7 @@ endef define Package/luci-app-mu300/conffiles /etc/config/unisoc_modem +/etc/config/unisoc_apn /etc/unisoc-modem/cpu.json /etc/unisoc-modem/cpu-voltage.json endef @@ -36,6 +37,7 @@ define Package/luci-app-mu300/install $(INSTALL_DIR) $(1)/www $(CP) ./htdocs/. $(1)/www/ $(CP) ./root/. $(1)/ + chmod 0600 $(1)/etc/config/unisoc_apn chmod 0755 $(1)/etc/init.d/unisoc-cpu chmod 0755 $(1)/etc/init.d/unisoc-modem-ui $(1)/etc/init.d/unisoc-sms-forward $(1)/etc/init.d/unisoc-traffic $(1)/etc/hotplug.d/net/90-unisoc-usb-host $(1)/etc/hotplug.d/iface/90-unisoc-usb-host $(1)/usr/libexec/rpcd/mu300dash $(1)/usr/libexec/unisoc-modem/* $(INSTALL_DIR) $(1)/usr/lib/lua/luci/i18n @@ -46,6 +48,7 @@ define Package/luci-app-mu300/postinst #!/bin/sh [ -n "$${IPKG_INSTROOT}" ] || { /usr/libexec/unisoc-modem/refresh-config + chmod 0600 /etc/config/unisoc_apn state=$$(uci -q get unisoc_modem.main.state_dir 2>/dev/null) state=$${state:-/etc/unisoc-modem/lock-state.d} old=/etc/mu300/dash/lock-state.d diff --git a/openwrt/luci-app-mu300/README.md b/openwrt/luci-app-mu300/README.md index 8656e449..db928343 100644 --- a/openwrt/luci-app-mu300/README.md +++ b/openwrt/luci-app-mu300/README.md @@ -3,6 +3,15 @@ A self-contained LuCI application for Unisoc cellular devices. It provides the dashboard, live radio readings, persistent network/band/cell/EN-DC locks, a guarded AT terminal and an SMS UI. +The Access Points (APN) page stores multiple profiles, with separate save and +confirmed apply operations. It currently supports the `mu300cell` netifd +protocol; unsupported platform protocols are explicitly read-only/unavailable. +Profiles and per-ICCID selections persist in `/etc/config/unisoc_apn`. Supports +PAP/CHAP credentials, independently maintained public-carrier auto-matching, +and optional initial attach configuration. Passwords are never returned by the +public RPC. Unbound SIMs use the existing data interface's global settings. +Applying does not switch SIM or restart USB/Wi-Fi. +See [APN and safe block-mount](../../docs/APN-AND-BLOCK-MOUNT.md) for details. The Device Management page controls USB role and gadget network policy, and lists host-side USB network adapters for optional attachment to the LAN bridge. diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js index 975e1fb1..9bab2ced 100644 --- a/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js @@ -110,6 +110,54 @@ var callUsbNetAdd = rpc.declare({ object: 'mu300dash', method: 'usb_net_add', pa * standalone package works in any OpenWrt buildroot without po2lmo or extra * language packages. Chinese remains the source/fallback language. */ var DASH_I18N = { + '切换': ['Switch', 'Geçiş yap'], + '编辑': ['Edit', 'Düzenle'], + '接入点 APN': ['Access points (APN)', 'Erişim noktaları (APN)'], + '无法读取当前 SIM 身份,请稍后重试': ['Cannot read the current SIM identity; try again later', 'Geçerli SIM kimliği okunamadı; daha sonra tekrar deneyin'], + '此接入点仍被 SIM 使用,不能删除': ['This profile is still assigned to a SIM and cannot be deleted', 'Bu profil hâlâ bir SIM’e atanmış; silinemez'], + '当前 SIM 已记住接入点,请使用按卡应用': ['This SIM has a saved profile; apply it per SIM', 'Bu SIM’in kayıtlı profili var; SIM’e özel uygulayın'], + '无鉴权': ['No authentication', 'Kimlik doğrulama yok'], + '用户名': ['Username', 'Kullanıcı adı'], + '密码': ['Password', 'Parola'], + '正在连接': ['Connecting', 'Bağlanıyor'], + '连接失败': ['Connection failed', 'Bağlantı başarısız'], + '鉴权方式': ['Authentication', 'Kimlik doğrulama'], + '留空保留原密码': ['Leave empty to keep the saved password', 'Kayıtlı parolayı korumak için boş bırakın'], + '未设置密码': ['No password set', 'Parola ayarlanmadı'], + '清除已保存密码': ['Clear saved password', 'Kayıtlı parolayı sil'], + '漫游 IP 协议': ['Roaming IP protocol', 'Dolaşım IP protokolü'], + '配置初始附着 APN(高级)': ['Configure initial attach APN (advanced)', 'İlk bağlantı APN’sini yapılandır (gelişmiş)'], + '初始附着默认关闭;仅在运营商需要时启用。不修改 IMS 配置。': ['Initial attach configuration is off by default; enable only if required by your carrier. IMS settings are not changed.', 'İlk bağlantı yapılandırması varsayılan olarak kapalıdır; yalnızca operatör gerektiriyorsa açın. IMS ayarları değiştirilmez.'], + '按当前 SIM 记住选择': ['Remember selection for this SIM', 'Seçimi bu SIM için hatırla'], + '使用全局接口配置': ['Using global interface settings', 'Genel arayüz ayarları kullanılıyor'], + '自动匹配当前 SIM': ['Auto-match current SIM', 'Geçerli SIM’i otomatik eşleştir'], + '按运营商匹配公网 APN;未知运营商使用 SIM 默认。专网或物联卡请手动设置。': ['Match a public APN by carrier; unknown carriers use the SIM default. Configure private networks and IoT SIMs manually.', 'Operatöre göre genel APN eşleştirilir; bilinmeyen operatörlerde SIM varsayılanı kullanılır. Özel ağları ve IoT SIM’leri elle yapılandırın.'], + '当前蜂窝接口不支持 APN 管理': ['The current cellular interface does not support APN management', 'Geçerli hücresel arayüz APN yönetimini desteklemiyor'], + '接入点参数无效': ['Invalid access point settings', 'Geçersiz erişim noktası ayarları'], + '接入点已不存在,请刷新': ['Access point no longer exists; refresh the list', 'Erişim noktası artık mevcut değil; listeyi yenileyin'], + '网络或 APN 配置有未应用更改,请先保存或撤销': ['Network or APN settings have pending changes; save or discard them first', 'Ağ veya APN ayarlarında bekleyen değişiklikler var; önce kaydedin veya geri alın'], + '接入点保存失败': ['Failed to save the access point', 'Erişim noktası kaydedilemedi'], + '最多保存 32 个接入点': ['You can save up to 32 access points', 'En fazla 32 erişim noktası kaydedebilirsiniz'], + '相同 APN 和协议的接入点已存在': ['An access point with this APN and protocol already exists', 'Bu APN ve protokole sahip bir erişim noktası zaten var'], + '不能删除当前接入点,请先切换': ['Switch to another access point before deleting the current one', 'Geçerli erişim noktasını silmeden önce başka birine geçin'], + '配置已保存,但应用失败,请刷新后重试': ['Settings saved, but could not be applied; refresh and try again', 'Ayarlar kaydedildi ancak uygulanamadı; yenileyip tekrar deneyin'], + '正在应用…': ['Applying…', 'Uygulanıyor…'], + '接入点已应用,正在连接;能否上网取决于 SIM 和运营商': ['APN applied; connecting. Internet access depends on your SIM and carrier', 'APN uygulandı; bağlanılıyor. İnternet erişimi SIM ve operatörünüze bağlıdır'], + '接入点已保存': ['Access point saved', 'Erişim noktası kaydedildi'], + '留空使用 SIM 默认接入点': ['Leave empty to use the SIM default APN', 'SIM varsayılan APN değerini kullanmak için boş bırakın'], + '接入点名称': ['Profile name', 'Profil adı'], + 'IP 协议': ['IP protocol', 'IP protokolü'], + '编辑接入点': ['Edit access point', 'Erişim noktasını düzenle'], + '添加接入点': ['Add access point', 'Erişim noktası ekle'], + '保存仅修改列表,点击切换后才会应用。': ['Saving only updates the list. Switch to a profile to apply it.', 'Kaydetmek yalnızca listeyi günceller. Uygulamak için profile geçin.'], + '当前配置': ['Current configuration', 'Geçerli yapılandırma'], + 'SIM 默认': ['SIM default', 'SIM varsayılanı'], + '接入点应用于当前上网接口,不切换 SIM。切换会短暂中断蜂窝网络,重启后仍保留。': ['Profiles apply to the current data interface without switching SIMs. Switching briefly interrupts cellular data and persists across reboots.', 'Profiller SIM değiştirmeden geçerli veri arayüzüne uygulanır. Geçiş hücresel veriyi kısa süreli keser ve yeniden başlatmalarda korunur.'], + '暂无接入点,请添加': ['No access points yet. Add one to get started.', 'Henüz erişim noktası yok. Başlamak için bir tane ekleyin.'], + '再次应用': ['Apply again', 'Yeniden uygula'], + '切换接入点?': ['Switch access point?', 'Erişim noktası değiştirilsin mi?'], + '将重新建立蜂窝连接,USB 和 Wi-Fi 不受影响。': ['The cellular connection will be re-established. USB and Wi-Fi are unaffected.', 'Hücresel bağlantı yeniden kurulacak. USB ve Wi-Fi etkilenmez.'], + '删除接入点?': ['Delete access point?', 'Erişim noktası silinsin mi?'], '清除全部蜂窝锁定': ['Clear all cellular locks', 'Tüm hücresel kilitleri temizle'], '清除当前 SIM 全部锁定': ['Clear all locks for the selected SIM', 'Seçili SIM için tüm kilitleri temizle'], '清除 SIM %s 的全部锁定?': ['Clear all locks for SIM %s?', 'SIM %s için tüm kilitler temizlensin mi?'], diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/apn.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/apn.js new file mode 100644 index 00000000..cf777dbe --- /dev/null +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/apn.js @@ -0,0 +1,107 @@ +'use strict'; +'require view'; +'require rpc'; +'require mu300.common as M'; + +var get=rpc.declare({object:'mu300dash',method:'apn_get',nobatch:true,expect:{'':{}}}); +var change=rpc.declare({object:'mu300dash',method:'apn_set',params:['action','payload'],nobatch:true,expect:{'':{}}}); +var errors={apn_unsupported:'当前蜂窝接口不支持 APN 管理',apn_invalid:'接入点参数无效',apn_missing:'接入点已不存在,请刷新',apn_unsaved:'网络或 APN 配置有未应用更改,请先保存或撤销',apn_storage:'接入点保存失败',apn_limit:'最多保存 32 个接入点',apn_duplicate:'相同 APN 和协议的接入点已存在',apn_current:'不能删除当前接入点,请先切换',apn_reload:'配置已保存,但应用失败,请刷新后重试',apn_busy:'另一项网络设置仍在执行,请稍后重试'}; +function el(tag,text,cls){var n=document.createElement(tag);if(text!=null)n.textContent=text;if(cls)n.className=cls;return n;} +Object.assign(errors,{apn_identity:'无法读取当前 SIM 身份,请稍后重试',apn_bound:'此接入点仍被 SIM 使用,不能删除',apn_scope:'当前 SIM 已记住接入点,请使用按卡应用'}); +function t(s){return M.translate(s);} +function proto(s){return {IP:'IPv4',IPV6:'IPv6',IPV4V6:'IPv4 / IPv6'}[s]||s;} +var CSS=` +.mud-apn .apn-panel{padding:20px;min-width:0}.mud-apn h3{margin:0;border:0;padding:0;font-size:1rem;color:var(--text)} +.mud-apn .apn-head,.mud-apn .apn-actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.mud-apn .apn-head h3{flex:1} +.mud-apn .apn-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,260px),1fr));gap:12px;margin-top:16px} +.mud-apn .apn-item{border:1px solid var(--hairline,var(--border-color,#ddd));border-radius:12px;padding:16px;min-width:0;display:flex;flex-direction:column;gap:10px} +.mud-apn .apn-item.active{border-color:var(--brand,var(--primary,#37a));background:color-mix(in srgb,var(--brand,var(--primary,#37a)) 5%,transparent)} +.mud-apn .apn-item strong,.mud-apn .apn-value{overflow-wrap:anywhere}.mud-apn .apn-actions{margin-top:auto}.mud-apn .mud-note{line-height:1.6;overflow-wrap:anywhere} +.mud-apn-editor{display:grid;gap:12px;margin-top:12px}.mud-apn-editor label{display:grid;gap:6px;min-width:0}.mud-apn-editor input,.mud-apn-editor select{width:100%;max-width:100%;box-sizing:border-box;margin:0} +.mud-apn-editor input[type=checkbox]{width:auto;justify-self:start} +.mud-apn-editor input:not([type=checkbox]),.mud-apn-editor select{min-width:0;min-height:36px;padding:7px 10px;border:1px solid var(--hairline,var(--border,#ccc));border-radius:var(--radius-base,.5rem);background:var(--surface,var(--background,#fff));color:var(--text,#222);font:inherit;line-height:1.4} +.mud-apn-editor input:not([type=checkbox]):focus,.mud-apn-editor select:focus{outline:2px solid var(--brand,var(--primary,#37a));outline-offset:1px} +.mud-dlg:has(.mud-apn-editor){max-height:calc(100dvh - 40px);overflow:auto;box-sizing:border-box} +@media(max-width:480px){.mud-apn .apn-panel{padding:14px}.mud-apn .apn-actions .mud-btn{flex:1}.mud-apn .apn-head h3{flex-basis:100%}} +`; +return view.extend({ + load:function(){return get();}, + render:function(data){ + M.injectCss();M.localizeMenu(); + this.root=el('div',null,'mud mud-apn');this.root.append(el('style',CSS)); + this.paint(data);return this.root; + }, + refresh:function(){var self=this,seq=this.readSeq=(this.readSeq||0)+1;return get().then(function(r){if(seq===self.readSeq)self.paint(r);});}, + run:function(button,action,payload){ + var self=this;if(self.busy)return Promise.resolve();self.busy=true;self.readSeq=(self.readSeq||0)+1;M.busy(button,true); + var toast=M.toast('正在应用…',{type:'busy',timeout:0}); + return change(action,JSON.stringify(payload)).then(function(r){ + if(!r.ok){ + var error=new Error(errors[r.error]||r.error||'接入点保存失败'); + if(r.saved)return self.refresh().catch(function(){}).then(function(){throw error;}); + throw error; + } + M.toast(action==='apply'||action==='auto'?'接入点已应用,正在连接;能否上网取决于 SIM 和运营商':'接入点已保存',{type:'success'}); + return self.refresh(); + }).catch(function(e){M.toast(t(errors[e.message]||e.message),{type:'error'});}) + .finally(function(){self.busy=false;toast.close();M.busy(button,false);}); + }, + edit:function(profile,button){ + var self=this;if(self.busy)return; + var form=el('form',null,'mud-apn-editor');form.onsubmit=function(e){e.preventDefault();}; + var name=el('input'),apn=el('input'),type=el('select'); + name.type='text';apn.type='text'; + name.required=true;name.maxLength=64;apn.maxLength=100;apn.pattern='[A-Za-z0-9.\\-]+'; + apn.placeholder=t('留空使用 SIM 默认接入点');name.value=profile?profile.name:'';apn.value=profile?profile.apn:''; + ['IPV4V6','IP'].forEach(function(v){var o=el('option',proto(v));o.value=v;type.append(o);});type.value=profile?profile.pdptype:'IPV4V6'; + [['接入点名称',name],['APN',apn],['IP 协议',type]].forEach(function(row){var label=el('label',t(row[0]));label.append(row[1]);form.append(label);}); + var auth=el('select'),user=el('input'),password=el('input'),roaming=el('select'),attach=el('input'),clear=el('input'); + user.type='text';user.autocomplete='off';user.spellcheck=false; + [['none','无鉴权'],['pap','PAP'],['chap','CHAP'],['papchap','PAP / CHAP']].forEach(function(v){var o=el('option',t(v[1]));o.value=v[0];auth.append(o);}); + auth.value=profile&&profile.auth||'none';user.value=profile&&profile.username||'';user.maxLength=64; + password.type='password';password.maxLength=64;password.autocomplete='new-password'; + password.placeholder=t(profile&&profile.has_password?'留空保留原密码':'未设置密码');clear.type='checkbox';attach.type='checkbox';attach.checked=!!(profile&&profile.attach==='1'); + [['IPV4V6','IPv4 / IPv6'],['IP','IPv4']].forEach(function(v){var o=el('option',v[1]);o.value=v[0];roaming.append(o);});roaming.value=profile&&profile.roaming||type.value; + [['鉴权方式',auth],['用户名',user],['密码',password],['清除已保存密码',clear],['漫游 IP 协议',roaming],['配置初始附着 APN(高级)',attach]].forEach(function(row){var label=el('label',t(row[0]));label.append(row[1]);form.append(label);}); + form.append(el('p',t('初始附着默认关闭;仅在运营商需要时启用。不修改 IMS 配置。'),'mud-note')); + function ask(){ + return M.confirmBox(profile?'编辑接入点':'添加接入点','保存仅修改列表,点击切换后才会应用。',{content:form,okText:'保存'}).then(function(yes){ + if(!yes)return; + if(!form.checkValidity() || !name.value.trim()) {M.toast('接入点参数无效',{type:'error'});return ask();} + var p={id:profile?profile.id:'',name:name.value.trim(),apn:apn.value.trim(),pdptype:type.value,auth:auth.value,username:user.value,roaming:roaming.value,attach:attach.checked?'1':'0'}; + if(clear.checked||password.value||!(profile&&profile.has_password))p.password=clear.checked?'':password.value; + return self.run(button,'save',p); + }); + } + return ask(); + }, + paint:function(data){ + var self=this;this.data=data;var old=this.root.querySelector('section');if(old)old.remove(); + var panel=el('section',null,'mud-card apn-panel'),head=el('div',null,'apn-head');this.root.append(panel);panel.append(head); + head.append(el('h3',t('接入点 APN'))); + var refresh=el('button',t('刷新'),'mud-btn'),add=el('button',t('添加接入点'),'mud-btn');head.append(refresh,add); + refresh.onclick=function(){if(self.busy)return;M.busy(refresh,true);self.refresh().catch(function(){M.toast('读取失败,稍后重试',{type:'error'});}).finally(function(){M.busy(refresh,false);});}; + add.onclick=function(){self.edit(null,add);};add.disabled=!data.ok; + if(!data.ok){panel.append(el('p',t(errors[data.error]||'读取失败,稍后重试'),'mud-note'));return;} + panel.append(el('p',t('当前配置')+':'+(data.current.apn||t('SIM 默认'))+' · '+proto(data.current.pdptype)+' · SIM '+(data.data_sim+1),'mud-note')); + var phase=data.connecting?'正在连接':data.connected?'已连接':data.dial&&data.dial.phase==='failed'?'连接失败':'未连接'; + panel.append(el('p',t(phase)+' · '+t(data.remembered?'按当前 SIM 记住选择':'使用全局接口配置'),'mud-note')); + var auto=el('button',t('自动匹配当前 SIM'),'mud-btn');head.append(auto); + auto.onclick=function(){if(self.busy)return;M.confirmBox('自动匹配当前 SIM','按运营商匹配公网 APN;未知运营商使用 SIM 默认。专网或物联卡请手动设置。',{danger:true}).then(function(yes){if(yes)return self.run(auto,'auto',{});});}; + panel.append(el('p',t('接入点应用于当前上网接口,不切换 SIM。切换会短暂中断蜂窝网络,重启后仍保留。'),'mud-note')); + var grid=el('div',null,'apn-grid');panel.append(grid); + if(!data.profiles.length)grid.append(el('p',t('暂无接入点,请添加'),'mud-note')); + data.profiles.forEach(function(p){ + var item=el('article',null,'apn-item'+(p.current?' active':''));grid.append(item); + item.append(el('strong',p.id==='automatic'&&p.name==='SIM default'?t('SIM 默认'):p.name)); + item.append(el('span',p.apn||t('SIM 默认'),'apn-value'));item.append(el('span',proto(p.pdptype),'mud-note')); + var actions=el('div',null,'apn-actions');item.append(actions); + var apply=el('button',t(p.current?'再次应用':'切换'),'mud-btn'),edit=el('button',t('编辑'),'mud-btn'),del=el('button',t('删除'),'mud-btn warn');actions.append(apply,edit,del); + del.disabled=p.current; + edit.onclick=function(){self.edit(p,edit);}; + apply.onclick=function(){if(self.busy)return;var label=el('label'),remember=el('input');remember.type='checkbox';remember.checked=true;remember.disabled=!!data.remembered;label.append(remember,document.createTextNode(' '+t('按当前 SIM 记住选择')));M.confirmBox('切换接入点?','将重新建立蜂窝连接,USB 和 Wi-Fi 不受影响。',{content:label,danger:true}).then(function(yes){if(yes)return self.run(apply,'apply',{id:p.id,remember:remember.checked});});}; + del.onclick=function(){if(self.busy)return;M.confirmBox('删除接入点?','',{content:el('p',p.name),danger:true}).then(function(yes){if(yes)return self.run(del,'delete',{id:p.id});});}; + }); + }, + handleSaveApply:null,handleSave:null,handleReset:null +}); diff --git a/openwrt/luci-app-mu300/lmo/mu300.en.lmo b/openwrt/luci-app-mu300/lmo/mu300.en.lmo index 8214cf31704e5146aaffb877ff57fda0912b23d4..5d87412b460eafd31f938a37381bf76e856d1df9 100644 GIT binary patch delta 163 zcmX@Y^nz)Eh=^lya%yq0LP36JUP-ZnhGT%ACc{LLcEuD11_l8>j!Pv#nh}UafLNHn zK~){fFPXSTKF|lq;WXUh!T}Yu0n&VdZ`T_^`5Hi)wA^ Wr9Aiy<#$Y$VU*{L0P?tjcnJWNKOI&8 delta 126 zcmaFCbcAVw$V82H!2kvZ1_AyCRdpcE2*e2!FUSX402!QyTUw?z`!8Q$8o6yNHYSl z1PJptsH#Kx9TWG+2ZjJS+=g3RIG}{needed=true;}); + print(needed?'1\n':'0\n');exit(0); +} else if(action=='get') { + result=apn.get(c,cachedIdentity()); + try {result.dial=json(fs.readfile('/run/unisoc-apn-dial-'+slot+'.json') || '{}');}catch(e){} + let bus=connect(null,2), status=bus?.call('network.interface.'+result.iface,'status',{}); + result.connected=status?.up===true;result.connecting=status?.pending===true; +} +else { + // Share the existing SIM-switch gate: an APN transaction must not commit + // half-way through changing the data card. Boot replay uses a separate lock. + const lock='/run/unisoc-data-sim-switch'; + let acquired=fs.mkdir(lock,448); + if(!acquired) { + let pid=trim(fs.readfile(lock+'/pid') || ''); + if(match(pid,/^[1-9][0-9]*$/) && !fs.stat('/proc/'+pid)) { + fs.unlink(lock+'/pid');fs.rmdir(lock);acquired=fs.mkdir(lock,448); + } + } + if(!acquired) result={ok:0,error:'apn_busy'}; + else { + fs.writefile(lock+'/pid',''+fs.readlink('/proc/self')); + try { + let payload=fs.readfile('/dev/stdin'); + if(length(payload || '')>4096)die('request too large'); + if(fs.stat('/run/unisoc-modem-lock-apply')) + result={ok:0,error:'apn_busy'}; + else { + let p=json(payload || '{}'), identity=cachedIdentity(); + if(action=='auto' || (action=='apply' && p.remember===true)) { + let pipe=fs.popen('/usr/libexec/unisoc-modem/apn-identity '+slot,'r'); + identity=json(pipe?.read('all') || '{}');pipe?.close(); + } + result=apn.change(c,action,p,iface=>{ + let bus=connect(null,3); + fs.writefile('/run/unisoc-apn-dial-'+slot+'.json',sprintf('%J',{phase:'queued'})); + // netifd compares configurations and restarts only changed interfaces. + // Do not restart network.service, USB, Wi-Fi or change the data SIM. + // Selection lives outside network UCI. Restart this bearer + // explicitly even when its netifd configuration is unchanged. + return apn.reconnect(bus,error,iface); + },identity); + fs.chmod('/etc/config/unisoc_apn',384); + fs.chmod('/etc/config/network',384); + } + } catch(e) { result={ok:0,error:'apn_invalid'}; } + fs.unlink(lock+'/pid');fs.rmdir(lock); + } +} +print(sprintf('%J\n',result)); diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/apn-identity b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/apn-identity new file mode 100644 index 00000000..4bbbf7f9 --- /dev/null +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/apn-identity @@ -0,0 +1,12 @@ +#!/bin/sh +# Read the requested card through the plugin's configured AT adapter. +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} -ge 18 ] && [ ${#iccid} -le 22 ] || exit 1 +umask 077 +json=$(printf '{"iccid":"%s"}' "$iccid") +printf '%s\n' "$json" > "/run/unisoc-apn-sim$slot.json.new.$$" && mv "/run/unisoc-apn-sim$slot.json.new.$$" "/run/unisoc-apn-sim$slot.json" +printf '%s\n' "$json" diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/apn.uc b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/apn.uc new file mode 100644 index 00000000..06a22659 --- /dev/null +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/apn.uc @@ -0,0 +1,135 @@ +// Profiles contain no modem commands. netifd remains the owner of the bearer. +const cfg = 'unisoc_apn'; +export function reconnect(bus,last_error,iface) { + if(!bus)return false; + // Successful netifd methods may send no response body. Check the ubus + // status rather than treating a null response as a failed operation. + for(let request in [['network','reload'],['network.interface.'+iface,'down'],['network.interface.'+iface,'up']]) { + bus.call(request[0],request[1],{}); + if(last_error(true))return false; + } + return true; +}; +function fail(error) { return {ok:0,error}; } +function valid_id(id) { return type(id)=='string' && match(id,/^[A-Za-z0-9_]{1,64}$/); } +function auth(p) { return p.auth || 'none'; } +function credentials(p) { + let user=p.username || '', password=p.password || ''; + 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}$/); }; +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) { + let found=null; + if(valid_identity(identity))c.foreach(cfg,'selection',s=>{if(s.iccid==identity.iccid)found=s;}); + return found; +} +// The small rule list is independently maintained. It deliberately excludes +// IMS/MMS, IoT/private/test APNs and ambiguous MVNO guesses. +export function automatic(imsi) { + if(type(imsi)!='string' || !match(imsi,/^[0-9]{14,16}$/))return null; + let numeric=substr(imsi,0,5), apn=null; + if(numeric in ['46000','46002','46004','46007','46008'])apn='cmnet'; + if(numeric in ['46001','46006','46009','46030'])apn='3gnet'; + if(numeric in ['46003','46005','46011','46012'])apn='ctnet'; + if(numeric=='46015')apn='cbnet'; + return apn?{apn,pdptype:'IPV4V6',roaming:'IPV4V6',auth:'none',username:'',password:'',attach:'0'}:null; +}; +export function validate(p) { + if(type(p)!='object' || type(p.name)!='string' || !length(trim(p.name)) || + length(p.name)>64 || match(p.name,/[[:cntrl:]]/)) return false; + let value=p.apn ?? ''; + if(type(value)!='string' || length(value)>100 || + (value!='' && !match(value,/^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/))) return false; + for(let label in split(value,'.'))if(length(label)>63)return false; + // mu300cell requires an IPv4 bearer address; IPv6-only is not supported. + return p.pdptype in ['IP','IPV4V6'] && (p.roaming || p.pdptype) in ['IP','IPV4V6'] && + auth(p) in ['none','pap','chap','papchap'] && credentials(p) && + (p.attach==null || p.attach in ['0','1']) && + length(sprintf('AT+SPCGAPNCFG=1,"%s","%s","%s",0,"%s","%s",3',value,p.pdptype,p.roaming || p.pdptype,p.username || '',p.password || ''))<=240; +}; +export function resolve(c,identity,base) { + let b=binding(c,identity); + if(!b)return {ok:1,source:'network',settings:options(base)}; + if(b.mode=='auto') { + let settings=automatic(identity.imsi); + // Unknown operators retain network-selected defaults, never a guessed APN. + return {ok:1,source:settings?'auto':'default',settings:settings || options({pdptype:'IPV4V6'})}; + } + let p=c.get_all(cfg,b.profile); + if(!p || p['.type']!='profile' || !validate(p))return fail('apn_missing'); + return {ok:1,source:'sim',profile:b.profile,settings:options(p)}; +}; +export function get(c,identity) { + let iface=c.get('unisoc_modem','main','data_interface') || 'wan'; + if(!match(iface,/^[A-Za-z0-9_]{1,32}$/) || c.get('network',iface)!='interface' || + c.get('network',iface,'proto')!='mu300cell') return fail('apn_unsupported'); + let current=options(c.get_all('network',iface)); + let selected=binding(c,identity), resolved=resolve(c,identity,current); + if(resolved.ok)current=resolved.settings; + // Credentials are only returned by the private dialer resolve path. + let publicCurrent={...current,has_password:!!length(current.password)};delete publicCurrent.password; + let profiles=[]; + c.foreach(cfg,'profile',s=>{ + let publicOptions=options(s);delete publicOptions.password; + push(profiles,{...publicOptions,id:s['.name'],name:s.name || s['.name'],has_password:!!length(s.password || ''), + current:selected?selected.mode=='manual' && selected.profile==s['.name']:same(s,current)}); + }); + return {ok:1,iface,current:publicCurrent,profiles,data_sim:c.get('unisoc_modem','main','data_sim')=='1'?1:0, + remembered:!!selected,mode:selected?.mode || 'global',identity_ready:!!valid_identity(identity),source:resolved.source || 'error'}; +}; +export function change(c,action,p,reload,identity) { + let state=get(c,identity); + if(!state.ok)return state; + if(!(action in ['save','delete','apply','auto']))return fail('apn_invalid'); + if(type(p)!='object')return fail('apn_invalid'); + if(length(c.changes(cfg) ?? {}) || length(c.changes('network') ?? {}) || + length(c.changes('unisoc_modem') ?? {})) return fail('apn_unsaved'); + let id=p.id || '', profile=null; + if(id) { + if(!valid_id(id))return fail('apn_invalid'); + for(let item in state.profiles)if(item.id==id)profile=item; + if(!profile)return fail('apn_missing'); + } + let remember=p.remember===true || action=='auto'; + if((action=='apply' || action=='auto') && remember && !valid_identity(identity))return fail('apn_identity'); + let target=action=='apply' && !remember?'network':cfg; + function failed() { c.revert(target);return fail('apn_storage'); } + if(action=='save') { + if(profile && p.password==null)p.password=c.get(cfg,id,'password') || ''; + if(!validate(p))return fail('apn_invalid'); + if(!id && length(state.profiles)>=32)return fail('apn_limit'); + for(let item in state.profiles) + if(item.id!=id && same(c.get_all(cfg,item.id),p))return fail('apn_duplicate'); + if(!id)id=c.add(cfg,'profile'); + if(!id || !c.set(cfg,id,'name',trim(p.name)) || !c.set(cfg,id,'apn',p.apn) || + !c.set(cfg,id,'pdptype',p.pdptype))return failed(); + for(let key,value in options(p))if(!c.set(cfg,id,key,value))return failed(); + } else if(action=='auto' || (action=='apply' && remember)) { + if(action=='apply' && (!profile || !validate(c.get_all(cfg,id))))return fail('apn_invalid'); + let b=binding(c,identity), sid=b?.['.name'] || c.add(cfg,'selection'); + if(!sid || !c.set(cfg,sid,'iccid',identity.iccid) || !c.set(cfg,sid,'mode',action=='auto'?'auto':'manual') || + !c.set(cfg,sid,'profile',action=='auto'?'':id))return failed(); + } else { + if(!profile)return fail('apn_missing'); + if(action=='delete') { + if(profile.current)return fail('apn_current'); + let used=false;c.foreach(cfg,'selection',s=>{if(s.mode=='manual' && s.profile==id)used=true;}); + if(used)return fail('apn_bound'); + if(!c.delete(cfg,id))return failed(); + } else { + let settings=c.get_all(cfg,id); + if(!validate(settings))return fail('apn_invalid'); + if(binding(c,identity))return fail('apn_scope'); + if(profile.current)return reload(state.iface)?{ok:1,unchanged:1}:{ok:0,saved:1,error:'apn_reload'}; + if(!c.set('network',state.iface,'apn',profile.apn) || + !c.set('network',state.iface,'pdptype',profile.pdptype))return failed(); + for(let key,value in options(settings))if(!c.set('network',state.iface,key,value))return failed(); + } + } + if(!c.commit(target))return failed(); + if((action=='apply' || action=='auto') && !reload(state.iface))return {ok:0,saved:1,error:'apn_reload'}; + return {ok:1,id,pending:action=='apply' || action=='auto'}; +}; diff --git a/openwrt/luci-app-mu300/root/usr/share/luci/menu.d/luci-app-mu300.json b/openwrt/luci-app-mu300/root/usr/share/luci/menu.d/luci-app-mu300.json index 028132a6..bd4edb6f 100644 --- a/openwrt/luci-app-mu300/root/usr/share/luci/menu.d/luci-app-mu300.json +++ b/openwrt/luci-app-mu300/root/usr/share/luci/menu.d/luci-app-mu300.json @@ -22,6 +22,12 @@ } }, + "admin/modem/apn": { + "title": "接入点 APN", + "order": 10, + "action": { "type": "view", "path": "mu300/apn" }, + "depends": { "acl": [ "luci-app-mu300" ] } + }, "admin/modem/locks": { "title": "网络锁定", "order": 1, diff --git a/openwrt/luci-app-mu300/root/usr/share/rpcd/acl.d/luci-app-mu300.json b/openwrt/luci-app-mu300/root/usr/share/rpcd/acl.d/luci-app-mu300.json index 1839dd25..cdc81115 100644 --- a/openwrt/luci-app-mu300/root/usr/share/rpcd/acl.d/luci-app-mu300.json +++ b/openwrt/luci-app-mu300/root/usr/share/rpcd/acl.d/luci-app-mu300.json @@ -4,7 +4,7 @@ "read": { "ubus": { "mu300dash": [ - "sysinfo", "status", "rates", "cells", "signal", "at_history", + "apn_get", "sysinfo", "status", "rates", "cells", "signal", "at_history", "lock_get", "lock_status", "sms_list", "sms_show", "forward_get", "forward_status", "traffic_get", "usb_get", "usb_net_list", "cpu_get", "cpu_voltage_get", "sim_get", "data_sim_get", "data_sim_status" ] diff --git a/openwrt/overlay/lib/netifd/proto/mu300cell.sh b/openwrt/overlay/lib/netifd/proto/mu300cell.sh index ae87adfd..734b7d0b 100755 --- a/openwrt/overlay/lib/netifd/proto/mu300cell.sh +++ b/openwrt/overlay/lib/netifd/proto/mu300cell.sh @@ -23,14 +23,19 @@ proto_mu300cell_init_config() { renew_handler=1 proto_config_add_string "apn" proto_config_add_string "pdptype" + proto_config_add_string "auth" + proto_config_add_string "username" + proto_config_add_string "password" + proto_config_add_string "roaming" + proto_config_add_boolean "attach" proto_config_add_boolean "peerdns" proto_config_add_array "dns:list(ipaddr)" } proto_mu300cell_setup() { local config="$1" - local apn pdptype peerdns out ifname ip prefix dns1 dns2 iid zone slot rc - json_get_vars apn pdptype peerdns + local apn pdptype peerdns out ifname ip prefix dns1 dns2 iid zone slot rc auth username password roaming attach + json_get_vars apn pdptype peerdns auth username password roaming attach . /opt/mu300/bin/mu300-sim-env mu300_sim_env || { proto_notify_error "$config" INVALID_SIM; return 1; } slot=$MU300_SIM_SLOT @@ -38,8 +43,10 @@ proto_mu300cell_setup() { # the next SIM. Keep this runtime ownership separate from persistent intent. printf '%s\n%s\n' "$slot" "$MU300_SIM_DEVICE" > "/run/mu300cell-$config.sim" - out=$(MU300_NETIFD=1 MU300_PDP_TYPE="${pdptype:-IP}" /opt/mu300/bin/mobile-data up $apn 2>/tmp/mu300cell.err) + printf '{"phase":"connecting"}\n' > "/run/unisoc-apn-dial-$slot.json" + out=$(MU300_NETIFD=1 MU300_PDP_TYPE="${pdptype:-IP}" MU300_AUTH="${auth:-none}" MU300_USERNAME="$username" MU300_PASSWORD="$password" MU300_ROAMING_PDP_TYPE="${roaming:-${pdptype:-IP}}" MU300_INITIAL_ATTACH="${attach:-0}" /opt/mu300/bin/mobile-data up "$apn" 2>/tmp/mu300cell.err) rc=$? + [ "$rc" = 0 ] || printf '{"phase":"failed"}\n' > "/run/unisoc-apn-dial-$slot.json" if [ "$rc" = 4 ]; then logger -t mu300cell "$(cat /tmp/mu300cell.err)" proto_notify_error "$config" DUAL_RADIO_REBOOT_REQUIRED @@ -56,12 +63,17 @@ proto_mu300cell_setup() { fi ip=$(echo "$out" | sed -n 's/^IP=//p') if [ -z "$ip" ]; then + printf '{"phase":"failed"}\n' > "/run/unisoc-apn-dial-$slot.json" logger -t mu300cell "attach failed: $(cat /tmp/mu300cell.err)" proto_notify_error "$config" ATTACH_FAILED proto_setup_failed "$config" return 1 fi ifname=$(echo "$out" | sed -n 's/^IFACE=//p') + # Per-SIM profiles can override the global protocol passed by netifd. + local effective_type + effective_type=$(echo "$out" | sed -n 's/^PDP_TYPE=//p') + case "$effective_type" in IP|IPV4V6) pdptype=$effective_type ;; esac prefix=$(echo "$out" | sed -n 's/^PREFIX=//p') dns1=$(echo "$out" | sed -n 's/^DNS1=//p') dns2=$(echo "$out" | sed -n 's/^DNS2=//p') @@ -111,6 +123,7 @@ proto_mu300cell_setup() { [ -n "$dns2" ] && proto_add_dns_server "$dns2" fi proto_send_update "$config" + printf '{"phase":"connected"}\n' > "/run/unisoc-apn-dial-$slot.json" # The event-driven child is the protocol task netifd owns. It reports IPv6 # netlink changes and CGEV-triggered IPv4/DNS changes without holding setup. [ "${pdptype:-IP}" != IP ] && proto_run_command "$config" \ diff --git a/openwrt/patches/fstools-probe-device-types.patch b/openwrt/patches/fstools-probe-device-types.patch new file mode 100644 index 00000000..55dc568c --- /dev/null +++ b/openwrt/patches/fstools-probe-device-types.patch @@ -0,0 +1,20 @@ +--- a/block.c ++++ b/block.c +@@ -45,5 +45,6 @@ + #include + + #include "probe.h" ++#include "block-probe-guard.h" + + #define AUTOFS_MOUNT_PATH "/tmp/run/blockd/" +@@ -533,7 +534,10 @@ + { + struct probe_info *pr, *epr; + char tmppath[64]; + ++ /* Never probe communication character devices matched by /dev/sd*. */ ++ if (!mu300_probe_allowed(path)) ++ return NULL; + if (!strncmp(path, "/dev/mtdblock", 13) && mtdblock_is_nand(path + 13)) + return NULL; + diff --git a/rootfs/overlay/opt/mu300/bin/mobile-data b/rootfs/overlay/opt/mu300/bin/mobile-data index a2d6adb3..5ff19791 100755 --- a/rootfs/overlay/opt/mu300/bin/mobile-data +++ b/rootfs/overlay/opt/mu300/bin/mobile-data @@ -530,6 +530,89 @@ up() { return $rc } +configure_pdp_context() { + # An explicitly empty netifd APN means SIM default, not "keep the old APN". + # Unmanaged/systemd callers without an argument retain their old behavior. + local apn="${1-${MU300_APN:-}}" pdptype="${MU300_PDP_TYPE:-IP}" result + [ -n "$apn" ] || [ "${MU300_NETIFD:-0}" = 1 ] || return 0 + case "$pdptype" in IP|IPV4V6) ;; *) echo 'Invalid PDP type' >&2; return 1;; esac + if [ "${#apn}" -gt 100 ] || { [ -n "$apn" ] && ! [[ "$apn" =~ ^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$ ]]; }; then + echo 'Invalid APN' >&2; return 1 + fi + result=$(at "AT+CGDCONT=$CID,\"$pdptype\",\"$apn\"" 5) || return 1 + printf '%s\n' "$result" | tr -d '\r' | grep -qx OK || { + echo 'PDP configuration rejected or unverified' >&2; return 1; + } + if [ "${MU300_NETIFD:-0}" = 1 ] || [ -n "${MU300_AUTH:-}${MU300_USERNAME:-}${MU300_PASSWORD:-}" ]; then + apn_credentials_valid || return 1 + # B09 RIL's ordinary M-ETHER bearer uses CGPCO, including auth=0 + # to clear a previous account. No credentials are printed to stderr. + result=$(at "AT+CGPCO=0,\"${MU300_USERNAME:-}\",\"${MU300_PASSWORD:-}\",$CID,$APN_AUTH_NUMBER" 5 2>/dev/null) || { + echo 'APN authentication configuration failed' >&2; return 1; + } + printf '%s\n' "$result" | tr -d '\r' | grep -qx OK || { + echo 'APN authentication rejected or unverified' >&2; return 1; + } + fi +} + +apn_credentials_valid() { + local user="${MU300_USERNAME:-}" password="${MU300_PASSWORD:-}" text="${MU300_USERNAME:-}${MU300_PASSWORD:-}" + case "${MU300_AUTH:-none}" in none) APN_AUTH_NUMBER=0;; pap) APN_AUTH_NUMBER=1;; chap) APN_AUTH_NUMBER=2;; papchap) APN_AUTH_NUMBER=3;; *) echo 'Invalid APN authentication' >&2; return 1;; esac + [ "${#user}" -le 64 ] && [ "${#password}" -le 64 ] || return 1 + [[ "$text" != *\"* && "$text" != *\\* && "$text" != *[!\ -\~]* ]] || { echo 'Invalid APN credentials' >&2; return 1; } +} + +resolve_apn_selection() { + local helper=/usr/libexec/unisoc-modem/apn identity iccid imsi= data needed + [ -x "$helper" ] || return 0 + needed=$("$helper" needs-identity 2>/dev/null) || { echo 'APN profile configuration unavailable' >&2; return 1; } + case "$needed" in 0|1) ;; *) echo 'Invalid APN profile configuration' >&2; return 1 ;; esac + 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; } + identity=$(printf '{"iccid":"%s"}' "$iccid") + fi + # Query IMSI only when this card actually has automatic selection enabled. + # Resolve global settings too: an already-running netifd may still have + # the old protocol schema after a no-restart hot deployment. + data=$(printf '%s' "$identity" | "$helper" resolve) || return 1 + if [ "$(printf '%s' "$data" | jsonfilter -e '@.source')" = default ]; then + imsi=$(at 'AT+CIMI' 3 2>/dev/null | tr -d '\r' | grep -E '^[0-9]{14,16}$' | head -n1) || true + [[ "$imsi" =~ ^[0-9]{14,16}$ ]] || { imsi=; echo 'SIM operator unavailable; using SIM default APN' >&2; } + data=$(printf '{"iccid":"%s","imsi":"%s"}' "$iccid" "$imsi" | "$helper" resolve) || return 1 + fi + [ "$(printf '%s' "$data" | jsonfilter -e '@.ok')" = 1 ] || { echo 'Remembered APN profile unavailable' >&2; return 1; } + if [ "$needed" = 1 ]; then + umask 077 + printf '{"iccid":"%s","imsi":"%s"}\n' "$iccid" "$imsi" > "/run/unisoc-apn-sim$MU300_SIM_SLOT.json.new.$$" + mv "/run/unisoc-apn-sim$MU300_SIM_SLOT.json.new.$$" "/run/unisoc-apn-sim$MU300_SIM_SLOT.json" + fi + RESOLVED_APN=$(printf '%s' "$data" | jsonfilter -e '@.settings.apn') + MU300_PDP_TYPE=$(printf '%s' "$data" | jsonfilter -e '@.settings.pdptype') + MU300_AUTH=$(printf '%s' "$data" | jsonfilter -e '@.settings.auth') + MU300_USERNAME=$(printf '%s' "$data" | jsonfilter -e '@.settings.username') + MU300_PASSWORD=$(printf '%s' "$data" | jsonfilter -e '@.settings.password') + MU300_ROAMING_PDP_TYPE=$(printf '%s' "$data" | jsonfilter -e '@.settings.roaming') + MU300_INITIAL_ATTACH=$(printf '%s' "$data" | jsonfilter -e '@.settings.attach') + APN_RESOLVED=1 +} + +configure_initial_apn() { + [ "${MU300_INITIAL_ATTACH:-0}" = 1 ] || return 0 + local apn="${1:-}" protocol="${MU300_PDP_TYPE:-IP}" roaming="${MU300_ROAMING_PDP_TYPE:-${MU300_PDP_TYPE:-IP}}" result command + case "$protocol:$roaming" in IP:IP|IP:IPV4V6|IPV4V6:IP|IPV4V6:IPV4V6) ;; *) return 1;; esac + [[ "$apn" =~ ^[A-Za-z0-9.-]*$ ]] || return 1 + apn_credentials_valid || return 1 + command="AT+SPCGAPNCFG=1,\"$apn\",\"$protocol\",\"$roaming\",0,\"${MU300_USERNAME:-}\",\"${MU300_PASSWORD:-}\",$APN_AUTH_NUMBER" + [ -n "$apn" ] || command='AT+SPCGAPNCFG=1,""' + [ "${#command}" -le 240 ] || return 1 + result=$(at "$command" 5 2>/dev/null) || { echo 'Initial APN configuration failed' >&2; return 1; } + printf '%s\n' "$result" | tr -d '\r' | grep -qx OK || { echo 'Initial APN configuration rejected' >&2; return 1; } +} + up_locked() { modem_stack || { echo "no modem stack in this kernel ($(uname -r))" >&2; exit 3; } rm -f /run/mu300-mobile-data-down @@ -546,6 +629,11 @@ up_locked() { fi fi mark dial-radio-on-done + if [ "${MU300_NETIFD:-0}" = 1 ]; then + resolve_apn_selection || return 1 + [ "${APN_RESOLVED:-0}" != 1 ] || set -- "$RESOLVED_APN" + configure_initial_apn "${1-${MU300_APN:-}}" || return 1 + fi # Android's RIL enables the IMS bearer used by SMS. This is idempotent; # keep it on the normal radio bring-up path and do not wait for IMS here. at 'AT+CAVIMS=1' 5 >/dev/null || true @@ -569,18 +657,7 @@ up_locked() { exit 1 } fi - # systemd has no way to pass an argument from a config file, so the APN can come from the environment too: - # /etc/mu300/mobile-data.conf is an EnvironmentFile for the service. The argument still wins, which is what - # the OpenWrt protocol handler uses. - set -- "${1:-${MU300_APN:-}}" - if [ -n "${1:-}" ]; then - # "IP", not "IPV4V6", because that is what Android's RIL asks this modem for. Measured on the same - # device with data working, its sipa_eth0 carries one IPv4 address and has IPv6 switched off outright - # (/proc/sys/net/ipv6/conf/sipa_eth0/disable_ipv6 = 1). A dual-stack context is the one part of our - # bring-up the working system never performs, and downlink is what we are missing (FINDINGS 13f). - # MU300_PDP_TYPE=IPV4V6 asks for both again, for a carrier that needs it. - at "AT+CGDCONT=$CID,\"${MU300_PDP_TYPE:-IP}\",\"$1\"" >/dev/null - fi + configure_pdp_context "$@" || return 1 # 不再先问一次 AT+CGACT?:开机时上下文一定是关的,问那一趟是一条整 AT 往返(实测约 2 s), # 而 CGACT=1 对已经激活的上下文是幂等的(重拨、watch 重连就是这种情况),所以问不问结果一样。 local activated @@ -642,7 +719,7 @@ up_locked() { esac if [ "${MU300_NETIFD:-0}" = 1 ]; then # OpenWrt: netifd (proto mu300cell) configures the address, routes, DNS and firewall itself - printf 'IFACE=%s\nIP=%s\nPREFIX=%s\nDNS1=%s\nDNS2=%s\nIID6=%s\n' "$IFACE" "$ip4" "$prefix" "$dns1" "$dns2" "$iid" + printf 'IFACE=%s\nIP=%s\nPREFIX=%s\nDNS1=%s\nDNS2=%s\nIID6=%s\nPDP_TYPE=%s\n' "$IFACE" "$ip4" "$prefix" "$dns1" "$dns2" "$iid" "${MU300_PDP_TYPE:-IP}" return 0 fi ip link set "$IFACE" up diff --git a/tests/apn.uc b/tests/apn.uc new file mode 100644 index 00000000..a2f015b0 --- /dev/null +++ b/tests/apn.uc @@ -0,0 +1,79 @@ +import * as a from 'apn'; +import * as fs from 'fs'; +import { cursor } from 'uci'; +let n=0; +function check(ok,label) { if(!ok)die('FAIL '+label+'\n');n++; } +let requests=[]; +check(a.reconnect({call:(object,method)=>{push(requests,[object,method]);return null;}},()=>null,'wan'),'empty successful ubus reply accepted'); +check(length(requests)==3 && requests[2][1]=='up','reload down up all requested'); +requests=[]; +check(!a.reconnect({call:(object,method)=>{push(requests,[object,method]);return null;}},()=>4,'wan') && length(requests)==1,'real ubus error stops reconnect'); +let pipe=fs.popen('mktemp -d /tmp/mu300-apn-test.XXXXXX','r'); +let dir=trim(pipe.read('all'));pipe.close(); +check(match(dir,/^\/tmp\/mu300-apn-test\.[a-zA-Z0-9]+$/),'private fixture'); +fs.mkdir(dir+'/delta',448); +fs.writefile(dir+'/unisoc_modem',"config modem 'main'\n option data_interface 'wan'\n option data_sim '1'\n"); +fs.writefile(dir+'/network',"config interface 'wan'\n option proto 'mu300cell'\n option apn 'old.apn'\n option pdptype 'IPV4V6'\n option peerdns '0'\n list dns '1.1.1.1'\nconfig interface 'lan'\n option proto 'static'\n option ipaddr '192.168.77.1'\n"); +fs.writefile(dir+'/unisoc_apn',"config profile 'automatic'\n option name 'SIM default'\n option apn ''\n option pdptype 'IPV4V6'\n"); +let c=cursor(dir,dir+'/delta'), calls=0; +function reload(iface) { check(iface=='wan','only selected iface');calls++;return true; } +let s=a.get(c);check(s.ok && s.data_sim==1 && s.current.apn=='old.apn','current SIM and APN'); +check(calls==0,'read never reconnects'); +for(let apn in ['internet','3gnet','a-b.example','a--b.example',''])check(a.validate({name:'x',apn,pdptype:'IPV4V6'}),'valid APN'); +for(let apn in ['a";AT','bad\nAT','a b','a..b','.foo','$(reboot)'])check(!a.validate({name:'x',apn,pdptype:'IP'}),'invalid APN'); +check(!a.validate({name:' ',apn:'a',pdptype:'IP'}),'empty name'); +check(!a.validate({name:'x',apn:'a',pdptype:'IPV6'}),'unsupported IPv6-only'); +let r=a.change(c,'save',{name:'Carrier',apn:'new.apn',pdptype:'IP'},reload); +check(r.ok && r.id && calls==0,'save does not apply');let id=r.id; +c=cursor(dir,dir+'/delta');check(length(a.get(c).profiles)==2,'profile persisted'); +check(c.get('network','wan','apn')=='old.apn','save leaves bearer alone'); +check(a.change(c,'save',{name:'Duplicate',apn:'new.apn',pdptype:'IP'},reload).error=='apn_duplicate','duplicate denied'); +check(a.change(c,'delete',{id:'../../../network'},reload).error=='apn_invalid','invalid id'); +check(a.change(c,'apply',{id:'missing'},reload).error=='apn_missing','missing profile'); +r=a.change(c,'apply',{id},reload);check(r.ok && calls==1,'apply reconnects once'); +c=cursor(dir,dir+'/delta');check(c.get('network','wan','apn')=='new.apn','APN persisted'); +check(c.get('network','wan','peerdns')=='0' && c.get('network','wan','dns')[0]=='1.1.1.1','DNS preserved'); +check(c.get('network','lan','ipaddr')=='192.168.77.1','LAN preserved'); +check(c.get('unisoc_modem','main','data_sim')=='1','SIM unchanged'); +check(a.change(c,'delete',{id},reload).error=='apn_current','active delete denied'); +r=a.change(c,'apply',{id:'automatic'},reload);check(r.ok && calls==2,'SIM default applies'); +c=cursor(dir,dir+'/delta');check(!c.get('network','wan','apn'),'old APN cleared'); +r=a.change(c,'delete',{id},reload);check(r.ok && calls==2,'inactive deleted without reconnect'); +c.set('network','lan','ipaddr','192.168.9.1');c.save('network'); +c=cursor(dir,dir+'/delta');r=a.change(c,'apply',{id:'automatic'},reload); +check(r.error=='apn_unsaved' && calls==2,'pending user changes protected'); +c.revert('network'); +r=a.change(c,'apply',{id:'automatic'},()=>false);check(!r.ok && r.saved && r.error=='apn_reload','apply failure reported'); +check(fs.mkdir(dir+'/lock',448),'lock acquired');check(!fs.mkdir(dir+'/lock',448),'parallel writer denied'); +fs.rmdir(dir+'/lock');check(fs.mkdir(dir+'/lock',448),'lock released'); +printf('apn: %d checks passed\n',n); +// Android-derived authentication, privacy and per-card persistence. +let card1={iccid:'89860012345678901234',imsi:'460001234567890'}; +let card2={iccid:'89860112345678901234',imsi:'460011234567890'}; +r=a.change(c,'save',{name:'Private',apn:'private.apn',pdptype:'IPV4V6',auth:'chap',username:'account',password:'secret'},reload); +check(r.ok,'authenticated profile');let privateId=r.id; +c=cursor(dir,dir+'/delta'); +check(index(sprintf('%J',a.get(c)),'secret')<0,'password absent from public state'); +check(a.change(c,'save',{id:privateId,name:'Private edited',apn:'private.apn',pdptype:'IPV4V6',auth:'chap',username:'account'},reload).ok,'edit keeps password'); +check(c.get('unisoc_apn',privateId,'password')=='secret','password retained'); +c=cursor(dir,dir+'/delta'); +for(let text in ['quote"','slash\\','line\n','非ASCII'])check(!a.validate({name:'x',apn:'internet',pdptype:'IP',username:text}),'credential injection denied'); +check(a.change(c,'apply',{id:privateId,remember:true},reload,{}).error=='apn_identity','identity mandatory'); +c=cursor(dir,dir+'/delta'); +check(a.change(c,'apply',{id:privateId,remember:true},reload,card1).ok,'card one assigned'); +c=cursor(dir,dir+'/delta'); +let selected=a.resolve(c,card1,{apn:'global',pdptype:'IP'}); +check(selected.ok && selected.settings.password=='secret' && selected.settings.apn=='private.apn','dialer gets card one credentials'); +check(a.resolve(c,card2,{apn:'global',pdptype:'IP'}).settings.apn=='global','other SIM does not inherit private APN'); +check(a.change(c,'delete',{id:privateId},reload,card2).error=='apn_bound','other card binding protected'); +check(a.change(c,'apply',{id:'automatic'},reload,card1).error=='apn_scope','global cannot override binding'); +check(a.change(c,'auto',{},reload,card2).ok,'second card auto assigned'); +c=cursor(dir,dir+'/delta'); +check(a.resolve(c,card2,{}).settings.apn=='3gnet','China Unicom public rule'); +check(a.resolve(c,card1,{}).settings.apn=='private.apn','first card binding persists'); +check(a.resolve(c,{iccid:card2.iccid,imsi:'999991234567890'},{}).settings.apn=='','unknown operator not guessed'); +check(a.automatic('460151234567890').apn=='cbnet','CBN rule'); +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); diff --git a/tests/block_mount_runtime.sh b/tests/block_mount_runtime.sh new file mode 100644 index 00000000..78253b8e --- /dev/null +++ b/tests/block_mount_runtime.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# Run ONLY in a disposable OpenWrt container, with the patched APK at /in/block.apk. +set -eu +[ "${MU300_BLOCK_TEST_CONTAINER:-}" = 1 ] || { echo 'container opt-in required' >&2; exit 2; } +apk update >/dev/null +apk add --allow-untrusted /in/block.apk >/dev/null +apk add e2fsprogs coreutils-timeout >/dev/null +apk list --installed block-mount | grep -F '16718b6e-r100' +test -x /sbin/block +test -s /lib/libblkid-tiny.so +test -x /etc/init.d/fstab +disk=/dev/sd-mu300-test.img +fifo=/dev/sdiag-mu300-test +channel=/dev/sdiom-mu300-test +for p in "$disk" "$fifo" "$channel"; do + [ ! -e "$p" ] && [ ! -L "$p" ] || exit 2 +done +trap 'rc=$?; rm -f "$disk" "$fifo" "$channel" /tmp/mu300-block-info /tmp/mu300-block-detect; exit "$rc"' EXIT +mkfifo "$fifo" +ln -s /dev/zero "$channel" +dd if=/dev/zero of="$disk" bs=1M count=0 seek=16 2>/dev/null +[ -f "$disk" ] && [ ! -b "$disk" ] && [ ! -c "$disk" ] +mkfs.ext4 -q -F -L MU300_TEST "$disk" +# An unsafe probe hangs on the FIFO even when a specific disk argument is used. +timeout 5 /sbin/block info > /tmp/mu300-block-info +grep -q 'LABEL="MU300_TEST".*TYPE="ext4"' /tmp/mu300-block-info +! grep -E 'sdiag-mu300|sdiom-mu300' /tmp/mu300-block-info +# The explicit-info path only prints block nodes (not regular-file fixtures), +# but must still finish its initial full scan in the presence of the FIFO. +timeout 5 /sbin/block info "$disk" >/dev/null +timeout 5 /sbin/block detect > /tmp/mu300-block-detect +grep -q '/mnt/sd-mu300-test.img' /tmp/mu300-block-detect +! grep -E 'sdiag-mu300|sdiom-mu300' /tmp/mu300-block-detect +echo 'block-mount runtime: APK, normal ext4 discovery and communication/FIFO filtering passed' diff --git a/tests/block_probe_guard.c b/tests/block_probe_guard.c new file mode 100644 index 00000000..cac251e2 --- /dev/null +++ b/tests/block_probe_guard.c @@ -0,0 +1,56 @@ +/* No real device is opened or changed by these tests. */ +#include +#include +#include +#include +#include +#include +#include +static mode_t fixture_mode; +static const char *fixture_subsystem; +static int fixture_exists = 1, reads; +static int mock_stat(const char *path, struct stat *st) +{ + (void)path; + if (!fixture_exists) return -1; + st->st_mode = fixture_mode; + st->st_rdev = makedev(250, 7); + return 0; +} +static ssize_t mock_readlink(const char *path, char *buf, size_t len) +{ + reads++; + assert(!strcmp(path, "/sys/dev/char/250:7/subsystem")); + if (!fixture_subsystem) return -1; + size_t n = strlen(fixture_subsystem); + if (n > len) n = len; + memcpy(buf, fixture_subsystem, n); + return n; +} +#define stat(path, st) mock_stat(path, st) +#define readlink mock_readlink +#include "../openwrt/block-probe-guard.h" +#undef stat +#undef readlink +int main(void) +{ + fixture_mode = S_IFBLK; assert(mu300_probe_allowed("/dev/mmcblk1p1")); + assert(mu300_probe_allowed("/dev/sda1")); + fixture_mode = S_IFREG; assert(mu300_probe_allowed("/mnt/swapfile")); + fixture_mode = S_IFDIR; assert(!mu300_probe_allowed("/dev/sd-directory")); + fixture_mode = S_IFIFO; assert(!mu300_probe_allowed("/dev/sdiag-fifo")); + fixture_mode = S_IFSOCK; assert(!mu300_probe_allowed("/dev/sd-socket")); + assert(!reads); + fixture_mode = S_IFCHR; + fixture_subsystem = "../../../../class/tty"; + assert(!mu300_probe_allowed("/dev/sdiag")); + assert(!mu300_probe_allowed("/dev/ubi0_0")); /* name alone is not trust */ + fixture_subsystem = "../../../../class/spipe"; + assert(!mu300_probe_allowed("/dev/sdiom")); + fixture_subsystem = NULL; assert(!mu300_probe_allowed("/dev/slog")); + fixture_subsystem = "../../../../class/ubi"; + assert(mu300_probe_allowed("/dev/ubi0_0")); + fixture_exists = 0; assert(!mu300_probe_allowed("/dev/missing")); + puts("block probe guard: 12 checks passed"); + return 0; +} diff --git a/tests/test_apn.py b/tests/test_apn.py new file mode 100644 index 00000000..bdcf59f5 --- /dev/null +++ b/tests/test_apn.py @@ -0,0 +1,99 @@ +"""APN list/UI/package contract and isolated dialer configuration tests.""" +import json +import re +from helpers import TOP, ShellTest + +APP=TOP/'openwrt/luci-app-mu300' +LIB=APP/'root/usr/libexec/unisoc-modem' + +class APN(ShellTest): + 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() {')] + helper=self.tmp/'apn' + helper.write_text('#!/bin/sh\nif [ "$1" = needs-identity ]; then echo 0; else cat <<\'JSON\'\n'+json.dumps({'ok':1,'source':'network','settings':{'apn':'carrier.test','pdptype':'IPV4V6','auth':'chap','username':'fixture','password':'secret','roaming':'IP','attach':'0'}})+'\nJSON\nfi\n') + 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/'resolve.sh' + path.write_text('set -eu\n'+function.replace('/usr/libexec/unisoc-modem/apn',str(helper))+''' +at() { echo UNEXPECTED-AT >&2; return 1; } +resolve_apn_selection +[ "$RESOLVED_APN:$MU300_PDP_TYPE:$MU300_AUTH:$MU300_USERNAME:$MU300_PASSWORD" = 'carrier.test:IPV4V6:chap:fixture:secret' ] +''') + r=self.script(['bash'],path) + self.assertEqual(r.returncode,0,r.stderr) + self.assertNotIn('secret',r.stdout+r.stderr) + self.assertNotIn('UNEXPECTED-AT',r.stderr) + + def test_authentication_and_attach_order(self): + source=(TOP/'rootfs/overlay/opt/mu300/bin/mobile-data').read_text() + functions=source[source.index('configure_pdp_context() {'):source.index('\nup_locked() {')] + path=self.tmp/'order.sh' + path.write_text('set -u\n'+functions+'''\nat() { printf '%s\\n' "$1" >> "$STUBLOG/at-calls"; printf '%s\\n' "${REPLY:-OK}"; } +configure_initial_apn internet && configure_pdp_context internet +''') + r=self.script(['bash'],path,CID='1',MU300_NETIFD='1',MU300_AUTH='papchap',MU300_USERNAME='fixture',MU300_PASSWORD='fixture-secret',MU300_PDP_TYPE='IPV4V6',MU300_ROAMING_PDP_TYPE='IP',MU300_INITIAL_ATTACH='1') + self.assertEqual(r.returncode,0,r.stderr) + calls=(self.tmp/'at-calls').read_text().splitlines() + self.assertEqual(calls,['AT+SPCGAPNCFG=1,"internet","IPV4V6","IP",0,"fixture","fixture-secret",3','AT+CGDCONT=1,"IPV4V6","internet"','AT+CGPCO=0,"fixture","fixture-secret",1,3']) + self.assertNotIn('fixture-secret',r.stdout+r.stderr) + (self.tmp/'at-calls').unlink() + r=self.script(['bash'],path,CID='1',MU300_NETIFD='1',REPLY='ERROR',MU300_INITIAL_ATTACH='1') + self.assertNotEqual(r.returncode,0) + self.assertEqual(len((self.tmp/'at-calls').read_text().splitlines()),1) + + def test_pdp_context(self): + source=(TOP/'rootfs/overlay/opt/mu300/bin/mobile-data').read_text() + function=source[source.index('configure_pdp_context() {'):source.index('\nup_locked() {')] + harness=function+'''\nat() { printf '%s\\n' "$1" >&2; printf '%s\\n' "${REPLY:-OK}"; } +configure_pdp_context "$@" +''' + path=self.tmp/'pdp.sh';path.write_text(harness) + r=self.script(['bash'],path,'',MU300_NETIFD='1',MU300_APN='stale.apn',CID='1',MU300_PDP_TYPE='IPV4V6') + self.assertEqual(r.returncode,0,r.stderr) + self.assertIn('AT+CGDCONT=1,"IPV4V6",""',r.stderr) + r=self.script(['bash'],path,'internet',CID='1',REPLY='ERROR') + self.assertNotEqual(r.returncode,0) + for apn in ('bad"AT','a b','a..b','a\nAT'): + r=self.script(['bash'],path,apn,CID='1') + self.assertNotEqual(r.returncode,0) + self.assertNotIn('AT+CGDCONT',r.stderr) + r=self.script(['bash'],path,CID='1') + self.assertEqual(r.returncode,0);self.assertNotIn('AT+CGDCONT',r.stderr) + r=self.script(['bash','-u'],path,'internet',CID='1',MU300_NETIFD='1',MU300_AUTH='chap',MU300_USERNAME='testuser',MU300_PASSWORD='testpass') + self.assertEqual(r.returncode,0,r.stderr) + # Authentication command is deliberately suppressed from stderr. + self.assertNotIn('testpass',r.stderr) + for value in ('bad"command','bad\\command','bad\ncommand','非ASCII'): + r=self.script(['bash','-u'],path,'internet',CID='1',MU300_NETIFD='1',MU300_PASSWORD=value) + self.assertNotEqual(r.returncode,0) + r=self.script(['bash','-u'],path,'internet',CID='1',MU300_NETIFD='1') + self.assertEqual(r.returncode,0,r.stderr) + self.assertIn('mobile-data up "$apn"',(TOP/'openwrt/overlay/lib/netifd/proto/mu300cell.sh').read_text()) + + def test_integration(self): + menu=json.loads((APP/'root/usr/share/luci/menu.d/luci-app-mu300.json').read_text()) + self.assertEqual(menu['admin/modem/apn']['action']['path'],'mu300/apn') + acl=json.loads((APP/'root/usr/share/rpcd/acl.d/luci-app-mu300.json').read_text()) + self.assertIn('apn_get',acl['luci-app-mu300']['read']['ubus']['mu300dash']) + self.assertIn('/etc/config/unisoc_apn',(APP/'Makefile').read_text()) + for build in ('build-openwrt-tf-magisk.sh','make-release.sh'): + text=(TOP/'tools'/build).read_text() + for path in ('usr/libexec/unisoc-modem/apn','usr/libexec/unisoc-modem/apn.uc','etc/config/unisoc_apn','www/luci-static/resources/view/mu300/apn.js'): + self.assertIn('./'+path+' ',text) + text=(LIB/'apn').read_text() + self.assertNotIn('fs.system',text) + self.assertNotIn('wifi reload',text) + + def test_errors_have_ui_labels(self): + ui=(APP/'htdocs/luci-static/resources/view/mu300/apn.js').read_text() + for name in ('apn','apn.uc'): + for error in re.findall(r"'(apn_[a-z]+)'",(LIB/name).read_text()): + self.assertIn(error+':',ui) diff --git a/tests/test_apn_ui.py b/tests/test_apn_ui.py new file mode 100644 index 00000000..a4b7db1d --- /dev/null +++ b/tests/test_apn_ui.py @@ -0,0 +1,80 @@ +"""Optional browser regression: real shared dialogs/CSS, isolated mock RPC.""" +import importlib.util +import os +import unittest +from helpers import TOP + +@unittest.skipUnless(os.environ.get('MU300_BROWSER_TESTS')=='1' and importlib.util.find_spec('playwright'), 'opt-in Playwright test') +class ApnUI(unittest.TestCase): + def test_responsive_crud_and_confirmation(self): + from playwright.sync_api import sync_playwright + src=TOP/'openwrt/luci-app-mu300/htdocs/luci-static/resources' + common=(src/'mu300/common.js').read_text(encoding='utf-8') + apn=(src/'view/mu300/apn.js').read_text(encoding='utf-8') + with sync_playwright() as pw: + browser=pw.chromium.launch(channel=os.environ.get('MU300_BROWSER_CHANNEL') or None,headless=True) + page=browser.new_page(viewport={'width':390,'height':844}) + errors=[];page.on('pageerror',lambda e:errors.append(str(e))) + page.route('**/*',lambda r:r.abort()) + for lang in ('zh','en','tr'): + page.set_content('') + page.evaluate('''({common,apn,lang})=>{ + window.L={env:{lang},bind:(fn,ctx)=>fn.bind(ctx)}; + window._=s=>s; window.N_=(a,b,n)=>n===1?a:b; + window.calls=[]; + window.state={ok:1,data_sim:1,current:{apn:'',pdptype:'IPV4V6'},profiles:[{id:'automatic',name:'SIM default',apn:'',pdptype:'IPV4V6',current:true}]}; + const rpc={declare:spec=>async(...args)=>{ + if(spec.method==='apn_get')return JSON.parse(JSON.stringify(state)); + if(spec.method!=='apn_set')return {}; + if(window.failNext){window.failNext=false;return {ok:0,error:'apn_storage'};} + calls.push(args);let [action,payload]=args,p=JSON.parse(payload); + if(action==='save'){p.id=p.id||'p'+state.profiles.length;state.profiles=state.profiles.filter(x=>x.id!==p.id);state.profiles.push(p);} + if(action==='delete')state.profiles=state.profiles.filter(x=>x.id!==p.id); + if(action==='apply'){let q=state.profiles.find(x=>x.id===p.id);state.current={apn:q.apn,pdptype:q.pdptype};state.profiles.forEach(x=>x.current=x.id===p.id);} + return {ok:1}; + }}; + const M=new Function('rpc','baseclass',common)(rpc,{extend:x=>x}); + const view=new Function('view','rpc','M',apn)({extend:x=>x},rpc,M); + window.M=M;window.apnView=view;document.body.append(view.render(state)); + }''',{'common':common,'apn':apn,'lang':lang}) + page.locator('.apn-head button').nth(1).click() + page.locator('.mud-apn-editor input').nth(0).fill('Carrier ') + page.locator('.mud-apn-editor input').nth(1).fill('internet.example') + page.locator('.mud-apn-editor select').nth(1).select_option('chap') + page.locator('.mud-apn-editor input').nth(2).fill('fixture-account') + self.assertEqual(page.locator('.mud-apn-editor input').nth(2).get_attribute('type'),'text') + self.assertTrue(page.locator('.mud-apn-editor input').nth(2).evaluate('(e)=>parseFloat(getComputedStyle(e).paddingLeft)>=10 && parseFloat(getComputedStyle(e).borderTopWidth)>=1')) + self.assertTrue(page.locator('.mud-dlg').evaluate('(e)=>e.getBoundingClientRect().top>=0 && e.getBoundingClientRect().bottom<=innerHeight')) + page.locator('.mud-apn-editor input[type=password]').fill('fixture-secret') + if lang!='zh': + self.assertNotIn('鉴权方式',page.locator('.mud-apn-editor').inner_text()) + self.assertNotIn('初始附着',page.locator('.mud-apn-editor').inner_text()) + page.locator('.mud-dlg [data-r="1"]').click() + page.wait_for_function('state.profiles.length===2 && !apnView.busy') + self.assertEqual(page.evaluate('calls.length'),1) + self.assertEqual(page.evaluate('JSON.parse(calls[0][1]).auth'),'chap') + self.assertEqual(page.evaluate('JSON.parse(calls[0][1]).username'),'fixture-account') + self.assertEqual(page.locator('.apn-item strong').nth(1).inner_text(),'Carrier ') + self.assertTrue(page.evaluate('document.documentElement.scrollWidth<=innerWidth')) + page.locator('.apn-item').nth(1).locator('button').nth(0).click() + page.locator('.mud-dlg [data-r="0"]').click() + self.assertEqual(page.evaluate('calls.length'),1) + page.locator('.apn-item').nth(1).locator('button').nth(0).click() + page.locator('.mud-dlg [data-r="1"]').click() + page.wait_for_function('calls.length===2 && !apnView.busy') + self.assertTrue(page.evaluate('JSON.parse(calls[1][1]).remember')) + self.assertTrue(page.locator('.apn-item').nth(1).locator('button').nth(2).is_disabled()) + page.locator('.apn-item').nth(0).locator('button').nth(2).click() + page.locator('.mud-dlg [data-r="1"]').click() + page.wait_for_function('state.profiles.length===1 && !apnView.busy') + self.assertEqual(page.locator('.mud-dlg-wrap').count(),0) + self.assertFalse(page.locator('.apn-actions button').nth(0).is_disabled()) + page.evaluate('window.failNext=true') + page.locator('.apn-actions button').nth(1).click() + page.locator('.mud-apn-editor input').nth(0).fill('Failed edit') + page.locator('.mud-dlg [data-r="1"]').click() + page.wait_for_function('!window.failNext && !apnView.busy') + self.assertEqual(page.locator('.apn-item strong').inner_text(),'Carrier ') + self.assertFalse(page.locator('.apn-actions button').nth(1).is_disabled()) + self.assertEqual(errors,[]) + browser.close() diff --git a/tests/test_block_probe.py b/tests/test_block_probe.py new file mode 100644 index 00000000..5e90da41 --- /dev/null +++ b/tests/test_block_probe.py @@ -0,0 +1,32 @@ +"""The fstools guard must run before probing/opening candidate devices.""" +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from helpers import TOP + +class BlockProbe(unittest.TestCase): + @unittest.skipUnless(sys.platform.startswith('linux') and shutil.which('cc'), 'Linux C compiler required') + def test_device_type_allowlist(self): + with tempfile.TemporaryDirectory() as tmp: + out=str(Path(tmp)/'guard') + subprocess.run(['cc','-Wall','-Wextra','-Werror',str(TOP/'tests/block_probe_guard.c'),'-o',out],check=True) + subprocess.run([out],check=True) + + def test_guard_is_before_probe(self): + patch=(TOP/'openwrt/patches/fstools-probe-device-types.patch').read_text() + self.assertIn('+\tif (!mu300_probe_allowed(path))',patch) + guard=(TOP/'openwrt/block-probe-guard.h').read_text() + self.assertNotIn('open(',guard) + self.assertIn('/sys/dev/char/%u:%u/subsystem',guard) + + def test_rootfs_requires_patched_package(self): + source=(TOP/'openwrt/build-rootfs.sh').read_text() + self.assertIn('sh "$TOP/openwrt/build-block-mount.sh"',source) + self.assertIn('apk add --allow-untrusted /in/block-mount-mu300.apk',source) + for name in ('build-openwrt-tf-magisk.sh','make-release.sh'): + source=(TOP/'tools'/name).read_text() + self.assertIn('./etc/mu300/block-mount.build-id ',source) + self.assertIn('./sbin/block ',source) diff --git a/tests/test_mu300_i18n.py b/tests/test_mu300_i18n.py index 2db9362c..4e42b7cd 100644 --- a/tests/test_mu300_i18n.py +++ b/tests/test_mu300_i18n.py @@ -179,7 +179,7 @@ if (M.translate('删除这条短信') !== '删除这条短信') throw Error('Chi def test_visible_chinese_literals_have_translations(self): literals = [] - for name in ('home', 'at', 'locks', 'sms', 'forward', 'traffic', 'settings'): + for name in ('home', 'at', 'locks', 'sms', 'forward', 'traffic', 'settings', 'apn'): source = (PACKAGE / f'htdocs/luci-static/resources/view/mu300/{name}.js').read_text(encoding='utf-8') for line in source.splitlines(): stripped = line.lstrip() diff --git a/tools/build-openwrt-tf-magisk.sh b/tools/build-openwrt-tf-magisk.sh index 1a82c2df..95c6d402 100755 --- a/tools/build-openwrt-tf-magisk.sh +++ b/tools/build-openwrt-tf-magisk.sh @@ -65,6 +65,7 @@ MU300_GPU=0 MU300_INPUTS="$IN" MU300_MAINLINE_OUT="$UO" MU300_LUCI_PLUGIN_SRC="$ MU300_VERSION="$VERSION-tf-$KERNEL" \ sh "$TOP/openwrt/build-rootfs.sh" "$(basename "$ROOTFS")" for f in ./lib/netifd/proto/mu300cell.sh ./lib/netifd/proto/mu300cell-v6.sh \ + ./sbin/block ./lib/libblkid-tiny.so ./etc/init.d/fstab ./etc/mu300/block-mount.build-id \ ./opt/mu300/bin/mu300-keys ./opt/mu300/bin/mu300-bt-init ./opt/mu300/bin/mu300-atd ./opt/mu300/bin/mu300-at ./opt/mu300/bin/mobile-data \ ./opt/mu300/bin/mu300-user-packages ./etc/init.d/mu300-user-packages ./etc/mu300/image-packages \ ./opt/mu300/lib/wifi-channels.sh ./usr/share/ucode/wifi/hostapd.uc \ @@ -75,6 +76,8 @@ for f in ./lib/netifd/proto/mu300cell.sh ./lib/netifd/proto/mu300cell-v6.sh \ ./www/luci-static/resources/mu300/refresh.js \ ./www/luci-static/resources/view/mu300/sms.css \ ./usr/libexec/unisoc-modem/dashboard-rates \ + ./usr/libexec/unisoc-modem/apn ./usr/libexec/unisoc-modem/apn.uc ./usr/libexec/unisoc-modem/apn-identity ./etc/config/unisoc_apn \ + ./www/luci-static/resources/view/mu300/apn.js \ ./usr/libexec/unisoc-modem/lock ./usr/libexec/unisoc-modem/boot-replay ./usr/libexec/unisoc-modem/sim-scope.sh \ ./usr/libexec/unisoc-modem/lock-apply.sh ./usr/libexec/unisoc-modem/lock-jobs.sh \ ./usr/libexec/unisoc-modem/traffic ./usr/libexec/unisoc-modem/traffic-core.uc \ diff --git a/tools/make-release.sh b/tools/make-release.sh index 533df2cd..0740765d 100755 --- a/tools/make-release.sh +++ b/tools/make-release.sh @@ -91,6 +91,9 @@ for f in ./opt/mu300/bin/mu300-at ./opt/mu300/bin/mobile-data \ ./usr/libexec/unisoc-modem/lock-apply.sh ./usr/libexec/unisoc-modem/lock-jobs.sh \ ./usr/libexec/unisoc-modem/traffic ./usr/libexec/unisoc-modem/traffic-core.uc \ ./usr/libexec/unisoc-modem/hotspot ./usr/libexec/unisoc-modem/hotspot.uc \ + ./sbin/block ./lib/libblkid-tiny.so ./etc/init.d/fstab ./etc/mu300/block-mount.build-id \ + ./usr/libexec/unisoc-modem/apn ./usr/libexec/unisoc-modem/apn.uc ./usr/libexec/unisoc-modem/apn-identity ./etc/config/unisoc_apn \ + ./www/luci-static/resources/view/mu300/apn.js \ ./www/luci-static/resources/view/mu300/traffic.js ./etc/init.d/unisoc-traffic \ ./www/luci-static/resources/view/mu300/cpu.js ./etc/init.d/unisoc-cpu \ ./usr/libexec/unisoc-modem/cpu ./usr/libexec/unisoc-modem/cpu.uc \