diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..785c55f9 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,64 @@ +# 更新日志 + +## 2026-10-08 · TF 安装包 r4 + +本次提供 Linux **6.18.54** 和 **7.2.8** 两套 Magisk TF 安装包。 +以下为相对上一提交版本累积的更新;r4 已包含最新看板布局。 + +### 看板更准确、布局更顺手 + +- 修复无线客户端明明已连接,却一直显示「0 台」的问题。驱动不提供信号强度时,也会正常列出设备,不再漏计。 +- 修复「连接跟踪」一直显示「0 条」的问题。改用系统提供的实时计数,避免反复扫描整个连接列表。 +- 无线客户端和 DHCP 租约在设备信息下方左右并排,手机窄屏自动上下排列;长设备名自动换行,不再把旁边撑出大片空白。 +- 「系统」版本移动到「LAN 地址」下方。 +- ICCID 下方增加本机号码;兼容更多号码读取方式。SIM 卡或基带未提供号码时仍显示 `--`,不会猜测号码。 +- 修正 4G、5G 邻区频段识别,避免把频率重叠的频段直接误判为另一个频段。 +- 优化上下行速率曲线的上下留白,减少曲线边缘被裁切的情况。 +- 减少读取系统信息时启动的短命进程,保持原有字段含义和刷新频率。 + +### 短信保存在本机,转发更可控 + +- 优先接收并保存到本机,修复收信临时文件扫描遗漏的问题。 +- 对必须保存在 SIM 上的短信,先安全归档、核对内容,再清理对应记录,减少 SIM 满后无法继续收信的问题;不会直接清空整张卡的短信。 +- 新增短信转发页面,支持邮件、Webhook、钉钉及本机 SIM 短信转发,并提供测试发送、号码/关键词黑名单和设备备注。 +- 转发默认关闭;启用或切换渠道后,不再把此前同步进来的历史短信整批转发出去。 +- 转发模板支持中文、英文、土耳其语;短信原文、号码及用户备注保持原样。不设置每日转发额度。 +- 修复邮件服务器域名和端口输入区域的布局。 +- 电源通知仅在设备确实具备可用电池信息时提供;无电池 F50 不显示虚假的电池通知功能。 + +### 流量统计和套餐设置 + +- 新增每日流量、当月流量、套餐额度和剩余流量展示,单位按数值自动切换。 +- 支持设置月结日、每日参考额度、上传/下载/合计统计,以及已用流量补记。 +- 支持查看历史记录,独立统计,不额外占用 AT 通道。 +- 流量统计是本机估算,不替代运营商账单;额度仅用于展示和提醒,不会自动断网。突然断电可能丢失最近尚未保存的统计。 + +### 主题和指示灯 + +- 默认内置 Aurora 官方配置插件,可在「系统 → Aurora 主题设计」调整主题,附带简体中文和土耳其语翻译,英文直接可用。 +- 保持 Aurora 默认主题和看板对官方 LuCI 主题的兼容,不需要首次开机联网下载配置插件。 +- LED 设置补全多语言,信号灯和 Wi-Fi 灯可分别控制亮度及开关。 + +### TF 安装更稳妥 + +- 格式化使用所选 TF 分区的全部容量,不再限制为 32 GiB;采用延后初始化等方式减少大容量卡安装时的格式化等待。 +- 安装前检查包完整性、空间、文件数量及设备所需文件;安装后核对关键文件、启动镜像和启动设置。 +- 修复已有 Linux 分区被 Android 标记为「无法挂载」时,误报 `vold did not release TF` 的情况,同时保留实际占用检查。 +- 修复已退出进程留下的挂载信息被误判为 TF 仍被占用的问题。 +- 增加安装进度、日志和超时退出,失败后不继续写入后续启动内容,减少无提示地长时间卡住。 +- 保留安装到 Android 当前槽位另一侧的逻辑,并加强写入后的核验;保护当前 Android 启动槽。 +- TF 启动明确指定从 SD 卡加载,避免安装异常时错误寻找机内存储作为替代目标。 +- 改善 Magisk 安装收尾兼容性,保留详细错误信息,便于定位真正失败的阶段。 + +### 内核和构建检查 + +- 6.18、7.2 构建补齐 KVM 与容器所需的内核配置和相关模块,并增加内核、模块与 rootfs 一致性检查。 +- 这不等于默认安装或启用 Docker、QEMU,也不代表所有设备的硬件虚拟化已完成实测。 +- r4 两份安装包已校验 ZIP 完整性、SHA-256、TF 启动标记及 40 个插件/功能文件与仓库源码的一致性。 + +### 安装前请注意 + +- **仍是全新安装,会格式化所选 TF 分区,不是保留个人数据的升级包。请先备份配置和数据。** +- 安装异常后应先重启 Android 再重试,并保留安装日志;不要在仍显示安装中时断电或重启。 +- 软件保护无法消除坏卡、接触不良或断电造成的风险。 +- 本次根目录保留 `20261008-r4` 两份安装包及其 `.sha256` 校验文件;旧包已移入本地 `backup/tf-packages-before-20261008-r4/`,可自行取回,不随源码提交。 diff --git a/android/magisk/mu300-linux-switch/switch.sh b/android/magisk/mu300-linux-switch/switch.sh index c2761a57..d2cfb357 100755 --- a/android/magisk/mu300-linux-switch/switch.sh +++ b/android/magisk/mu300-linux-switch/switch.sh @@ -138,8 +138,7 @@ tmp=${TMPDIR:-/data/local/tmp}/mu300-bc.bin $BB printf "$(echo "$new" | sed 's/../\\x&/g')" > "$tmp" || die "could not build the block file" [ "$($BB stat -c %s "$tmp")" = 32 ] || { rm -f "$tmp"; die "the block file is not 32 bytes"; } -dd if="$tmp" of="$MISC" bs=1 seek="$BC_OFFSET" conv=notrunc 2>/dev/null || { rm -f "$tmp"; die "writing misc failed"; } -sync +$BB dd if="$tmp" of="$MISC" bs=1 seek="$BC_OFFSET" conv=notrunc,fsync 2>/dev/null || { rm -f "$tmp"; die "writing misc failed"; } rm -f "$tmp" back=$(hex_of "$MISC" "$BC_OFFSET" 32) diff --git a/android/magisk/mu300-openwrt-tf/customize.sh b/android/magisk/mu300-openwrt-tf/customize.sh index c390b057..0b953584 100755 --- a/android/magisk/mu300-openwrt-tf/customize.sh +++ b/android/magisk/mu300-openwrt-tf/customize.sh @@ -40,25 +40,15 @@ KERNEL=7.2 PWHASH='' EOF ui_msg "- 正在将 OpenWrt 根文件系统安装到 $R" "- Installing OpenWrt rootfs to $R" +# Use init's namespace: Magisk's private mounts must not hide vold's aliases. +# A subprocess also isolates traps/options from Magisk's own final cleanup. +mkdir -p /data/local/tmp/mu300-tf-install MU300_PAYLOAD_DIR="$MODPATH" MU300_INSTALL_TMP=/data/local/tmp/mu300-tf-install \ -MU300_VENDOR_FROM_DEVICE=1 MU300_KEEP_PAYLOAD=1 \ - sh "$MODPATH/android-install.sh" || ui_fail "! TF 卡根文件系统安装失败;启动分区未改动" \ - "! TF rootfs installation failed; boot partitions were not changed" -IMG=$MODPATH/boot-linux.img -want=$(cat "$MODPATH/boot-linux.sha256") -have=$("$BB" sha256sum "$IMG" | "$BB" cut -d' ' -f1) -[ "$have" = "$want" ] || ui_fail "! 安装包中的启动镜像校验失败" "! packaged boot image checksum mismatch" -ui_msg "- 正在写入并校验 boot_$linux_slot" "- Writing and verifying boot_$linux_slot" -"$BB" dd if="$IMG" of="$bootdev" bs=4M 2>/dev/null || ui_fail "! 写入 boot_$linux_slot 失败" "! writing boot_$linux_slot failed" -sync -bytes=$("$BB" stat -c %s "$IMG") -back=$("$BB" dd if="$bootdev" bs=1M count=$(( (bytes + 1048575) / 1048576 )) 2>/dev/null | \ - "$BB" head -c "$bytes" | "$BB" sha256sum | "$BB" cut -d' ' -f1) -[ "$back" = "$want" ] || ui_fail "! boot_$linux_slot 校验失败;misc 未改动" \ - "! boot_$linux_slot verification failed; misc was not changed" -ui_msg "- 正在设置下次从 $linux_slot 槽位启动" "- Arming slot $linux_slot" -MU300_BUSYBOX="$BB" MAGISKTMP=${MAGISKTMP:-/data/adb/magisk} \ - sh "$MODPATH/switch.sh" --no-reboot || ui_fail "! 无法设置启动槽位" "! boot slot could not be armed" +MU300_VENDOR_FROM_DEVICE=1 MU300_KEEP_PAYLOAD=1 MU300_BUSYBOX="$BB" \ +MU300_TF_BOOTDEV="$bootdev" MAGISKTMP=${MAGISKTMP:-/data/adb/magisk} \ + "$BB" nsenter -t 1 -m "$BB" sh "$MODPATH/tf-install-worker.sh" || \ + ui_fail "! 安装未完成,已停止后续步骤。请保留 /data/local/tmp/mu300-tf-install 日志并重启 Android 后再试" \ + "! Installation incomplete; subsequent stages stopped. Keep /data/local/tmp/mu300-tf-install logs and reboot Android before retrying" ui_msg "- 安装完成;重启后进入 OpenWrt" "- Installation complete; reboot to enter OpenWrt" ui_msg "- 如果 Linux 启动失败,设备会自动返回 Android" \ "- A failed Linux boot automatically returns to Android" diff --git a/boot/build-boot-image.py b/boot/build-boot-image.py index f5735a37..a47cb932 100755 --- a/boot/build-boot-image.py +++ b/boot/build-boot-image.py @@ -127,6 +127,8 @@ def main(): 'ones of the same name when it runs on that device') ap.add_argument('--device', help='the device this image is for (f50, u30air): written to /etc/mu300-device, ' 'which init trusts over its own guess from the device tree') + ap.add_argument('--root-target', choices=['sd'], + help='TF-only device segment: never probe an internal eMMC root when TF fails') ap.add_argument('--trial-guard', type=int, metavar='SECONDS', help='for experiments only: reboot SECONDS after switch_root unless /run/stay exists (with a ' 'one-shot trial, that is back to Android when the kernel boots without USB)') @@ -180,6 +182,12 @@ def main(): files['linux-modules/' + name] = ((a.modules / name).read_bytes(), stat.S_IFREG | 0o644) if a.trial_guard and a.generic_ramdisk: ap.error('--trial-guard does not go into a generic ramdisk') + if a.root_target: + if a.generic_ramdisk: + ap.error('--root-target does not go into a generic ramdisk') + # Deliberately absent from generic updates: keep the install target + # from the device segment when concatenating a new generic ramdisk. + files['etc/mu300-root-target'] = (a.root_target.encode() + b'\n', stat.S_IFREG | 0o644) if a.device: # only in the device segment: a generic segment is the same for every device if a.generic_ramdisk: diff --git a/boot/init b/boot/init index aaaaf36a..4837dd67 100644 --- a/boot/init +++ b/boot/init @@ -175,10 +175,10 @@ find_partitions() { write_misc_bc() { # write_misc_bc FILE STAGE [ -n "$misc" ] || { log "stage=misc-NOT-FOUND"; return 1; } - dd if="$1" of="$misc" bs=1 seek=2048 conv=notrunc 2>/dev/null - sync - dd if="$misc" of=/run/bc.bin bs=1 skip=2048 count=32 2>/dev/null - if cmp -s /run/bc.bin "$1"; then log "stage=$2 dev=$misc"; else log "stage=$2-MISMATCH dev=$misc"; fi + dd if="$1" of="$misc" bs=1 seek=2048 conv=notrunc,fsync 2>/dev/null || return 1 + dd if="$misc" of=/run/bc.bin bs=512 skip=4 count=1 2>/dev/null || return 1 + head -c 32 /run/bc.bin > /run/bc-check.bin + if cmp -s /run/bc-check.bin "$1"; then log "stage=$2 dev=$misc"; else log "stage=$2-MISMATCH dev=$misc"; return 1; fi } restore_android() { if [ "$linux_slot" = a ]; then @@ -368,12 +368,32 @@ ROOT_OFFSET=27762098176 # linux-boot/rootfs-region.env; outside every GPT part # this file - with the default above. Devices whose region is elsewhere then booted into standalone mode and went # back to Android. So find it the way the installer places it - the first 2 MiB boundary after the last partition # - and take the first candidate that really holds the mu300root filesystem (ext4 magic and label). -is_mu300root() { # is_mu300root OFFSET; loop setup seeks instead of reading through tens of GiB - probe=$(losetup -f 2>/dev/null) || return 1 - losetup -o "$1" "$probe" /dev/mmcblk0 2>/dev/null || return 1 - magic=$(dd if="$probe" bs=1 skip=1080 count=2 2>/dev/null | od -An -tx1 | tr -d ' \n') - label=$(dd if="$probe" bs=1 skip=1144 count=9 2>/dev/null) - losetup -d "$probe" 2>/dev/null +root_region_valid() { + # Validate both GPT boundaries BEFORE dd or losetup. Some Android MMC + # drivers wedge on out-of-device reads instead of returning an error (#65). + case $1 in ''|*[!0-9]*) return 1 ;; esac + disk_sectors=$(cat /sys/block/mmcblk0/size) || return 1 + case $disk_sectors in ''|*[!0-9]*) return 1 ;; esac + [ "$1" -gt 0 ] && [ $(( $1 % 512 )) -eq 0 ] || return 1 + root_sector=$(( $1 / 512 )); partition_end=0 + for partition in /sys/block/mmcblk0/mmcblk0p*; do + [ -r "$partition/start" ] || continue + part_start=$(cat "$partition/start") || return 1 + part_size=$(cat "$partition/size") || return 1 + case $part_start:$part_size in *[!0-9:]*|:*|*:) return 1 ;; esac + part_end=$((part_start + part_size)) + [ "$part_end" -le "$partition_end" ] || partition_end=$part_end + done + [ "$partition_end" -gt 0 ] && [ "$root_sector" -ge "$partition_end" ] || return 1 + [ "$root_sector" -le $((disk_sectors - 34 - 8)) ] || return 1 + root_bytes=$(( (disk_sectors - 34 - root_sector) * 512 )) +} +is_mu300root() { + root_region_valid "$1" || return 1 + dd if=/dev/mmcblk0 of=/run/root-super bs=512 skip="$root_sector" count=8 2>/dev/null || return 1 + [ "$(wc -c < /run/root-super)" -eq 4096 ] || return 1 + magic=$(dd if=/run/root-super bs=1 skip=1080 count=2 2>/dev/null | od -An -tx1 | tr -d ' \n') + label=$(dd if=/run/root-super bs=1 skip=1144 count=9 2>/dev/null) [ "$magic" = 53ef ] && [ "$label" = mu300root ] } find_root_offset() { @@ -388,16 +408,22 @@ find_root_offset() { done return 1 } -# Prefer an ext4 TF filesystem labelled mu300sd. A missing/foreign card costs -# at most the short device-enumeration window and falls back to internal eMMC. +# A TF-only image must never fall through to the eMMC free-region probe. +root_target=$(cat /etc/mu300-root-target 2>/dev/null) +# Generic images retain the bounded internal-root fallback. sd_root= for n in $(seq 1 8); do seen= for d in /dev/mmcblk[1-9]p1 /dev/mmcblk[1-9]; do [ -b "$d" ] || continue seen=1 - magic=$(dd if="$d" bs=1 skip=1080 count=2 2>/dev/null | od -An -tx1 | tr -d ' \n') - label=$(dd if="$d" bs=1 skip=1144 count=16 2>/dev/null | tr -d '\000') + sectors=$(cat "/sys/class/block/${d##*/}/size" 2>/dev/null) + case $sectors in ''|*[!0-9]*) continue ;; esac + [ "$sectors" -ge 8 ] || continue + dd if="$d" of=/run/sd-super bs=512 count=8 2>/dev/null || continue + [ "$(wc -c < /run/sd-super)" -eq 4096 ] || continue + magic=$(dd if=/run/sd-super bs=1 skip=1080 count=2 2>/dev/null | od -An -tx1 | tr -d ' \n') + label=$(dd if=/run/sd-super bs=1 skip=1144 count=16 2>/dev/null | tr -d '\000') [ "$magic" = 53ef ] && [ "$label" = mu300sd ] && { sd_root=$d; break 2; } done [ -n "$seen" ] && break @@ -416,12 +442,14 @@ if [ -n "$sd_root" ]; then fi [ "$root_mounted" = 1 ] && read_usb_boot_policy setup_usb_gadget -if [ -z "$sd_root" ]; then +internal_root= +if [ "$root_mounted" = 0 ] && [ "$root_target" != sd ]; then if found=$(find_root_offset); then [ "$found" = "$ROOT_OFFSET" ] || log "stage=root-offset found=$found (default $ROOT_OFFSET)" ROOT_OFFSET=$found + internal_root=1 else - log "stage=root-offset not-found (trying the default $ROOT_OFFSET)" + log "stage=root-offset not-found (no internal mount attempted)" fi fi mkdir -p /newroot @@ -438,11 +466,10 @@ pick_root() { [ "$os" = ubuntu ] && [ -x /disk/lib/systemd/systemd ] && { echo /disk; return; } done } -if [ "$root_mounted" = 0 ]; then +if [ "$root_mounted" = 0 ] && [ "$internal_root" = 1 ] && root_region_valid "$ROOT_OFFSET"; then rootloop=$(losetup -f 2>/run/rootmount.err) - if [ -n "$rootloop" ] && losetup -o $ROOT_OFFSET "$rootloop" /dev/mmcblk0 2>>/run/rootmount.err \ + if [ -n "$rootloop" ] && losetup -o "$ROOT_OFFSET" -S "$root_bytes" "$rootloop" /dev/mmcblk0 2>>/run/rootmount.err \ && [ "$(cat /sys/block/${rootloop#/dev/}/loop/offset)" = "$ROOT_OFFSET" ] \ - && [ "$(dd if="$rootloop" bs=1 skip=1080 count=2 2>/dev/null | od -An -tx1 | tr -d ' ')" = 53ef ] \ && mount -t ext4 -o noatime "$rootloop" /disk 2>>/run/rootmount.err; then root_mounted=1 fi @@ -537,6 +564,13 @@ if [ "$root_mounted" = 1 ] && rootdir=$(pick_root) && [ -n "$rootdir" ]; then fi log "stage=rootfs-unavailable $(cat /run/rootmount.err)" restore_android +if [ "$root_target" = sd ]; then + log 'stage=tf-root-unavailable (returning to Android; eMMC root probe skipped)' + # Do not enter the vendor/standalone diagnostic boot on a missing TF root. + # No extra global sync into the failed TF; restore_android verifies misc. + reboot -f + while :; do sleep 1; done +fi ifconfig usb0 $NET.1 netmask 255.255.255.0 up log "stage=usb0 $(ifconfig usb0 2>&1 | head -1)" cat > /etc/udhcpd.conf </dev/null +adb push "$TOP/tools/android-mount-mu300root.sh" "$TOP/tools/android-install.sh" "$TOP/tools/tf-storage.sh" $T/ >/dev/null for os in $OSES; do if [ $MODE = prebuilt ]; then adb push "$REL/$(rootfs_file $os)" $T/mu300-$os.tar.gz >/dev/null diff --git a/mu300-linux-openwrt-tf-6.18-20261008-r4.zip.sha256 b/mu300-linux-openwrt-tf-6.18-20261008-r4.zip.sha256 new file mode 100644 index 00000000..4bc327ae --- /dev/null +++ b/mu300-linux-openwrt-tf-6.18-20261008-r4.zip.sha256 @@ -0,0 +1 @@ +74085191aade9af7247ea6c4a935b7a1cca04b2d286db77aa883e7eaf1cb69e1 mu300-linux-openwrt-tf-6.18-20261008-r4.zip diff --git a/mu300-linux-openwrt-tf-7.2-20261008-r4.zip.sha256 b/mu300-linux-openwrt-tf-7.2-20261008-r4.zip.sha256 new file mode 100644 index 00000000..00fd04a6 --- /dev/null +++ b/mu300-linux-openwrt-tf-7.2-20261008-r4.zip.sha256 @@ -0,0 +1 @@ +0554c2028de3fe6f081671988d9c78debc9dfc6fbb3318653de2e24f71d4c191 mu300-linux-openwrt-tf-7.2-20261008-r4.zip diff --git a/openwrt/AURORA.md b/openwrt/AURORA.md new file mode 100644 index 00000000..8b685a0c --- /dev/null +++ b/openwrt/AURORA.md @@ -0,0 +1,24 @@ +# Built-in Aurora packages + +`build-rootfs.sh` installs the official Aurora theme 1.4.0 and its configuration +app 1.2.5 into the rootfs. This is shared by TF and other OpenWrt installation +methods using this builder. Bootstrap remains available; Aurora remains the +default theme. + +The configuration app is available under **System → Aurora Theme Design**. +English is built into the app; Chinese (Simplified) and Turkish translation +packages are included. No first-boot package download is needed. + +Official source and pinned release: + +- https://github.com/eamonxg/luci-app-aurora-config/releases/tag/v1.2.5 +- `aurora-config-packages.sha256` pins the three official release assets. + +Downloads are cached under `work/` and verified before installation. To update, +review the upstream theme/config compatibility, update the release URL, package +mounts and checksum manifest together, then rebuild. Missing UI, menu, ACL or +translation files fail both rootfs and TF package validation. + +The MU300 dashboard remains a separate plugin and does not depend on this +configuration app. Its existing Aurora and standard LuCI theme support is +unchanged. diff --git a/openwrt/aurora-config-packages.sha256 b/openwrt/aurora-config-packages.sha256 new file mode 100644 index 00000000..522bc2b5 --- /dev/null +++ b/openwrt/aurora-config-packages.sha256 @@ -0,0 +1,3 @@ +e290ef9465615d92b5d8baaeacb68a0b5f59edcc647895fa691fc2a3c81b6669 luci-app-aurora-config-1.2.5-r20260920.apk +65de0bfda210c1e13df54749627342aea555fa9a01b363f4263ddba7d257b46b luci-i18n-aurora-config-zh-cn-26.262.58276.362887a.apk +2d11e934ec9d3efd4af4b6a8adc3ed10d2e9ea8c1b417cf55fe153ad1df66a3a luci-i18n-aurora-config-tr-26.262.58276.362887a.apk diff --git a/openwrt/build-rootfs.sh b/openwrt/build-rootfs.sh index 7b55bd7b..eb72e57b 100755 --- a/openwrt/build-rootfs.sh +++ b/openwrt/build-rootfs.sh @@ -22,6 +22,9 @@ TOP=$(cd "$(dirname "$0")/.." && pwd) # build inputs (out/, firmware/, android-subset/, tools binaries, busybox) may live outside the checkout IN=${MU300_INPUTS:-$TOP} MAINLINE=${MU300_MAINLINE_OUT:-$IN/upstream/out} +if [ -d "$MAINLINE/modules" ]; then + python3 "$TOP/upstream/check-container-support.py" "$MAINLINE" +fi for f in mu300cell.sh mu300cell-v6.sh; do [ -s "$TOP/openwrt/overlay/lib/netifd/proto/$f" ] || { echo "required cellular protocol helper missing: $f" >&2; exit 1; @@ -52,6 +55,30 @@ theme_hash=$(sha256sum "$THEME_APK" | cut -d' ' -f1) [ "$theme_hash" = "$THEME_SHA" ] || { echo "Aurora APK checksum mismatch: $THEME_APK" >&2; exit 1; } +# Install the matching official configuration UI and translations at build +# time, not from a first-boot download. Unique temporary names allow concurrent +# 6.x/7.x builds to share this verified download cache safely. +AURORA_CONFIG_BASE=https://github.com/eamonxg/luci-app-aurora-config/releases/download/v1.2.5 +mkdir -p "$TOP/work" +while read -r expected package; do + [ -n "$package" ] || continue + cached="$TOP/work/$package" + if [ ! -s "$cached" ]; then + partial=$(mktemp "$cached.part.XXXXXX") + if ! curl -fL -o "$partial" "$AURORA_CONFIG_BASE/$package"; then + rm -f "$partial"; exit 1 + fi + actual=$(sha256sum "$partial" | cut -d' ' -f1) + [ "$actual" = "$expected" ] || { + rm -f "$partial"; echo "Aurora config APK checksum mismatch: $package" >&2; exit 1; + } + mv "$partial" "$cached" + fi + actual=$(sha256sum "$cached" | cut -d' ' -f1) + [ "$actual" = "$expected" ] || { + echo "Aurora config APK checksum mismatch: $package" >&2; exit 1; + } +done < "$TOP/openwrt/aurora-config-packages.sha256" TARBALL=$FLAVOUR-$VER-armsr-armv8-rootfs.tar.gz URL=$BASEURL/$VER/targets/armsr/armv8 @@ -92,15 +119,20 @@ docker run --rm --platform linux/arm64 \ $(opt firmware firmware) $(opt android-subset android-subset) $(opt android-gpu-subset android-gpu-subset) \ $(opt tools/logdw/logdw logdw) $(opt tools/bt-init/mu300-bt-init bt-init) $(opt tools/keys/mu300-keys keys) $(opt tools/gpu/cltest cltest) \ $(opt busybox busybox) $(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 "$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 \ -e KREL=$KREL -e OUT="$(basename "$OUT")" -e MU300_VERSION="${MU300_VERSION:-dev}" mu300-$FLAVOUR-base:$VER /bin/sh -eu -c ' mkdir -p /var/lock /var/run /tmp apk update >/dev/null # openssl-util: mu300-vpn fetches the VPN server certificate with it to pin, for links that ask for allowInsecure; # 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 \ +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 \ i2c-tools gpiod-tools >/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 apk del procd-ujail procd-seccomp >/dev/null 2>&1 || true # online firmware upgrades flash whole-disk armsr images: that would overwrite the eMMC, so remove them @@ -122,6 +154,12 @@ printf "mu300\n" > $R/etc/hostname # the real one comes from uci (etc/uci-defa cp -a /in/opt-mu300 $R/opt/mu300 cp -a /in/overlay/. $R/ [ -s $R/www/luci-static/aurora/main.css ] || { echo "Aurora theme assets missing" >&2; exit 1; } +for f in www/luci-static/resources/view/aurora/studio.js \ + www/luci-static/resources/view/aurora/marketplace.js \ + usr/share/luci/menu.d/luci-app-aurora.json usr/share/rpcd/acl.d/luci-app-aurora.json \ + usr/lib/lua/luci/i18n/aurora-config.zh-cn.lmo usr/lib/lua/luci/i18n/aurora-config.tr.lmo; do + [ -s "$R/$f" ] || { echo "Aurora config required file missing: $f" >&2; exit 1; } +done grep -q "mediaurlbase .*/luci-static/aurora" $R/etc/config/luci || { echo "Aurora theme is not the LuCI default" >&2; exit 1; } @@ -133,7 +171,7 @@ patch --batch --fuzz=0 -d $R -p1 -i /in/fw4-sipa-offload.patch 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-modem-ui $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/* + 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/ # The source-tree install does not run the package postinst. Register only @@ -184,17 +222,28 @@ done if [ -d /in/luci-plugin ]; then n=$(sed -n "s/^START=//p" $R/etc/init.d/unisoc-modem-ui) ln -sf ../init.d/unisoc-modem-ui $R/etc/rc.d/S$n"unisoc-modem-ui" + n=$(sed -n "s/^START=//p" $R/etc/init.d/unisoc-sms-forward) + ln -sf ../init.d/unisoc-sms-forward $R/etc/rc.d/S$n"unisoc-sms-forward" + n=$(sed -n "s/^START=//p" $R/etc/init.d/unisoc-traffic) + ln -sf ../init.d/unisoc-traffic $R/etc/rc.d/S$n"unisoc-traffic" + ln -sf ../init.d/unisoc-traffic $R/etc/rc.d/K01unisoc-traffic fi # busybox PATH is /usr/sbin:/usr/bin:/sbin:/bin, so the commands go into /usr/bin for c in mu300-toolkit mu300-next-boot mu300-os mu300-update mobile-data mu300-at mu300-sms led-status mu300-vpn wifi-client mu300-ttl mu300-wifi-band mu300-led mu300-usb mu300-nfc; do ln -sf /opt/mu300/bin/$c $R/usr/bin/$c; done # no kernel of its own: OpenWrt kmods (6.12) and grub are unused on this device rm -rf $R/lib/modules/6.* $R/boot -# out-of-tree modules for the experimental mainline kernel (upstream/) +# In-tree and vendor modules for the selected mainline kernel (upstream/). if ls /in/mainline-modules/*.ko >/dev/null 2>&1; then # the release the modules were built for (their vermagic), not a version written down here krel=$(for f in /in/mainline-modules/*.ko; do tr "\0" "\n" < $f | sed -n "s/^vermagic=\([^ ]*\) .*/\1/p"; break; done) [ -n "$krel" ] && mkdir -p $R/lib/modules/$krel && cp /in/mainline-modules/*.ko $R/lib/modules/$krel/ + for f in modules.builtin modules.builtin.modinfo; do + [ ! -f /in/mainline-$f ] || cp /in/mainline-$f $R/lib/modules/$krel/$f + done fi cd $R && tar -czf /out/$OUT . ls -la /out/$OUT' +if [ -d "$MAINLINE/modules" ]; then + python3 "$TOP/upstream/check-container-support.py" "$MAINLINE" --rootfs "$TOP/openwrt/$(basename "$OUT")" +fi rm -rf "$REGDB" diff --git a/openwrt/luci-app-mu300/Makefile b/openwrt/luci-app-mu300/Makefile index 8c5f3574..af2fb614 100644 --- a/openwrt/luci-app-mu300/Makefile +++ b/openwrt/luci-app-mu300/Makefile @@ -1,8 +1,8 @@ include $(TOPDIR)/rules.mk PKG_NAME:=luci-app-mu300 -PKG_VERSION:=1.0.1 -PKG_RELEASE:=3 +PKG_VERSION:=1.1.0 +PKG_RELEASE:=1 PKG_LICENSE:=MIT PKG_MAINTAINER:=MU300 Linux contributors PKGARCH:=all @@ -14,7 +14,7 @@ define Package/luci-app-mu300 CATEGORY:=LuCI SUBMENU:=3. Applications TITLE:=Unisoc modem control center - DEPENDS:=+luci-base +rpcd +jsonfilter + DEPENDS:=+luci-base +rpcd +jsonfilter +curl +ca-bundle +openssl-util +msmtp +ucode +ucode-mod-fs +ucode-mod-ubus +ucode-mod-uci +ucode-mod-uloop endef define Package/luci-app-mu300/description @@ -34,7 +34,7 @@ define Package/luci-app-mu300/install $(INSTALL_DIR) $(1)/www $(CP) ./htdocs/. $(1)/www/ $(CP) ./root/. $(1)/ - chmod 0755 $(1)/etc/init.d/unisoc-modem-ui $(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/* + 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 $(CP) ./lmo/. $(1)/usr/lib/lua/luci/i18n/ endef @@ -55,6 +55,10 @@ define Package/luci-app-mu300/postinst /etc/init.d/rpcd restart 2>/dev/null || true /etc/init.d/unisoc-modem-ui enable 2>/dev/null || true /etc/init.d/unisoc-modem-ui start 2>/dev/null || true + /etc/init.d/unisoc-sms-forward enable 2>/dev/null || true + /etc/init.d/unisoc-sms-forward start 2>/dev/null || true + /etc/init.d/unisoc-traffic enable 2>/dev/null || true + /etc/init.d/unisoc-traffic start 2>/dev/null || true } exit 0 endef @@ -65,6 +69,10 @@ define Package/luci-app-mu300/postrm if [ "$$1" = remove ]; then /etc/init.d/unisoc-modem-ui stop 2>/dev/null || true /etc/init.d/unisoc-modem-ui disable 2>/dev/null || true + /etc/init.d/unisoc-sms-forward stop 2>/dev/null || true + /etc/init.d/unisoc-sms-forward disable 2>/dev/null || true + /etc/init.d/unisoc-traffic stop 2>/dev/null || true + /etc/init.d/unisoc-traffic disable 2>/dev/null || true rm -f /etc/unisoc-modem/usb-boot.conf fi rm -f /tmp/luci-indexcache /tmp/luci-modulecache/* 2>/dev/null diff --git a/openwrt/luci-app-mu300/README.md b/openwrt/luci-app-mu300/README.md index 63651cc9..15ab4bb5 100644 --- a/openwrt/luci-app-mu300/README.md +++ b/openwrt/luci-app-mu300/README.md @@ -34,10 +34,82 @@ The SMS page uses `sms_command`, whose CLI contract is the existing `mu300-sms` interface: `list`, `show`, `send`, `delete` and `sync`. This keeps SIM storage details out of LuCI and lets each firmware supply its own adapter. +## SMS forwarding + +The separate SMS forwarding page offers HTTPS webhook, DingTalk, TLS-verified +SMTP and local-SIM SMS destinations, plus optional device information, a device +note, phone/keyword blocklists, power notifications and a confirmed test send. +The feature is off by default. Its procd worker reads the local SMS pool only; +it does not open an AT port, invoke a SIM sync or delay boot. On first enable or +channel change it records the current pool ID before accepting new messages. +It stores each message's progress before delivery, so a restart or failed +delivery cannot replay old SMS. Blocked SMS are marked processed as well. + +The adapter records `source: direct` for live `+CMT` delivery and `source: sim` +for SIM imports. `received` is the local insertion time, not proof of a new SMS. +SIM imports (including legacy records without `source`) are forwarded only if +their original `scts` is at or after the enable/channel-change barrier. This +retains delayed synchronization of new messages without mailing pre-enable +SIM history. SCTS must include its UTC offset: AT `yy/mm/dd,hh:mm:ss+qq` +(quarter-hours), or PDU `YYYY-MM-DD hh:mm:ss+hh:mm`. Unknown dates and undecoded +SIM PDUs remain in the inbox but are not automatically forwarded. Direct +delivery uses its local insertion time, allowing delayed SMSC delivery. +This does not change transport failures: failed SMTP/webhook submissions are +reported but are not automatically retried. + +The template language (Chinese, English or Turkish) is saved independently of +the browser session and used for message subjects, generated text, device-info +labels, tests and power notifications. Until saved, the editor offers the current +UI language; older configurations keep Chinese output. Original SMS bodies, +sender IDs, device notes and webhook JSON keys are never translated. SMTP +subjects use UTF-8 RFC 2047 encoding. + +Private settings and replay state are in +`/etc/unisoc-modem/forward/` (0700 directory, 0600 files); passwords never +appear in the editor response or routine status polling. The package requires +`curl`, `msmtp`, a CA bundle and `openssl-util` for the TLS destinations. The source-tree +TF rootfs builder installs those tools explicitly. The SMS adapter must expose +a persistent `msg/` pool with the `next_id` and message-header format used by +`mu300-sms`; a different firmware can supply that adapter via +`unisoc_modem.main.sms_pool` and `sms_command`. + +Power notifications are selectable only if a real `battery` power-supply +reports presence, capacity and charge state. Battery-less F50 builds leave +this option unavailable rather than forwarding the SC27xx fuel gauge's +unreliable phantom reading. The local SMS path is limited to one 70-unit +UCS-2 part by the existing MU300 adapter. There is no daily forwarding quota. + Network interface and state paths are also configured in the same UCI section; none of the web code requires `sipa_eth0`, `wan`, `br-lan` or `/opt/mu300` from the host firmware. +## Data plan accounting + +The data-plan page records the selected cellular WAN interface's RX/TX byte +counters in an independent ucode/uloop worker. It samples every ten seconds +without opening AT channels or running a shell per sample. The dashboard reads +the worker's atomic RAM snapshot, so its refresh rate does not drive accounting. +The interface follows the existing adapter settings and netifd by default; a +device override is available for other firmware layouts. + +Settings include a plan name, monthly-cycle and daily-reference allowances in +decimal GB, RX/TX/combined accounting, and a monthly reset day from 1 to 31. +Short months clamp the reset to their last day, in the device timezone. A usage +adjustment can account for traffic consumed before installing the plugin; it +expires at the next cycle and does not alter measured day/month history. Quotas +display usage warnings only and do not disconnect the network. + +The worker retains 93 daily and 24 calendar-month buckets, showing the latest +31 days and 12 months. It checkpoints to `/etc/unisoc-modem/traffic/state.json` +every 60 seconds and at a clean stop; abrupt power loss can lose recent unsaved +samples. Package upgrades leave the database intact, and a sysupgrade keep rule +includes it. Initial activation establishes a baseline rather than inventing +earlier daily history. Counter resets and interface recreation are handled; +statistics are local estimates and may differ from carrier billing. + +Accounting boundary tests can run on OpenWrt with: +`TZ=UTC0 ucode -L /usr/libexec/unisoc-modem tests/traffic_core.uc`. + ## Persistent locks The package owns `/etc/init.d/unisoc-modem-ui`. It starts a non-blocking procd 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 b9914263..8983372e 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 @@ -25,6 +25,12 @@ var callSmsShow = rpc.declare({ object: 'mu300dash', method: 'sms_show', params: var callSmsSend = rpc.declare({ object: 'mu300dash', method: 'sms_send', params: [ 'num', 'text' ], expect: { '': {} } }); var callSmsDel = rpc.declare({ object: 'mu300dash', method: 'sms_delete', params: [ 'id', 'sim' ], expect: { '': {} } }); var callSmsSync = rpc.declare({ object: 'mu300dash', method: 'sms_sync', expect: { '': {} } }); +var callForwardGet = rpc.declare({ object: 'mu300dash', method: 'forward_get', expect: { '': {} } }); +var callForwardStatus = rpc.declare({ object: 'mu300dash', method: 'forward_status', expect: { '': {} } }); +var callForwardSet = rpc.declare({ object: 'mu300dash', method: 'forward_set', params: [ 'payload' ], expect: { '': {} } }); +var callForwardTest = rpc.declare({ object: 'mu300dash', method: 'forward_test', expect: { '': {} } }); +var callTrafficGet = rpc.declare({ object: 'mu300dash', method: 'traffic_get', expect: { '': {} } }); +var callTrafficSet = rpc.declare({ object: 'mu300dash', method: 'traffic_set', params: [ 'payload' ], expect: { '': {} } }); var callUsbGet = rpc.declare({ object: 'mu300dash', method: 'usb_get', expect: { '': {} } }); var callUsbSet = rpc.declare({ object: 'mu300dash', method: 'usb_set', params: [ 'kind', 'value', 'scope', 'auto' ], expect: { '': {} } }); var callUsbNetList = rpc.declare({ object: 'mu300dash', method: 'usb_net_list', expect: { '': {} } }); @@ -34,6 +40,125 @@ 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 = { + '本机号码': ['Phone number', 'Telefon numarası'], + '流量池': ['Data plan', 'Veri paketi'], + '今日流量': ['Today’s data', 'Bugünkü veri'], + '当月流量': ['This month’s data', 'Bu ayki veri'], + '自然月统计': ['Calendar-month usage', 'Takvim ayı kullanımı'], + '套餐周期已用': ['Used this billing cycle', 'Bu dönemde kullanılan'], + '套餐剩余': ['Plan remaining', 'Pakette kalan'], + '套餐与流量池': ['Plan and data allowance', 'Paket ve veri kotası'], + '套餐名称': ['Plan name', 'Paket adı'], + '每周期额度(GB)': ['Allowance per cycle (GB)', 'Dönem kotası (GB)'], + '每日参考额度(GB)': ['Daily reference allowance (GB)', 'Günlük referans kotası (GB)'], + '每月重置日(1–31)': ['Monthly reset day (1–31)', 'Aylık sıfırlama günü (1–31)'], + '套餐计量方式': ['Plan accounting', 'Paket hesaplama yöntemi'], + '上下行合计': ['Download + upload', 'İndirme + yükleme'], + '仅下行': ['Download only', 'Yalnızca indirme'], + '仅上行': ['Upload only', 'Yalnızca yükleme'], + '额度为 0 表示不限量;1 GB = 1000 MB。重置日在设备当地时间零点生效,短月份使用当月最后一天。': ['Set 0 for unlimited; 1 GB = 1000 MB. Reset takes place at midnight in the device timezone; shorter months use their last day.', 'Sınırsız için 0 girin; 1 GB = 1000 MB. Sıfırlama cihazın yerel saatine göre gece yarısı yapılır; kısa aylarda ayın son günü kullanılır.'], + '统计网卡': ['Accounting interface', 'İstatistik arayüzü'], + '自动使用蜂窝 WAN 网卡': ['Use the cellular WAN interface automatically', 'Hücresel WAN arayüzünü otomatik kullan'], + '校准本周期已用(GB,可选)': ['Adjust used data this cycle (GB, optional)', 'Bu dönem kullanılan veriyi düzelt (GB, isteğe bağlı)'], + '留空保持现有统计': ['Leave blank to keep existing usage', 'Mevcut kullanımı korumak için boş bırakın'], + '校准只调整当前套餐周期,不修改每日和自然月历史;下个周期自动恢复实际统计。': ['Adjustments affect only the current billing cycle, not daily or calendar-month history. The next cycle uses measured data again.', 'Düzeltme yalnızca mevcut paket dönemini etkiler; günlük ve takvim ayı geçmişi değişmez. Sonraki dönemde ölçülen veri kullanılır.'], + '最近每日用量': ['Recent daily usage', 'Son günlük kullanımlar'], + '每月用量历史': ['Monthly usage history', 'Aylık kullanım geçmişi'], + '日期': ['Date', 'Tarih'], + '月份': ['Month', 'Ay'], + '下行': ['Download', 'İndirme'], + '上行': ['Upload', 'Yükleme'], + '合计': ['Total', 'Toplam'], + '从启用统计时开始记录;统计约每 10 秒更新、每 60 秒保存。突然断电可能损失最近未保存的记录。': ['Recording starts when accounting is enabled. Usage updates about every 10 seconds and is saved every 60 seconds. Sudden power loss may lose recent unsaved usage.', 'Kayıt, istatistik hizmeti açıldığında başlar. Kullanım yaklaşık 10 saniyede güncellenir, 60 saniyede kaydedilir. Ani güç kesintisinde son kaydedilmemiş veriler kaybolabilir.'], + '本地网卡统计供参考,计费以运营商为准。额度用于显示和提醒,不会自动断网。': ['Local interface statistics are an estimate; carrier billing takes precedence. Allowances display warnings and never disconnect the network.', 'Yerel arayüz istatistikleri tahminidir; operatörün hesabı esas alınır. Kotalar uyarı gösterir, ağı otomatik kesmez.'], + '不限量': ['Unlimited', 'Sınırsız'], + '未设置套餐名称': ['No plan name set', 'Paket adı ayarlanmadı'], + '每周期额度:': ['Cycle allowance: ', 'Dönem kotası: '], + '下次重置:': ['Next reset: ', 'Sonraki sıfırlama: '], + '每日参考额度:': ['Daily reference allowance: ', 'Günlük referans kotası: '], + '更新于:': ['Updated: ', 'Güncelleme: '], + '流量统计服务暂不可用': ['Data accounting service is unavailable', 'Veri istatistik hizmeti kullanılamıyor'], + '统计网卡暂不可用': ['Accounting interface is unavailable', 'İstatistik arayüzü kullanılamıyor'], + '系统时间尚未同步': ['System clock is not synchronized yet', 'Sistem saati henüz eşitlenmedi'], + '统计数据保存失败': ['Failed to save usage data', 'Kullanım verileri kaydedilemedi'], + '已达到套餐额度': ['Plan allowance reached', 'Paket kotasına ulaşıldı'], + '已达到每日参考额度': ['Daily reference allowance reached', 'Günlük referans kotasına ulaşıldı'], + '暂无统计记录': ['No usage records yet', 'Henüz kullanım kaydı yok'], + '校准本周期已用流量?': ['Adjust this cycle’s used data?', 'Bu dönemin kullanılan verisi düzeltilecek mi?'], + '这会将当前套餐周期已用值调整为输入值,每日和自然月记录不变。': ['This sets current cycle usage to the entered value. Daily and calendar-month records stay unchanged.', 'Mevcut dönem kullanımı girilen değere ayarlanır. Günlük ve takvim ayı kayıtları değişmez.'], + '正在保存流量池设置…': ['Saving data plan settings…', 'Veri paketi ayarları kaydediliyor…'], + '短信转发': ['SMS forwarding', 'SMS yönlendirme'], + '开启短信转发': ['Enable SMS forwarding', 'SMS yönlendirmeyi aç'], + '转发已开启': ['Forwarding enabled', 'Yönlendirme açık'], + '转发未开启': ['Forwarding disabled', 'Yönlendirme kapalı'], + '转发方式': ['Forwarding method', 'Yönlendirme yöntemi'], + '模板语言': ['Template language', 'Şablon dili'], + '简体中文': ['Simplified Chinese', 'Basitleştirilmiş Çince'], + '保存后用于转发标题、提示文字和电源通知;短信原文及设备备注保持不变。': ['After saving, this language is used for forwarding titles, labels, and power notifications. Original SMS text and device notes stay unchanged.', 'Kaydettikten sonra yönlendirme başlıkları, etiketler ve güç bildirimleri bu dilde gönderilir. SMS metni ve cihaz notları değiştirilmez.'], + '钉钉机器人': ['DingTalk bot', 'DingTalk botu'], + '本机短信': ['Device SMS', 'Cihaz SMS’i'], + '邮件 SMTP': ['Email SMTP', 'E-posta SMTP'], + 'HTTPS 地址': ['HTTPS address', 'HTTPS adresi'], + '以固定 JSON 格式发送,不执行自定义命令。': ['Sends a fixed JSON payload; no custom commands are run.', 'Sabit bir JSON gönderir; özel komut çalıştırılmaz.'], + '机器人 Webhook 地址': ['Bot webhook URL', 'Bot webhook adresi'], + '加签密钥 · 留空保留': ['Signing secret · leave blank to keep', 'İmza anahtarı · korumak için boş bırakın'], + '清除加签密钥': ['Clear signing secret', 'İmza anahtarını sil'], + '附带设备信息': ['Include device information', 'Cihaz bilgisini ekle'], + 'SMTP 服务器域名': ['SMTP server domain', 'SMTP sunucu alan adı'], + '端口 · 465 / 587': ['Port · 465 / 587', 'Bağlantı noktası · 465 / 587'], + '发件邮箱': ['Sender email', 'Gönderen e-posta'], + '收件邮箱': ['Recipient email', 'Alıcı e-posta'], + '授权码 / 密码 · 留空保留': ['App password / password · leave blank to keep', 'Uygulama şifresi / şifre · korumak için boş bırakın'], + '已配置,留空保留': ['Configured; leave blank to keep', 'Yapılandırıldı; korumak için boş bırakın'], + '请输入授权码': ['Enter an app password', 'Uygulama şifresini girin'], + '可选': ['Optional', 'İsteğe bağlı'], + '清除邮件配置': ['Clear email configuration', 'E-posta yapılandırmasını sil'], + '使用邮箱提供的 SMTP 授权码;始终验证 TLS 证书。': ['Use your email provider’s SMTP app password; the TLS certificate is always verified.', 'E-posta sağlayıcınızın SMTP uygulama şifresini kullanın; TLS sertifikası her zaman doğrulanır.'], + '短信接收号码 · 每行一个,最多 3 个': ['SMS recipients · one per line, up to 3', 'SMS alıcıları · satır başına bir, en fazla 3'], + '经本机 SIM 转发,可能产生短信费用;每条最多 70 个 UCS-2 单元,不限制每日转发条数。': ['Forwarding uses the device SIM and may incur SMS charges; up to 70 UCS-2 units per message, with no daily forwarding limit.', 'Yönlendirme cihazın SIM kartını kullanır ve ücret doğurabilir; mesaj başına en fazla 70 UCS-2 birimi, günlük yönlendirme sınırı yoktur.'], + '电源通知': ['Power notifications', 'Güç bildirimleri'], + '电源状态通知': ['Power status notifications', 'Güç durumu bildirimleri'], + '充电状态变化,或电量跨过 5%、20%、40%、60%、80%、100% 时通知。': ['Notify when charging status changes or battery level crosses 5%, 20%, 40%, 60%, 80%, or 100%.', 'Şarj durumu değiştiğinde veya pil seviyesi %5, %20, %40, %60, %80 ya da %100 eşiğini geçtiğinde bildir.'], + '设备暂未提供有效电池状态': ['No valid battery status is available on this device', 'Bu cihazda geçerli pil durumu yok'], + '设备备注': ['Device note', 'Cihaz notu'], + '黑名单': ['Blocklists', 'Engelleme listeleri'], + '号码黑名单 · 每行一个,最多 64 个': ['Number blocklist · one per line, up to 64', 'Numara engelleme listesi · satır başına bir, en fazla 64'], + '关键词黑名单 · 每行一个,最多 32 个': ['Keyword blocklist · one per line, up to 32', 'Anahtar kelime engelleme listesi · satır başına bir, en fazla 32'], + '命中的新短信只记为已处理,不会转发;清空规则后不会补发。规则不影响电源通知。': ['Matching new SMS are marked processed and not forwarded; clearing rules will not resend them. Power notifications are unaffected.', 'Eşleşen yeni SMS’ler işlenmiş sayılır ve yönlendirilmez; kurallar silinince tekrar gönderilmez. Güç bildirimleri etkilenmez.'], + '测试与状态': ['Test and status', 'Test ve durum'], + '设备独立执行,关闭页面仍生效;仅转发新短信,失败不自动重发。': ['Runs on the device even with this page closed; only new SMS are forwarded, and failed deliveries are not retried.', 'Sayfa kapalıyken de cihazda çalışır; yalnızca yeni SMS’ler yönlendirilir ve başarısız teslimatlar yeniden denenmez.'], + '保存设置': ['Save settings', 'Ayarları kaydet'], + '发送测试消息': ['Send test message', 'Test mesajı gönder'], + '刷新状态': ['Refresh status', 'Durumu yenile'], + '最近转发:': ['Last forwarding: ', 'Son yönlendirme: '], + '最近电源通知:': ['Last power notice: ', 'Son güç bildirimi: '], + '暂无投递': ['No delivery yet', 'Henüz teslimat yok'], + '发送成功': ['Sent successfully', 'Başarıyla gönderildi'], + '已拦截向原发件人转发': ['Forwarding to original sender blocked', 'Asıl gönderene yönlendirme engellendi'], + '短信过长,未发送': ['SMS too long; not sent', 'SMS çok uzun; gönderilmedi'], + '设备保存失败': ['Device storage failed', 'Cihaza kaydedilemedi'], + '短信服务暂不可用': ['SMS service temporarily unavailable', 'SMS hizmeti geçici olarak kullanılamıyor'], + '配置无效': ['Invalid configuration', 'Geçersiz yapılandırma'], + '目标地址无效': ['Invalid destination', 'Geçersiz hedef adresi'], + '投递失败,请检查配置和设备网络': ['Delivery failed; check the settings and device network', 'Teslimat başarısız; ayarları ve cihaz ağını kontrol edin'], + '邮箱服务器拒绝登录,请检查授权码': ['SMTP login rejected; check the app password', 'SMTP girişi reddedildi; uygulama şifresini kontrol edin'], + '读取失败,请刷新页面': ['Loading failed; refresh the page', 'Yükleme başarısız; sayfayı yenileyin'], + '号码无效、重复或超过数量上限': ['Invalid, duplicate or too many numbers', 'Geçersiz, yinelenen veya fazla sayıda numara'], + '关键词无效、重复或超过数量上限': ['Invalid, duplicate or too many keywords', 'Geçersiz, yinelenen veya fazla sayıda anahtar kelime'], + '请先配置当前转发渠道': ['Configure the selected forwarding channel first', 'Önce seçilen yönlendirme kanalını yapılandırın'], + '保存短信转发设置?': ['Save SMS forwarding settings?', 'SMS yönlendirme ayarları kaydedilsin mi?'], + '开启后只处理新收到的短信;历史短信不会补发。': ['Only newly received SMS will be processed; old messages will not be forwarded.', 'Yalnızca yeni alınan SMS’ler işlenecek; eski mesajlar yönlendirilmeyecek.'], + '正在保存短信转发设置…': ['Saving SMS forwarding settings…', 'SMS yönlendirme ayarları kaydediliyor…'], + '保存失败': ['Save failed', 'Kaydetme başarısız'], + '已保存': ['Saved', 'Kaydedildi'], + '请先保存修改再测试': ['Save changes before testing', 'Testten önce değişiklikleri kaydedin'], + '请先开启并保存短信转发': ['Enable and save forwarding first', 'Önce yönlendirmeyi açıp kaydedin'], + '将使用本机 SIM 向已保存号码发送,可能产生短信费用。': ['The device SIM will send to the saved numbers; SMS charges may apply.', 'Cihazın SIM kartı kayıtlı numaralara gönderecek; SMS ücreti doğabilir.'], + '将向当前已保存渠道发送一条固定测试消息。': ['A fixed test message will be sent to the saved channel.', 'Kayıtlı kanala sabit bir test mesajı gönderilecek.'], + '发送测试消息?': ['Send a test message?', 'Test mesajı gönderilsin mi?'], + '测试已开始,请稍后刷新状态': ['Test started; refresh status shortly', 'Test başladı; kısa süre sonra durumu yenileyin'], + '测试失败:': ['Test failed: ', 'Test başarısız: '], + '未知错误': ['Unknown error', 'Bilinmeyen hata'], '设备管理': ['Device management', 'Cihaz yönetimi'], 'USB 角色': ['USB role', 'USB rolü'], '当前角色': ['Current role', 'Geçerli rol'], @@ -332,6 +457,8 @@ var DASH_I18N = { '收件人:号码,如 10086 或 +86...': ['Recipient: number, e.g. 10086 or +86...', 'Alıcı: numara, ör. 10086 veya +86...'], '刷新': ['Refresh', 'Yenile'], '从 SIM 同步': ['Sync from SIM', 'SIM’den eşitle'], + 'SIM 存储': ['SIM storage', 'SIM depolama'], + 'SIM 存储已满;自动归档尚未释放空间,请检查短信服务。': ['SIM storage is full; automatic archiving has not freed space. Check the SMS service.', 'SIM depolaması dolu; otomatik arşivleme henüz yer açmadı. SMS hizmetini kontrol edin.'], '清空本地池': ['Clear local pool', 'Yerel havuzu temizle'], '加载中': ['Loading', 'Yükleniyor'], '选择左侧会话,或直接在下方输入号码发送。': ['Select a conversation on the left, or enter a number below to send.', 'Soldan bir görüşme seçin veya göndermek için aşağıya bir numara girin.'], @@ -515,6 +642,16 @@ function fmtBytes(b) { while (b >= 1024 && i < u.length - 1) { b /= 1024; i++; } return (b >= 100 ? b.toFixed(0) : b.toFixed(1)) + ' ' + u[i]; } +// Traffic plans use decimal GB; keep memory/rate formatting unchanged. +function fmtTrafficBytes(b) { + if (b == null || b === '' || !Number.isFinite(Number(b)) || Number(b) < 0) return '--'; + b = Number(b); + var u = [ 'B', 'KB', 'MB', 'GB', 'TB' ], i = 0; + while (b >= 1000 && i < u.length - 1) { b /= 1000; i++; } + var value = Number(b.toFixed(i === 0 ? 0 : 2)); + if (value >= 1000 && i < u.length - 1) { value = 1; i++; } + return value + ' ' + u[i]; +} function fmtRate(bps) { if (bps == null || isNaN(bps) || bps < 0) return '--'; var u = [ 'B/s', 'KB/s', 'MB/s', 'GB/s' ], i = 0; @@ -547,6 +684,10 @@ html.mud-bootstrap-theme{--surface:var(--background-color-high);--surface-sunken .mud-sec>h3{margin:16px 0 10px;font-size:.7rem;font-weight:600;color:var(--text-muted,var(--text-light,#787d85));letter-spacing:.08em} .mud-sec>h3::before{content:'';display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--brand,var(--primary,#2f7bf6));margin-right:7px;vertical-align:1px} .mud-cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:0 28px} +.mud-client-cols{grid-template-columns:repeat(auto-fit,minmax(min(100%,300px),1fr));gap:16px 28px;margin-top:16px;align-items:start} +.mud-client-cols>div{min-width:0} +.mud-client-cols .mud-cli .t{flex-wrap:wrap;overflow-wrap:anywhere} +.mud-client-cols .mud-cli .s{overflow-wrap:anywhere} .mud-body>.mud-sec+.mud-sec{border-top:1px dashed color-mix(in oklab,var(--hairline,var(--border,#ddd)) 60%,transparent);margin-top:14px;padding-top:2px} /* 首屏骨架:卡片正常占位,只让待填字段呼吸;第一份快照到达后停止。 */ @keyframes mudpulse{0%,100%{opacity:1}50%{opacity:.35}} @@ -720,21 +861,26 @@ function set(id, text, color) { } function spark(el, arr, min, max, win) { if (!el || !arr || arr.length < 2) return; - var w = 100, h = 34, pts = []; + var w = 100, h = 34, padX = 1, padY = 3, baseY = h - padY, pts = []; for (var i = 0; i < arr.length; i++) { - pts.push([ i / (win - 1) * w, - h - Math.max(0, Math.min(1, (arr[i] - min) / (max - min || 1))) * (h - 3) - 1.5 ]); + pts.push([ padX + i / (win - 1) * (w - 2 * padX), + baseY - Math.max(0, Math.min(1, (arr[i] - min) / (max - min || 1))) * (h - 2 * padY) ]); } /* Catmull-Rom 转三次贝塞尔:折线变平滑曲线 */ var d = 'M' + pts[0][0].toFixed(1) + ',' + pts[0][1].toFixed(1); for (var i = 0; i < pts.length - 1; i++) { var p0 = pts[Math.max(0, i - 1)], p1 = pts[i], p2 = pts[i + 1], p3 = pts[Math.min(pts.length - 1, i + 2)]; - d += 'C' + (p1[0] + (p2[0] - p0[0]) / 6).toFixed(1) + ',' + (p1[1] + (p2[1] - p0[1]) / 6).toFixed(1) + - ' ' + (p2[0] - (p3[0] - p1[0]) / 6).toFixed(1) + ',' + (p2[1] - (p3[1] - p1[1]) / 6).toFixed(1) + + // Catmull-Rom can overshoot even when every sample is inside the SVG. + // Bound controls to their segment and leave room for the stroke itself. + var lo = Math.min(p1[1], p2[1]), hi = Math.max(p1[1], p2[1]); + var c1y = Math.max(lo, Math.min(hi, p1[1] + (p2[1] - p0[1]) / 6)); + var c2y = Math.max(lo, Math.min(hi, p2[1] - (p3[1] - p1[1]) / 6)); + d += 'C' + (p1[0] + (p2[0] - p0[0]) / 6).toFixed(1) + ',' + c1y.toFixed(1) + + ' ' + (p2[0] - (p3[0] - p1[0]) / 6).toFixed(1) + ',' + c2y.toFixed(1) + ' ' + p2[0].toFixed(1) + ',' + p2[1].toFixed(1); } var last = pts.length - 1; - var area = d + ' L' + pts[last][0].toFixed(1) + ',' + h + ' L' + pts[0][0].toFixed(1) + ',' + h + ' Z'; + var area = d + ' L' + pts[last][0].toFixed(1) + ',' + baseY + ' L' + pts[0][0].toFixed(1) + ',' + baseY + ' Z'; var gid = 'mudg-' + (el.id || Math.floor(Math.random() * 1e6)); el.innerHTML = '' + '' + @@ -760,7 +906,11 @@ function neighborRows(c, lockedCell) { var l = qLabel(n.rsrp, n.rsrq, n.sinr); var key = n.rat + ':' + n.arfcn + ',' + n.pci; var isLocked = lk.split('|').indexOf(key) >= 0; - return '
' + (n.rat == 'nr' ? 'NR n' + esc(n.band) : 'LTE B' + esc(n.band)) + '' + + var nrBand = n.band != null && n.band !== 0 ? 'n' + esc(n.band) : + (Array.isArray(n.band_candidates) && n.band_candidates.length ? + n.band_candidates.map(function(b) { return 'n' + esc(b); }).join('/') : '--'); + var lteBand = n.band != null && n.band !== 0 ? 'B' + esc(n.band) : '--'; + return '
' + (n.rat == 'nr' ? 'NR ' + nrBand : 'LTE ' + lteBand) + '' + '' + esc(n.pci != null ? n.pci : '--') + '' + '' + esc(n.arfcn != null ? n.arfcn : '--') + '' + '' + (n.rsrp != null ? n.rsrp.toFixed(1) : '--') + '' + @@ -986,10 +1136,13 @@ return baseclass.extend({ callLockGet: callLockGet, callLockFresh: callLockFresh, callLockSet: callLockSet, callSmsList: callSmsList, callSmsShow: callSmsShow, callSmsSend: callSmsSend, callSmsDel: callSmsDel, callSmsSync: callSmsSync, + callForwardGet: callForwardGet, callForwardStatus: callForwardStatus, + callForwardSet: callForwardSet, callForwardTest: callForwardTest, + callTrafficGet: callTrafficGet, callTrafficSet: callTrafficSet, callUsbGet: callUsbGet, callUsbSet: callUsbSet, callUsbNetList: callUsbNetList, callUsbNetAdd: callUsbNetAdd, carrierName: carrierName, qLabel: qLabel, qCol: qCol, qScore: qScore, - esc: esc, fmtBytes: fmtBytes, fmtRate: fmtRate, fmtUptime: fmtUptime, PLMN_CN: PLMN_CN, + esc: esc, fmtBytes: fmtBytes, fmtTrafficBytes: fmtTrafficBytes, fmtRate: fmtRate, fmtUptime: fmtUptime, PLMN_CN: PLMN_CN, uiLanguage: uiLanguage, translate: translate, localize: localize, localizeMenu: localizeMenu, injectCss: injectCss, v: v, set: set, spark: spark, neighborRows: neighborRows, toast: toast, busy: busy, confirmBox: confirmBox, alertBox: alertBox, choiceBox: choiceBox, diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/forward.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/forward.js new file mode 100644 index 00000000..22ce41bc --- /dev/null +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/forward.js @@ -0,0 +1,254 @@ +'use strict'; +'require view'; +'require poll'; +'require mu300.common as M'; + +/* All destinations and rules are private to this authenticated editor. The + * status poll never includes a URL, phone number, password or SMS body. */ +var METHODS = { webhook: 'Webhook', dingtalk: '钉钉机器人', smtp: '邮件 SMTP', sms: '本机短信' }; +var RESULTS = { + idle: '暂无投递', sent: '发送成功', disabled: '转发未开启', + self_forward_blocked: '已拦截向原发件人转发', + message_too_long: '短信过长,未发送', storage_failed: '设备保存失败', + source_unavailable: '短信服务暂不可用', power_unavailable: '设备暂未提供有效电池状态', + invalid_config: '配置无效', invalid_forward_config: '配置无效', + invalid_destination: '目标地址无效', delivery_failed: '投递失败,请检查配置和设备网络', + smtp_auth_failed: '邮箱服务器拒绝登录,请检查授权码' +}; +var ERRORS = { + invalid_config: '配置无效', invalid_forward_config: '配置无效', + invalid_destination: '目标地址无效', forward_storage_failed: '设备保存失败', + sms_list_unavailable: '短信服务暂不可用', power_unavailable: '设备暂未提供有效电池状态' +}; +function result(code) { return M.translate(RESULTS[code] || '暂无投递'); } +function lines(value) { return String(value || '').split(/\r?\n/).map(function(s) { return s.trim(); }).filter(Boolean); } +function count(value) { return lines(value).length; } +function validPhones(value, max) { + var a = lines(value), seen = {}; + return a.length <= max && a.every(function(p) { + var key = p.replace(/^\+/, ''); + if (!/^\+?[0-9]{3,32}$/.test(p) || seen[key]) return false; + seen[key] = true; return true; + }); +} + +return view.extend({ + load: function() { return L.resolveDefault(M.callForwardGet(), {}); }, + render: function(data) { + M.injectCss(); + M.localizeMenu(); + var root = document.createElement('div'); + root.className = 'mud'; + root.innerHTML = ` + +
+
+

短信转发

--
+
暂无投递
+ +
+
+
+
+
保存后用于转发标题、提示文字和电源通知;短信原文及设备备注保持不变。
+
+
+
以固定 JSON 格式发送,不执行自定义命令。
+
+
+
+
+ + +
+
+
+
+
+
+
+
+
+ + +
使用邮箱提供的 SMTP 授权码;始终验证 TLS 证书。
+
+
+
+ +
经本机 SIM 转发,可能产生短信费用;每条最多 70 个 UCS-2 单元,不限制每日转发条数。
+
+
+
+

电源通知

+ +
充电状态变化,或电量跨过 5%、20%、40%、60%、80%、100% 时通知。
+
+
+

黑名单

+
+
+
命中的新短信只记为已处理,不会转发;清空规则后不会补发。规则不影响电源通知。
+
+
+
+

测试与状态

+
设备独立执行,关闭页面仍生效;仅转发新短信,失败不自动重发。
+ +
+ + + +
+
`; + M.localize(root); + this.root = root; + this.data = data || {}; + this.saved = this.data.config || null; + this.status = this.data.status || {}; + this.wire(); + if (this.saved) this.fill(this.saved); + else this.error(this.data.error || '读取失败,请刷新页面'); + // A legacy config has no saved template language. The UI offers its + // current locale, but it must be saved before a matching test can run. + this.savedPayload = this.saved && this.saved.template_language ? JSON.stringify(this.payload()) : null; + this.paintStatus(); + this.paintMethod(); + var self = this; + poll.add(function() { return self.refreshStatus(); }, 5); + return root; + }, + q: function(id) { return this.root.querySelector('#mud-fwd-' + id); }, + error: function(s) { + this.q('error').textContent = s ? M.translate(ERRORS[s] || s) : ''; + this.q('error').hidden = !s; + }, + fill: function(c) { + var self = this; + [ 'enabled', 'power_forward_enabled', 'smtp_forward_device_info', + 'dingtalk_forward_device_info', 'sms_forward_device_info' ].forEach(function(k) { self.q(k).checked = !!c[k]; }); + [ 'method', 'webhook_url', 'dingtalk_webhook', 'sms_to_phone', 'blacklist_phone', + 'blacklist_keywords', 'nickname' ].forEach(function(k) { self.q(k).value = c[k] || ''; }); + this.q('template_language').value = c.template_language || M.uiLanguage(); + [ 'host', 'port', 'username', 'to' ].forEach(function(k) { self.q('smtp_' + k).value = c.smtp && c.smtp[k] || (k === 'port' ? '465' : ''); }); + [ 'smtp_password', 'dingtalk_secret' ].forEach(function(k) { self.q(k).value = ''; self.q('clear_' + k).checked = false; }); + this.q('smtp_password').placeholder = M.translate(c.smtp && c.smtp.password_configured ? '已配置,留空保留' : '请输入授权码'); + this.q('dingtalk_secret').placeholder = M.translate(c.dingtalk_secret_configured ? '已配置,留空保留' : '可选'); + this.paintMethod(); + }, + payload: function() { + var self = this, p = {}; + [ 'enabled', 'power_forward_enabled', 'smtp_forward_device_info', + 'dingtalk_forward_device_info', 'sms_forward_device_info', + 'clear_smtp_password', 'clear_dingtalk_secret' ].forEach(function(k) { p[k] = self.q(k).checked ? 1 : 0; }); + [ 'method', 'template_language', 'webhook_url', 'dingtalk_webhook', 'dingtalk_secret', 'sms_to_phone', + 'smtp_host', 'smtp_port', 'smtp_username', 'smtp_to', 'smtp_password', + 'blacklist_phone', 'blacklist_keywords', 'nickname' ].forEach(function(k) { p[k] = self.q(k).value.trim(); }); + [ 'sms_to_phone', 'blacklist_phone', 'blacklist_keywords' ].forEach(function(k) { p[k] = lines(p[k]).join('\n'); }); + if (p.clear_smtp_password) { + p.smtp_host = ''; p.smtp_username = ''; p.smtp_to = ''; p.smtp_password = ''; p.smtp_port = '465'; + } + return p; + }, + validate: function(p) { + if (!validPhones(p.sms_to_phone, 3) || !validPhones(p.blacklist_phone, 64)) return '号码无效、重复或超过数量上限'; + var words = lines(p.blacklist_keywords); + if (words.length > 32 || words.some(function(w) { return unescape(encodeURIComponent(w)).length > 128; }) || + new Set(words).size !== words.length) return '关键词无效、重复或超过数量上限'; + if (p.power_forward_enabled && !this.status.power_supported) return '设备暂未提供有效电池状态'; + if (p.enabled && ((p.method === 'webhook' && !p.webhook_url) || + (p.method === 'dingtalk' && !p.dingtalk_webhook) || + (p.method === 'sms' && !p.sms_to_phone) || + (p.method === 'smtp' && !p.smtp_host))) return '请先配置当前转发渠道'; + return ''; + }, + paintMethod: function() { + var method = this.q('method').value; + this.root.querySelectorAll('.mud-fwd-channel').forEach(function(el) { el.hidden = el.getAttribute('data-method') !== method; }); + }, + paintStatus: function() { + var s = this.status || {}; + this.q('state').textContent = M.translate(s.enabled ? '转发已开启' : '转发未开启'); + this.q('state').classList.toggle('on', !!s.enabled); + this.q('last').textContent = M.translate('最近转发:') + result(s.last_result); + this.q('power-last').textContent = M.translate('最近电源通知:') + result(s.power_last_result); + this.q('power_forward_enabled').disabled = !s.power_supported && !this.q('power_forward_enabled').checked; + this.q('power-note').textContent = M.translate(s.power_supported ? + '充电状态变化,或电量跨过 5%、20%、40%、60%、80%、100% 时通知。' : '设备暂未提供有效电池状态'); + }, + refreshStatus: function() { + var self = this; + return L.resolveDefault(M.callForwardStatus(), {}).then(function(r) { + if (r.status) { self.status = r.status; self.paintStatus(); } + }); + }, + wire: function() { + var self = this; + this.q('method').onchange = function() { self.paintMethod(); }; + this.q('save').onclick = function() { + var p = self.payload(), error = self.validate(p); + if (error) { self.error(error); return; } + M.confirmBox('保存短信转发设置?', '开启后只处理新收到的短信;历史短信不会补发。', { okText: '保存' }).then(function(yes) { + if (!yes) return; + var btn = self.q('save'), toast = M.toast('正在保存短信转发设置…', { type: 'busy', timeout: 0 }); + M.busy(btn, true); self.error(''); + L.resolveDefault(M.callForwardSet(JSON.stringify(p)), {}).then(function(r) { + M.busy(btn, false); + if (!r.ok) { self.error(r.error || '保存失败'); toast.update('保存失败', 'error'); } + else { + self.savedPayload = null; + L.resolveDefault(M.callForwardGet(), {}).then(function(v) { + if (v.config) { + self.saved = v.config; + self.status = v.status || {}; + self.fill(v.config); + self.savedPayload = JSON.stringify(self.payload()); + self.paintStatus(); + } + }); + toast.update('已保存', 'success'); + } + setTimeout(function() { toast.close(); }, 3000); + }); + }); + }; + this.q('test').onclick = function() { + var p = self.payload(); + if (JSON.stringify(p) !== self.savedPayload) { + self.error('请先保存修改再测试'); return; + } + if (!self.status.enabled) { self.error('请先开启并保存短信转发'); return; } + var msg = p.method === 'sms' ? '将使用本机 SIM 向已保存号码发送,可能产生短信费用。' : + '将向当前已保存渠道发送一条固定测试消息。'; + M.confirmBox('发送测试消息?', msg, { okText: '发送' }).then(function(yes) { + if (!yes) return; + var btn = self.q('test'); M.busy(btn, true); + L.resolveDefault(M.callForwardTest(), {}).then(function(r) { + M.busy(btn, false); + M.toast(r.ok ? '测试已开始,请稍后刷新状态' : '测试失败:' + (r.error || '未知错误'), + { type: r.ok ? 'success' : 'error' }); + setTimeout(function() { self.refreshStatus(); }, 1500); + }); + }); + }; + this.q('refresh').onclick = function() { self.refreshStatus(); }; + } +}); diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js index bd5bdc95..48fc1cfa 100644 --- a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js @@ -128,6 +128,9 @@ return view.extend({
--累计接收
--累计发送
+
--今日流量
+
--当月流量
+
--套餐剩余
@@ -178,28 +181,35 @@ return view.extend({
USB 网络--
连接跟踪--
LAN 地址--
-
无线客户端--
-
DHCP 租约--
+
系统--
-
设备型号--
-
系统--
调制解调器--
运营商--
PLMN--
IMEI--
IMSI--
ICCID--
+
本机号码--
模组--
固件--
显示卡号信息
-
+
+
+
无线客户端--
+
+
+
+
DHCP 租约--
+
+
+
@@ -325,6 +335,7 @@ return view.extend({ M.set('imei', mask(id && id.imei)); M.set('imsi', mask(id && id.imsi)); M.set('iccid', mask(id && id.iccid)); + M.set('msisdn', mask(id && id.msisdn)); M.set('fwmodel', id ? (id.model || '--') : '--'); M.set('fw', id ? (id.fw || '--') : '--'); }, @@ -446,6 +457,10 @@ return view.extend({ this.lastNet = { ts: i.ts, rx: net.rx, tx: net.tx }; } var w = i.wan || {}; + var traffic = i.traffic && i.traffic.clock_ok && i.ts - i.traffic.updated_at < 30 ? i.traffic : null; + M.set('tr-day', traffic ? M.fmtTrafficBytes(traffic.today_used) : '--'); + M.set('tr-month', traffic ? M.fmtTrafficBytes(traffic.month_used) : '--'); + M.set('tr-left', traffic ? (traffic.remaining == null ? M.translate('不限量') : M.fmtTrafficBytes(traffic.remaining)) : '--'); M.v('ip').innerHTML = M.esc(w.ip4 || '--') + (w.ip6 ? '
' + M.esc(w.ip6) : ''); M.set('dns', w.dns || '--'); M.set('apn', w.apn || '--'); @@ -498,13 +513,11 @@ return view.extend({ }).join('') || ''; /* 近期 DHCP 租约:没人连着的时候这里也能看出谁来过 */ M.v('leases').innerHTML = (i.lan && i.lan.list && i.lan.list.length) - ? '
近期 DHCP 租约
' + - '' + - i.lan.list.slice(0, 8).map(function(l) { - return '' + - '' + - ''; - }).join('') + '
' + M.esc(l.host || l.ip || '?') + '' + M.esc(l.ip || '') + '' + M.esc(l.mac) + '' + (l.left >= 3600 ? Math.round(l.left / 3600) + ' 小时' : Math.max(0, Math.round(l.left / 60)) + ' 分') + '
' + ? i.lan.list.slice(0, 8).map(function(l) { + return '
' + M.esc(l.host || l.ip || '?') + '' + + '' + (l.left >= 3600 ? Math.round(l.left / 3600) + ' 小时' : Math.max(0, Math.round(l.left / 60)) + ' 分') + '' + + '
' + (l.ip ? M.esc(l.ip) + ' · ' : '') + M.esc(l.mac) + '
'; + }).join('') : ''; var t = i.temps || {}; diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/sms.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/sms.js index df4c1d71..02a0d1b8 100644 --- a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/sms.js +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/sms.js @@ -23,6 +23,7 @@ return view.extend({ root.innerHTML = `

短信

+
@@ -96,7 +97,7 @@ return view.extend({ if (!choice) return; L.resolveDefault(M.callSmsDel(id, choice === 'sim')).then(function(r) { r = r || {}; - if (r.ok === false) { self.note('删除失败', 'error'); return; } + if (r.ok === false) { self.note(M.translate('删除失败') + (r.error ? ': ' + r.error : ''), 'error'); return; } delete self.cache[id]; self.note(choice === 'sim' ? '已删除(本地 + SIM)' : '已删除(仅本地)', 'success'); self.reload(); @@ -153,7 +154,8 @@ return view.extend({ var self = this; /* 5 秒轮询的防闪烁:数据签名没变(无新消息、无未读状态翻转)就完全 * 不重绘——整块 innerHTML 重建 + 全文异步回填会产生肉眼可见的闪烁 */ - var sig = (this.stat && this.stat.total) + '|' + all.map(function(m) { + var sig = (this.stat && this.stat.total) + '|' + + (this.stat && this.stat.sim_used) + '/' + (this.stat && this.stat.sim_total) + '|' + all.map(function(m) { return m.id + ':' + m.status; }).join(','); if (sig === this._sig) return; @@ -172,6 +174,14 @@ return view.extend({ var st = this.stat || {}; this.Q('sms-stat').textContent = M.translate('· ' + (st.total || all.length) + ' 条' + (st.unread ? ',' + st.unread + ' 条未读' : '') + ' · ' + peers.length + ' 个会话'); + var cap = this.Q('sms-capacity'); + var fresh = st.sim_seen && (Date.now() / 1000 - st.sim_seen < 120); + cap.style.display = fresh && st.sim_total > 0 ? '' : 'none'; + if (fresh && st.sim_total > 0) { + cap.textContent = M.translate('SIM 存储') + ': ' + st.sim_used + '/' + st.sim_total + + (st.sim_used >= st.sim_total ? ' · ' + M.translate('SIM 存储已满;自动归档尚未释放空间,请检查短信服务。') : ''); + cap.style.color = st.sim_used >= st.sim_total ? 'var(--error,#c93636)' : ''; + } var box = this.Q('sms-convs'); if (!peers.length) { box.innerHTML = '
' + M.esc(M.translate('池子是空的:收到/发出的短信会出现在这里,或点「从 SIM 同步」。')) + '
'; diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/traffic.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/traffic.js new file mode 100644 index 00000000..9ad22ff5 --- /dev/null +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/traffic.js @@ -0,0 +1,143 @@ +'use strict'; +'require view'; +'require poll'; +'require mu300.common as M'; + +function formatUsage(n) { return M.fmtTrafficBytes(n); } +var ERRORS = { invalid_config: '配置无效', traffic_unavailable: '流量统计服务暂不可用', + storage_failed: '统计数据保存失败', clock_unsynced: '系统时间尚未同步' }; + +return view.extend({ + load: function() { return L.resolveDefault(M.callTrafficGet(), {}); }, + render: function(data) { + M.injectCss(); M.localizeMenu(); + var root = document.createElement('div'); root.className = 'mud'; + root.innerHTML = ` + +
+
今日流量--
+
当月流量--自然月统计
+
套餐周期已用--
+
套餐剩余--
+
+
+
+
+
+
+
+
+
+

套餐与流量池

+
+
+
+
+
+
+
+
额度为 0 表示不限量;1 GB = 1000 MB。重置日在设备当地时间零点生效,短月份使用当月最后一天。
+
+
+
校准只调整当前套餐周期,不修改每日和自然月历史;下个周期自动恢复实际统计。
+
+
+
+

最近每日用量

+
日期下行上行合计
+
+
+
+

每月用量历史

+
月份下行上行合计
+
从启用统计时开始记录;统计约每 10 秒更新、每 60 秒保存。突然断电可能损失最近未保存的记录。
+
本地网卡统计供参考,计费以运营商为准。额度用于显示和提醒,不会自动断网。
+
`; + M.localize(root); this.root = root; this.data = data || {}; + this.fill(this.data.config || {}); this.paint(); this.wire(); + var self = this; poll.add(function() { return self.refresh(); }, 10); + return root; + }, + q: function(k) { return this.root.querySelector('#mud-tr-' + k); }, + fill: function(c) { + var self = this; + ['plan_name','device'].forEach(function(k) { self.q(k).value = c[k] || ''; }); + ['monthly_gb','daily_gb'].forEach(function(k) { self.q(k).value = c[k] || 0; }); + this.q('reset_day').value = c.reset_day || 1; this.q('count_mode').value = c.count_mode || 'total'; + this.q('used_gb').value = ''; + }, + paint: function() { + var d = this.data, s = d.status || {}, c = d.config || {}, self = this; + this.q('today').textContent = formatUsage(s.today_used); this.q('month').textContent = formatUsage(s.month_used); + this.q('cycle').textContent = formatUsage(s.cycle_used); + this.q('remaining').textContent = s.remaining == null ? M.translate('不限量') : formatUsage(s.remaining); + this.q('today-detail').textContent = M.translate('下行') + ' ' + formatUsage(s.today && s.today.rx) + ' / ' + M.translate('上行') + ' ' + formatUsage(s.today && s.today.tx); + this.q('cycle-date').textContent = s.cycle_start || '--'; + this.q('plan-name').textContent = c.plan_name || M.translate('未设置套餐名称'); + this.q('quota').textContent = M.translate('每周期额度:') + (s.monthly_limit ? formatUsage(s.monthly_limit) : M.translate('不限量')); + this.q('reset').textContent = M.translate('下次重置:') + (s.cycle_end || '--'); + this.q('daily').textContent = M.translate('每日参考额度:') + (s.daily_limit ? formatUsage(s.daily_limit) : M.translate('不限量')); + this.q('updated').textContent = (s.device || '--') + ' · ' + M.translate('更新于:') + (s.updated_at ? new Date(s.updated_at * 1000).toLocaleTimeString() : '--'); + this.q('meter').style.width = (s.monthly_limit ? Math.min(100, 100 * s.cycle_used / s.monthly_limit) : 0) + '%'; + this.q('meter').style.background = s.over_limit ? 'var(--danger,#d45)' : 'var(--brand,#2f7bf6)'; + var warnings = []; + if (!d.status) warnings.push('流量统计服务暂不可用'); + else { + if (!s.available) warnings.push('统计网卡暂不可用'); + if (!s.clock_ok) warnings.push('系统时间尚未同步'); + if (s.storage_error) warnings.push('统计数据保存失败'); + if (s.over_limit) warnings.push('已达到套餐额度'); + if (s.daily_over_limit) warnings.push('已达到每日参考额度'); + } + this.q('warning').textContent = warnings.map(function(x) { return M.translate(x); }).join(' · '); + ['days','months'].forEach(function(k) { + self.q(k).innerHTML = (d[k] || []).map(function(row) { + return '' + M.esc(row.date) + '' + formatUsage(row.rx) + '' + formatUsage(row.tx) + '' + formatUsage(row.rx + row.tx) + ''; + }).join('') || '' + M.esc(M.translate('暂无统计记录')) + ''; + }); + }, + refresh: function() { + var self = this; + return L.resolveDefault(M.callTrafficGet(), {}).then(function(d) { self.data = d; self.paint(); }); + }, + wire: function() { + var self = this; + this.q('refresh').onclick = function() { self.refresh(); }; + this.q('save').onclick = function() { + var p = { plan_name:self.q('plan_name').value.trim(), device:self.q('device').value.trim(), count_mode:self.q('count_mode').value, + monthly_gb:Number(self.q('monthly_gb').value), daily_gb:Number(self.q('daily_gb').value), reset_day:Number(self.q('reset_day').value) }; + if (self.q('used_gb').value.trim() !== '') p.used_gb = Number(self.q('used_gb').value); + if (!Number.isInteger(p.reset_day) || p.reset_day < 1 || p.reset_day > 31 || + ['monthly_gb','daily_gb','used_gb'].some(function(k) { return p[k] != null && (!Number.isFinite(p[k]) || p[k] < 0 || p[k] > 100000); })) { + M.toast('配置无效', {type:'error'}); return; + } + var confirmed = p.used_gb == null ? Promise.resolve(true) : + M.confirmBox('校准本周期已用流量?', '这会将当前套餐周期已用值调整为输入值,每日和自然月记录不变。', {okText:'保存'}); + confirmed.then(function(yes) { + if (!yes) return; + M.busy(self.q('save'), true); var toast = M.toast('正在保存流量池设置…', {type:'busy', timeout:0}); + L.resolveDefault(M.callTrafficSet(JSON.stringify(p)), {}).then(function(r) { + M.busy(self.q('save'), false); + if (!r.ok) toast.update(ERRORS[r.error] || '保存失败', 'error'); + else { self.q('used_gb').value = ''; toast.update('已保存', 'success'); self.refresh(); } + setTimeout(function() { toast.close(); }, 3000); + }); + }); + }; + } +}); diff --git a/openwrt/luci-app-mu300/lmo/mu300.en.lmo b/openwrt/luci-app-mu300/lmo/mu300.en.lmo index 263151c7..512e3374 100644 Binary files a/openwrt/luci-app-mu300/lmo/mu300.en.lmo and b/openwrt/luci-app-mu300/lmo/mu300.en.lmo differ diff --git a/openwrt/luci-app-mu300/lmo/mu300.tr.lmo b/openwrt/luci-app-mu300/lmo/mu300.tr.lmo index d35b23a0..180262a0 100644 Binary files a/openwrt/luci-app-mu300/lmo/mu300.tr.lmo and b/openwrt/luci-app-mu300/lmo/mu300.tr.lmo differ diff --git a/openwrt/luci-app-mu300/po/en/mu300.po b/openwrt/luci-app-mu300/po/en/mu300.po index 5f8b8095..be7fb3db 100644 --- a/openwrt/luci-app-mu300/po/en/mu300.po +++ b/openwrt/luci-app-mu300/po/en/mu300.po @@ -15,6 +15,12 @@ msgstr "Network locks" msgid "短信" msgstr "SMS" +msgid "短信转发" +msgstr "SMS forwarding" + +msgid "流量池" +msgstr "Data plan" + msgid "AT 终端" msgstr "AT terminal" diff --git a/openwrt/luci-app-mu300/po/tr/mu300.po b/openwrt/luci-app-mu300/po/tr/mu300.po index 6e9b4d3f..68b16c16 100644 --- a/openwrt/luci-app-mu300/po/tr/mu300.po +++ b/openwrt/luci-app-mu300/po/tr/mu300.po @@ -15,6 +15,12 @@ msgstr "Ağ kilitleri" msgid "短信" msgstr "SMS" +msgid "短信转发" +msgstr "SMS yönlendirme" + +msgid "流量池" +msgstr "Veri paketi" + msgid "AT 终端" msgstr "AT terminali" diff --git a/openwrt/luci-app-mu300/root/etc/init.d/unisoc-sms-forward b/openwrt/luci-app-mu300/root/etc/init.d/unisoc-sms-forward new file mode 100644 index 00000000..ca25d019 --- /dev/null +++ b/openwrt/luci-app-mu300/root/etc/init.d/unisoc-sms-forward @@ -0,0 +1,14 @@ +#!/bin/sh /etc/rc.common +# Separate from the USB/lock boot worker: installing or restarting the +# forwarding feature must not rerun USB gadget policy or touch the modem. +START=96 +USE_PROCD=1 + +start_service() { + procd_open_instance + procd_set_param command /usr/libexec/unisoc-modem/sms-forward run + procd_set_param respawn 3600 5 0 + procd_set_param stdout 1 + procd_set_param stderr 1 + procd_close_instance +} diff --git a/openwrt/luci-app-mu300/root/etc/init.d/unisoc-traffic b/openwrt/luci-app-mu300/root/etc/init.d/unisoc-traffic new file mode 100644 index 00000000..6a032795 --- /dev/null +++ b/openwrt/luci-app-mu300/root/etc/init.d/unisoc-traffic @@ -0,0 +1,18 @@ +#!/bin/sh /etc/rc.common +START=96 +STOP=01 +USE_PROCD=1 + +start_service() { + procd_open_instance + procd_set_param command /usr/bin/ucode -g 1000 /usr/libexec/unisoc-modem/traffic + procd_set_param respawn 3600 5 0 + procd_set_param term_timeout 8 + procd_set_param stdout 1 + procd_set_param stderr 1 + procd_close_instance +} + +stop_service() { + ubus -t 3 call unisoc.traffic flush >/dev/null 2>&1 || true +} diff --git a/openwrt/luci-app-mu300/root/lib/upgrade/keep.d/unisoc-traffic b/openwrt/luci-app-mu300/root/lib/upgrade/keep.d/unisoc-traffic new file mode 100644 index 00000000..7cf8e76b --- /dev/null +++ b/openwrt/luci-app-mu300/root/lib/upgrade/keep.d/unisoc-traffic @@ -0,0 +1 @@ +/etc/unisoc-modem/traffic/ diff --git a/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash b/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash index 6f61ed00..b4cf12c6 100644 --- a/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash +++ b/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash @@ -227,21 +227,30 @@ esc_ml() { # multi-line text -> one JSON string } m_sms_list() { - local page out + local page out sms_store sms_used sms_total sms_seen page=$(inp '@.page'); case "$page" in ''|*[!0-9]*) page=1 ;; esac out=$("$SMS" list "$page" 2>/dev/null) || out='' [ -n "$out" ] || { printf '{"error":"mu300-sms 不可用(短信服务没装或没起来)"}\n'; return; } + if [ -r "$MU300_SMS_POOL/storage" ]; then + read -r sms_store sms_used sms_total sms_seen < "$MU300_SMS_POOL/storage" + fi + case ${sms_used:-} in ''|*[!0-9]*) sms_used= ;; esac + case ${sms_total:-} in ''|*[!0-9]*) sms_total= ;; esac + case ${sms_seen:-} in ''|*[!0-9]*) sms_seen= ;; esac # first line "pool: N message(s), U unread - page P/T (10 per page)", # then fixed-width rows (see mu300-sms cmd_list); parse by column position - printf '%s\n' "$out" | awk ' + printf '%s\n' "$out" | awk -v sms_used="$sms_used" -v sms_total="$sms_total" -v sms_seen="$sms_seen" ' NR == 1 { total = $0; sub(/^pool: /, "", total); sub(/ message.*/, "", total) unread = $0; sub(/^pool: [0-9]+ message\(s\), /, "", unread); sub(/ unread.*/, "", unread) pg = $0; sub(/.*page /, "", pg); sub(/\/.*/, "", pg) pgs = $0; sub(/.*page [0-9]+\//, "", pgs); sub(/ \(.*/, "", pgs) - printf "{\"total\":%s,\"unread\":%s,\"page\":%s,\"pages\":%s,\"msgs\":[", + printf "{\"total\":%s,\"unread\":%s,\"page\":%s,\"pages\":%s,\"sim_used\":%s,\"sim_total\":%s,\"sim_seen\":%s,\"msgs\":[", (total ~ /^[0-9]+$/ ? total : 0), (unread ~ /^[0-9]+$/ ? unread : 0), - (pg ~ /^[0-9]+$/ ? pg : 1), (pgs ~ /^[0-9]+$/ ? pgs : 1) + (pg ~ /^[0-9]+$/ ? pg : 1), (pgs ~ /^[0-9]+$/ ? pgs : 1), + (sms_used ~ /^[0-9]+$/ ? sms_used : -1), + (sms_total ~ /^[0-9]+$/ ? sms_total : 0), + (sms_seen ~ /^[0-9]+$/ ? sms_seen : 0) next } { @@ -294,9 +303,17 @@ m_sms_delete() { sim=$(inp '@.sim') case "$id" in all|[0-9][0-9]*) ;; *) printf '{"ok":0,"error":"bad id"}\n'; return ;; esac # sim=1 also removes the message from the SIM storage (mu300-sms delete --sim) - [ "$sim" = 1 ] && "$SMS" delete "$id" --sim >/dev/null 2>&1 || - "$SMS" delete "$id" >/dev/null 2>&1 - printf '{"ok":1}\n' + local out + if [ "$sim" = 1 ]; then + out=$("$SMS" delete "$id" --sim 2>&1) + else + out=$("$SMS" delete "$id" 2>&1) + fi + if [ $? = 0 ]; then + printf '{"ok":1}\n' + else + printf '{"ok":0,"error":"%s"}\n' "$(esc_ml "$(printf '%s\n' "$out" | tail -n1)")" + fi } m_sms_sync() { @@ -326,6 +343,12 @@ do_list() { "sms_send": { "num": "String", "text": "String" }, "sms_delete": { "id": "String", "sim": "String" }, "sms_sync": { }, + "forward_get": { }, + "forward_status": { }, + "forward_set": { "payload": "String" }, + "forward_test": { }, + "traffic_get": { }, + "traffic_set": { "payload": "String" }, "usb_get": { }, "usb_set": { "kind": "String", "value": "String", "scope": "String", "auto": "String" }, "usb_net_list": { }, @@ -375,6 +398,23 @@ call) sms_send) run_m sms_send 'm_sms_send' ;; sms_delete) run_m sms_delete 'm_sms_delete' ;; sms_sync) run_m sms_sync 'm_sms_sync' ;; + forward_get) "$DASH/sms-forward" get ;; + forward_status) "$DASH/sms-forward" status ;; + forward_set) + payload=$(inp '@.payload') + printf '%s' "$payload" | "$DASH/sms-forward" set + ;; + forward_test) + # Delivery can take 25 s and must not tie up the LuCI RPC request. + setsid "$DASH/sms-forward" test-run >/dev/null 2>&1 & + printf '{"ok":1,"started":1}\n' + ;; + traffic_get) + ubus -t 3 call unisoc.traffic get 2>/dev/null || printf '{"error":"traffic_unavailable"}\n' + ;; + traffic_set) + ubus -t 5 call unisoc.traffic set "$INPUT" 2>/dev/null || printf '{"ok":0,"error":"traffic_unavailable"}\n' + ;; usb_get) run_m usb_get '"$DASH/device-usb" get' ;; usb_set) kind=$(inp '@.kind'); value=$(inp '@.value'); scope=$(inp '@.scope'); auto=$(inp '@.auto') diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cell b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cell index 58487f22..aab4bcd8 100644 --- a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cell +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cell @@ -21,15 +21,16 @@ # AT+SPENGMD=0,6,0 Unisoc engineering: LTE serving cell (band/EARFCN/PCI/RSRP/RSRQ/bandwidth/ECI/TAC) # AT+SPENGMD=0,14,1 NR serving cell (band/ARFCN/PCI/RSRP/RSRQ/SINR/MCS/BLER) # AT+SPENGMD=0,6,6 LTE neighbour slots (8 x 12 fields, first 4 per slot are the reading) -# AT+SPQ5GNCELLEX NR neighbour table with real per-cell SINR +# AT+SPENGMD=0,14,2 NR neighbour arrays with per-cell band and SINR +# AT+SPQ5GNCELLEX fallback NR neighbour table (no per-cell band) # AT+CGEQOSRDP=1 QCI + up/down AMBR of the active bearer # AT+SPENGMD=0,1,0 is NEVER sent: it switches the AT port into streaming mode and # kills the channel until the next reboot (V50 archive; blacklisted in the rpcd # AT terminal too). # -# SIM/module identity (IMEI/IMSI/ICCID/model/firmware) changes only when the SIM +# SIM/module identity (IMEI/IMSI/ICCID/phone number/model/firmware) changes only when the SIM # or the firmware changes, so it lives in the configured state directory and is re-read -# at most every 6 hours - not on every round, and never inside a page request. +# once per boot and at most every 6 hours thereafter, never inside a page request. # Two rounds share this script: # mu300-dash-cell full: everything below, ~11 commands, neighbours included @@ -52,6 +53,8 @@ IDENT_DIR=${MU300_DASH_IDENT_DIR:-${STATE_DIR%/lock-state.d}} IDENT=$IDENT_DIR/sim.json AT=${MU300_AT:-/usr/libexec/unisoc-modem/at} IDENT_MAXAGE=21600 # seconds; a SIM change goes through a reboot, 6 h is plenty +BOOT_ID= +[ ! -r /proc/sys/kernel/random/boot_id ] || IFS= read -r BOOT_ID < /proc/sys/kernel/random/boot_id mkdir -p "$DIR" "$IDENT_DIR" 2>/dev/null @@ -77,6 +80,35 @@ at() { now() { date +%s; } n_or_null() { case "$1" in ''|*[!0-9]*) echo null ;; *) echo "$1" ;; esac; } qs() { [ -n "$1" ] && printf '"%s"' "$(printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | tr -d '\r\n')" || echo null; } +cnum_number() { + # +CNUM: "alpha","number",type[,speed,service,...]. Ignore the label, + # echoes and empty entries; an unprovisioned SIM legitimately has no number. + awk -F '"' '/^\+CNUM:/ { + n=$4; gsub(/[ ()-]/, "", n) + if (n !~ /^\+?[0-9]+$/ || length(n) > 32) next + if ($5 ~ /^[[:space:]]*,[[:space:]]*145([[:space:]]*,|[[:space:]]*$)/ && n !~ /^\+/) n="+" n + print n; exit + }' +} +ims_number() { + # The stock F50 RIL's getPAU request uses AT+SPPAURI?. Prefer an explicit + # tel URI, otherwise an international SIP user part. A numeric SIP IMSI + # without '+' is not sufficient evidence of a telephone number. + awk '/^\+SPPAURI:/ { + sub(/^\+SPPAURI:[[:space:]]*/, "") + count=split($0, fields, /[[:space:]",<>]+/) + for (i=1; i<=count; i++) { + uri=fields[i]; lower=tolower(uri) + if (lower !~ /^(tel|sips?):/) continue + n=uri; sub(/^[^:]*:/, "", n); sub(/[@;?].*$/, "", n) + gsub(/[().-]/, "", n) + digits=n; sub(/^\+/, "", digits) + if (digits !~ /^[0-9]+$/ || length(digits)<3 || length(digits)>15) continue + if (lower ~ /^tel:/) { found=1; print n; exit } + if (n ~ /^\+/ && sip == "") sip=n + } + } END { if (!found && sip != "") print sip }' +} # --------------------------------------------------------------- one collector # the same "one owner, spare waits/takes over" pattern mu300-atd uses, so two @@ -134,7 +166,7 @@ IDENT_JSON=null # (No backslash line continuations inside the awk: comma-newline is portable, # busybox awk does not promise the GNU one.) sp_fragment() { # sp_fragment MODE LINE [PHYLINE] (MODE: lte | nr | ltenb) - [ -n "$2" ] || { echo null; return; } + [ -n "$2" ] || { [ "$1" = ltenb ] || echo null; return; } awk -v mode="$1" -v line="$2" -v phy="${3:-}" ' function norm(l, arr, s, n, i) { s = l; gsub(/\r/, "", s) @@ -171,13 +203,7 @@ sp_fragment() { # sp_fragment MODE LINE [PHYLINE] (MODE: lte | nr | ltenb) return (v == "" || v == "NA" || v == "N/A") ? "null" : "\"" v "\"" } function lteband(fr, a,b,r,i,n) { - n = split("1:0-599 2:600-1199 3:1200-1949 4:1950-2399 5:2400-2649 7:2750-3449 8:3450-3799 12:5010-5179 13:5180-5279 14:5280-5379 17:5730-5849 18:5850-5999 19:6000-6149 20:6150-6449 25:8040-8689 26:8690-9039 27:9040-9209 28:9210-9659 30:9770-9869 31:9870-9919 33:36000-36199 34:36200-36349 35:36350-36949 36:36950-37549 37:37550-37749 38:37750-38249 39:38250-38649 40:38650-39649 41:39650-41589 42:41590-43589 43:43590-45589 44:45590-46589 46:46790-54539 47:54540-55239 48:55240-56739 49:56740-58239 50:58240-59089 51:59090-59139 65:65536-66435 66:66436-67335", a, " ") - for (i = 1; i <= n; i++) { split(a[i], b, ":"); split(b[2], r, "-") - if (fr >= r[1] && fr <= r[2]) return b[1] } - return 0 - } - function nrband(fr, a,b,r,i,n) { - n = split("1:422000-434000 3:361000-376000 5:173800-178800 8:185000-192000 28:151600-160600 40:460000-480000 41:499200-537999 77:620000-680000 78:620000-653333 79:693334-733333", a, " ") + n = split("1:0-599 2:600-1199 3:1200-1949 4:1950-2399 5:2400-2649 6:2650-2749 7:2750-3449 8:3450-3799 9:3800-4149 10:4150-4749 11:4750-4949 12:5010-5179 13:5180-5279 14:5280-5379 17:5730-5849 18:5850-5999 19:6000-6149 20:6150-6449 21:6450-6599 22:6600-7399 23:7500-7699 24:7700-8039 25:8040-8689 26:8690-9039 27:9040-9209 28:9210-9659 29:9660-9769 30:9770-9869 31:9870-9919 32:9920-10359 33:36000-36199 34:36200-36349 35:36350-36949 36:36950-37549 37:37550-37749 38:37750-38249 39:38250-38649 40:38650-39649 41:39650-41589 42:41590-43589 43:43590-45589 44:45590-46589 45:46590-46789 46:46790-54539 47:54540-55239 48:55240-56739 49:56740-58239 50:58240-59089 51:59090-59139 52:59140-60139 65:65536-66435 66:66436-67335 67:67336-67535 68:67536-67835 69:67836-68335 70:68336-68585 71:68586-68935 72:68936-68985 73:68986-69035 74:69036-69465 75:69466-70315 76:70316-70365 85:70366-70545", a, " ") for (i = 1; i <= n; i++) { split(a[i], b, ":"); split(b[2], r, "-") if (fr >= r[1] && fr <= r[2]) return b[1] } return 0 @@ -226,38 +252,68 @@ sp_fragment() { # sp_fragment MODE LINE [PHYLINE] (MODE: lte | nr | ltenb) printf "{\"band\":%d,\"arfcn\":%d,\"pci\":%d,\"rsrp\":%s,\"rsrq\":%s,\"sinr\":%s,\"bw_mhz\":%s,\"gnb\":%s,\"cid\":%s,\"ul_mcs\":%s,\"dl_mcs\":%s,\"ul_bler\":%s,\"dl_bler\":%s}", band, arfcn, pci, c1(f(t[3])), c1(f(t[4])), c1(f(t[15])), num(bw), fs(t[8]), fs(t[9]), num(f(t[16])), num(f(t[17])), c1(f(t[18])), c1(f(t[19])) - } else { # ltenb: eight 12-field slots, first four are EARFCN/PCI/RSRP/RSRQ + } else { # ltenb: up to eight dash-delimited 12-field CSV blocks out = "" - for (s = 0; s < 8; s++) { - b = s*12; if (b+3 >= n) break - earfcn = f(t[b]); pci = f(t[b+1]) + for (s = 0; s < n && s < 8; s++) { + fields = split(t[s], row, ","); if (fields < 4) continue + earfcn = f(row[1]); pci = f(row[2]) if (earfcn == 0 && pci == 0) continue out = out sprintf("{\"rat\":\"lte\",\"band\":%d,\"arfcn\":%d,\"pci\":%d,\"rsrp\":%s,\"rsrq\":%s},", - lteband(earfcn), earfcn, pci, c1(f(t[b+2])), c1(f(t[b+3]))) + lteband(earfcn), earfcn, pci, c1(f(row[3])), c1(f(row[4]))) } sub(/,$/, "", out); print (out == "" ? "" : out) } }' } -nr_neighbours() { # SPQ5GNCELLEX CSV: serving 8-tuple, count at index 8, then 8-tuples (arfcn,pci,rsrp,rsrq,sinr,..) +nr_neighbours() { # SPENGMD: band/ARFCN/PCI/RSRP/RSRQ/SINR arrays; SPQ fallback has no band [ -n "$1" ] || { echo ""; return; } - awk -v line="$1" ' + awk -v line="$1" -v source="$2" ' + function signed(v) { gsub(/\+/, "-", v); return v+0 } function nrband(fr, a,b,r,i,n) { - n = split("1:422000-434000 3:361000-376000 5:173800-178800 8:185000-192000 28:151600-160600 40:460000-480000 41:499200-537999 77:620000-680000 78:620000-653333 79:693334-733333", a, " ") + # n78 is contained in n77. The fallback does not report the band, + # so their shared ARFCNs must remain ambiguous rather than n77. + if (fr >= 620000 && fr <= 653333) return "null" + n = split("1:422000-434000 3:361000-376000 5:173800-178800 8:185000-192000 28:151600-160600 40:460000-480000 41:499200-537999 77:653334-680000 79:693334-733333", a, " ") for (i = 1; i <= n; i++) { split(a[i], b, ":"); split(b[2], r, "-") if (fr >= r[1] && fr <= r[2]) return b[1] } - return 0 + return "null" } BEGIN { + if (source == "spengmd") { + # Unisoc uses "-" between arrays but "+" for negative values. + # Restore the signs before splitting; do not infer band from ARFCN. + gsub(/\r/, "", line) + gsub(/,-/, ",+", line); gsub(/--/, "-+", line); sub(/^-/, "+", line) + n = split(line, field, "-") + if (n < 6) exit + count = split(field[1], bands, ",") + a = split(field[2], arfcns, ","); if (a < count) count = a + a = split(field[3], pcis, ","); if (a < count) count = a + a = split(field[4], rsrps, ","); if (a < count) count = a + a = split(field[5], rsrqs, ","); if (a < count) count = a + a = split(field[6], sinrs, ","); if (a < count) count = a + for (i = 1; i <= count; i++) { + if (bands[i] !~ /^[0-9]+$/ || arfcns[i] !~ /^[0-9]+$/ || pcis[i] !~ /^[0-9]+$/) continue + if (rsrps[i] !~ /^\+?[0-9]+$/ || rsrqs[i] !~ /^\+?[0-9]+$/ || sinrs[i] !~ /^\+?[0-9]+$/) continue + if (bands[i]+0 == 0 || arfcns[i]+0 == 0) continue + out = out sprintf("{\"rat\":\"nr\",\"band\":%d,\"arfcn\":%d,\"pci\":%d,\"rsrp\":%.1f,\"rsrq\":%.1f,\"sinr\":%.1f},", + bands[i], arfcns[i], pcis[i], signed(rsrps[i])/100, signed(rsrqs[i])/100, signed(sinrs[i])/100) + } + sub(/,$/, "", out); print out + exit + } + # SPQ5GNCELLEX CSV: serving 8-tuple, count at index 8, then + # 8-tuples (arfcn,pci,rsrp,rsrq,sinr,...). It has no band field. m = split(line, a, ","); cnt = a[9]+0 out = "" for (i = 0; i < cnt && i < 8; i++) { b = 9 + i*8; if (b+5 > m) break fr = a[b+1]+0; pci = a[b+2]+0 if (fr == 0 && pci == 0) continue - out = out sprintf("{\"rat\":\"nr\",\"band\":%d,\"arfcn\":%d,\"pci\":%d,\"rsrp\":%.1f,\"rsrq\":%.1f,\"sinr\":%.1f},", - nrband(fr), fr, pci, a[b+3]/100, a[b+4]/100, a[b+5]/100) + out = out sprintf("{\"rat\":\"nr\",\"band\":%s,\"band_candidates\":%s,\"arfcn\":%d,\"pci\":%d,\"rsrp\":%.1f,\"rsrq\":%.1f,\"sinr\":%.1f},", + nrband(fr), (fr >= 620000 && fr <= 653333) ? "[77,78]" : "[]", + fr, pci, a[b+3]/100, a[b+4]/100, a[b+5]/100) } sub(/,$/, "", out); print out }' @@ -316,7 +372,7 @@ R4=$(printf '%s\n' "$CEREG" | tr -d '"' | awk -F',' '{ gsub(/ /,"",$2); print $2 R5=$(printf '%s\n' "$C5GREG" | tr -d '"' | awk -F',' '{ gsub(/ /,"",$2); print $2 }') REGISTERED=0 case "$R4:$R5" in 1:*|5:*|10:*|*:1|*:5|*:10) REGISTERED=1 ;; esac -SP_LTE=; SP_LTEPHY=; SP_NR=; SP_LN=; SP_NRNB=; QOS=; COPS= +SP_LTE=; SP_LTEPHY=; SP_NR=; SP_LN=; SP_NRNB=; SP_NRNB_SOURCE=; QOS=; COPS= if [ "$REGISTERED" = 1 ]; then SP_LTE=$(at 'AT+SPENGMD=0,6,0' 2 | grep -v '^AT' | grep -- '-' | head -n1) SP_LTEPHY=$(at 'AT+SPENGMD=0,0,6' 2 | grep -v '^AT' | grep -- '-' | head -n1) @@ -326,12 +382,19 @@ if [ "$MODE" = full ]; then COPS=$(at 'AT+COPS?' 2 | grep '^+COPS:' | head -n1) if [ "$REGISTERED" = 1 ]; then SP_LN=$(at 'AT+SPENGMD=0,6,6' 2 | grep -v '^AT' | grep -- '-' | head -n1) - SP_NRNB=$(at 'AT+SPQ5GNCELLEX' 2 | sed -n 's/^+SPQ5GNCELLEX: *//p' | head -n1) + SP_NRNB=$(at 'AT+SPENGMD=0,14,2' 2 | grep -v '^AT' | grep -- '-' | head -n1) + SP_NRNB_SOURCE=spengmd + if [ -z "$SP_NRNB" ]; then + SP_NRNB=$(at 'AT+SPQ5GNCELLEX' 2 | sed -n 's/^+SPQ5GNCELLEX: *//p' | head -n1) + SP_NRNB_SOURCE=spq + fi QOS=$(at 'AT+CGEQOSRDP=1' 2 | sed -n 's/^+CGEQOSRDP: *//p' | head -n1) fi IDENT_AGE=999999 [ -s "$IDENT" ] && IDENT_AGE=$(( $(now) - $(date -r "$IDENT" +%s 2>/dev/null || echo 0) )) - if [ "$IDENT_AGE" -le "$IDENT_MAXAGE" ]; then + if [ "$IDENT_AGE" -ge 0 ] && [ "$IDENT_AGE" -le "$IDENT_MAXAGE" ] && + [ -n "$BOOT_ID" ] && grep -Fq "\"boot_id\":\"$BOOT_ID\"" "$IDENT" && + grep -q '"msisdn"[[:space:]]*:' "$IDENT"; then IDENT_JSON=$(cat "$IDENT" 2>/dev/null || echo null) else i_mfg=$(at 'AT+CGMI' 2 | grep -v '^OK' | head -n1) @@ -341,8 +404,18 @@ if [ "$MODE" = full ]; then i_imsi=$(at 'AT+CIMI' 2 | tr -cd '0-9' | cut -c1-15) i_iccid=$(at 'AT+CCID' 2 | tr -cd '0-9' | cut -c1-20) if [ -n "$i_imei$i_imsi$i_iccid" ]; then - IDENT_JSON=$(printf '{"ts":%d,"mfg":%s,"model":%s,"fw":%s,"imei":%s,"imsi":%s,"iccid":%s}' \ - "$(now)" "$(qs "$i_mfg")" "$(qs "$i_model")" "$(qs "$i_fw")" "$(qs "$i_imei")" "$(qs "$i_imsi")" "$(qs "$i_iccid")") + # Keep this optional query out of the live signal polling path. + # Cache a null too, so a SIM without a number is not queried again + # on every full refresh. Older identity caches migrate once. + i_msisdn=$(at 'AT+CNUM' 2 | cnum_number) + i_msisdn_source=sim + if [ -z "$i_msisdn" ]; then + i_msisdn=$(at 'AT+SPPAURI?' 2 | ims_number) + i_msisdn_source=ims + fi + [ -n "$i_msisdn" ] || i_msisdn_source= + IDENT_JSON=$(printf '{"ts":%d,"boot_id":%s,"mfg":%s,"model":%s,"fw":%s,"imei":%s,"imsi":%s,"iccid":%s,"msisdn":%s,"msisdn_source":%s}' \ + "$(now)" "$(qs "$BOOT_ID")" "$(qs "$i_mfg")" "$(qs "$i_model")" "$(qs "$i_fw")" "$(qs "$i_imei")" "$(qs "$i_imsi")" "$(qs "$i_iccid")" "$(qs "$i_msisdn")" "$(qs "$i_msisdn_source")") printf '%s\n' "$IDENT_JSON" > "$IDENT.part" 2>/dev/null && mv "$IDENT.part" "$IDENT" elif [ -s "$IDENT" ]; then IDENT_JSON=$(cat "$IDENT"); fi fi @@ -377,7 +450,7 @@ printf '{"ts":%d,"cfun":%s,"reg":%s,"reg5g":%s,"sig_src":"%s","sig":%s,"lte":%s, # the full tier: everything else the page needs only every few seconds LN=$(sp_fragment ltenb "$SP_LN") -NN=$(nr_neighbours "$SP_NRNB") +NN=$(nr_neighbours "$SP_NRNB" "$SP_NRNB_SOURCE") # one neighbour list, NR first (the page shows NR cells at the top) if [ -n "$NN" ] && [ -n "$LN" ]; then NEIGH="[$NN,$LN]" elif [ -n "$NN" ]; then NEIGH="[$NN]" diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/dashboard-info b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/dashboard-info index 060a094c..2935000a 100644 --- a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/dashboard-info +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/dashboard-info @@ -29,25 +29,66 @@ BB=/opt/mu300/bin/busybox t3() { "$BB" timeout -s KILL 3 "$@" 2>/dev/null; } # external asks: netifd, uci, iw... t2() { "$BB" timeout -s KILL 2 "$@" 2>/dev/null; } -rd() { cat "$1" 2>/dev/null; } +# All callers except the device-tree fallback read one-line proc/sysfs text. +# A shell builtin avoids starting cat for every thermal zone, battery and +# interface counter (dozens of short-lived processes per snapshot). +rd() { + [ -r "$1" ] || return 0 + IFS= read -r _rd < "$1" || : + printf '%s\n' "$_rd" +} n_or_null() { case "$1" in ''|*[!0-9.-]*) echo null ;; *) echo "$1" ;; esac; } f_or_null() { case "$1" in ''|*[!0-9.-]*) echo null ;; *) echo "$1" ;; esac; } -# JSON string escaping (and drop newlines: the output is one line) -esc() { printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | tr -d '\r\n'; } -qs() { [ -n "$1" ] && printf '"%s"' "$(esc "$1")" || echo null; } +# JSON string escaping (and drop newlines: the output is one line). +# Avoid a sed+tr process pair for every hostname, address and client field. +CR=$(printf '\r') +NL=$(printf '\nx'); NL=${NL%x} +esc() { + local value=$1 out= ch + while [ -n "$value" ]; do + ch=${value%"${value#?}"}; value=${value#?} + case "$ch" in + "\\") out="$out\\\\" ;; + '"') out="$out\\\"" ;; + "$CR"|"$NL") ;; + *) out=$out$ch ;; + esac + done + printf '%s' "$out" +} +qs() { [ -n "$1" ] && { printf '"'; esc "$1"; printf '"'; } || printf 'null'; } # ------------------------------------------------------------- temperature # type -> label, the four zones this SoC actually has; hottest covers the rest -temp_of() { - local z t +# Read all zone types in one pass instead of rescanning every zone four times. +named_temps() { + local z type temp seen_soc= seen_cpu= seen_nr= seen_brd= + local raw_soc= raw_cpu= raw_nr= raw_brd= for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/type" ] || continue - [ "$(rd "$z/type")" = "$1" ] || continue - t=$(rd "$z/temp") - [ -n "$t" ] || return 0 - awk -v v="$t" 'BEGIN{printf "%.1f", v/1000}' - return 0 + type=; IFS= read -r type < "$z/type" || : + case "$type" in + soc-thmzone) [ -z "$seen_soc" ] || continue; seen_soc=1 ;; + apcpu0-thmzone) [ -z "$seen_cpu" ] || continue; seen_cpu=1 ;; + nr0-thmzone) [ -z "$seen_nr" ] || continue; seen_nr=1 ;; + board-thmzone) [ -z "$seen_brd" ] || continue; seen_brd=1 ;; + *) continue ;; + esac + temp=; [ -r "$z/temp" ] && IFS= read -r temp < "$z/temp" || : + case "$type" in + soc-thmzone) raw_soc=$temp ;; + apcpu0-thmzone) raw_cpu=$temp ;; + nr0-thmzone) raw_nr=$temp ;; + board-thmzone) raw_brd=$temp ;; + esac done + awk -v soc="$raw_soc" -v cpu="$raw_cpu" -v nr="$raw_nr" -v brd="$raw_brd" ' + BEGIN { + printf "%s %s %s %s", soc=="" ? "null" : sprintf("%.1f", soc/1000), + cpu=="" ? "null" : sprintf("%.1f", cpu/1000), + nr=="" ? "null" : sprintf("%.1f", nr/1000), + brd=="" ? "null" : sprintf("%.1f", brd/1000) + }' } temp_hottest() { rd /sys/class/thermal/thermal_zone*/temp 2>/dev/null | sort -n | tail -n1 | awk '{printf "%.1f", $1/1000}' @@ -87,11 +128,12 @@ apn=$(t3 uci -q get "network.$DATA_IFACE.apn") # ------------------------------------------------------------------- system NOW=$(date +%s) -UPTIME=$(cut -d' ' -f1 /proc/uptime | cut -d. -f1) +read -r UPTIME _ < /proc/uptime +UPTIME=${UPTIME%%.*} HOST=$(t3 uci -q get system.@system[0].hostname) [ -n "$HOST" ] || HOST=$(rd /proc/sys/kernel/hostname) MODEL=$(rd /tmp/sysinfo/model 2>/dev/null) -[ -n "$MODEL" ] || MODEL=$(rd /proc/device-tree/model 2>/dev/null | tr -d '\0') +[ -n "$MODEL" ] || MODEL=$(cat /proc/device-tree/model 2>/dev/null | tr -d '\0') FW=$(sed -n "s/^DISTRIB_DESCRIPTION='\(.*\)'$/\1/p" /etc/openwrt_release 2>/dev/null) [ -n "$FW" ] || FW=$(uname -sr) @@ -105,7 +147,7 @@ CPUN=$(grep -c '^processor' /proc/cpuinfo) FREQS= for p in /sys/devices/system/cpu/cpufreq/policy*/scaling_cur_freq; do [ -r "$p" ] || continue - d=$(dirname "$p") + d=${p%/*} FREQS="$FREQS{\"cur\":$(n_or_null "$(rd "$p")"),\"max\":$(n_or_null "$(rd "$d/cpuinfo_max_freq")")}," done FREQS=${FREQS%,} @@ -117,10 +159,8 @@ MEM_A=$(awk '/^MemAvailable/{print $2}' /proc/meminfo) DF=$(df -k / 2>/dev/null | awk 'NR==2{print $2, $3, $4}') set -- $DF; DISK_T=$1; DISK_U=$2; DISK_A=$3 -T_SOC=$(temp_of soc-thmzone) -T_CPU=$(temp_of apcpu0-thmzone) -T_NR=$(temp_of nr0-thmzone) -T_BRD=$(temp_of board-thmzone) +set -- $(named_temps) +T_SOC=$1; T_CPU=$2; T_NR=$3; T_BRD=$4 T_HOT=$(temp_hottest) # ------------------------------------------------------------------- power @@ -154,48 +194,87 @@ net_obj() { # net_obj IFACE -> {"rx":N,"tx":N,"up":0|1} or null # ONE "uci show wireless" instead of nine "uci get": each uci call costs a fork # plus config parse and they added up to most of this script's runtime. WSHOW=$(t3 uci -q show wireless 2>/dev/null) -wu() { # wu KEY -> value ('' when absent); KEY like "radio0.channel" - printf '%s\n' "$WSHOW" | sed -n "s/^wireless\\.$1='\\(.*\\)'$/\\1/p" | head -n1 -} # anonymous sections appear in "uci show" under their cfg id, and named ones use # their name - either way the section type line has no quotes; resolve the first # wifi-iface section once and read its options through that key -IFKEY=$(printf '%s\n' "$WSHOW" | sed -n "s/^wireless\\.\\([^.]*\\)=wifi-iface\$/\\1/p" | head -n1) -W_SSID=$(wu "${IFKEY:-x}.ssid") -W_CH=$(wu 'radio0.channel') -W_BAND=$(wu 'radio0.band') -[ -n "$W_BAND" ] || W_BAND=$(wu 'radio0.hwmode') -W_HT=$(wu 'radio0.htmode') # HE80 / VHT40 / HT20 -> the number is the width -W_WIDTH=$(printf '%s' "$W_HT" | tr -cd '0-9' | head -c 2) +IFKEY= +while IFS= read -r line; do + case "$line" in + wireless.*=wifi-iface) + IFKEY=${line#wireless.}; IFKEY=${IFKEY%%=*} + case "$IFKEY" in *.*) IFKEY= ;; *) break ;; esac + ;; + esac +done </dev/null) printf '%s' "$HAPD" | grep -q '"status": *"ENABLED"' && W_HOSTAPD=1 -W_DIS=$(wu 'radio0.disabled') [ "$W_DIS" = "1" ] && W_UP=0 || W_UP=1 [ -d "/sys/class/net/$WIFI_DEVICE" ] || W_UP=0 [ "$W_HOSTAPD" = 1 ] || W_UP=0 -# station table: one block per client - mac, signal, tx/rx bitrate, connected time -W_CLIENTS=$(t3 iw dev "$WIFI_DEVICE" station dump 2>/dev/null | awk -F':\t*' ' - /^Station / { mac = $2; sub(/ .*/, "", mac); sig = tx = rx = ct = "" } - /^ signal:/ { sig = $2 + 0 } - /^ tx bitrate:/ { tx = $2; sub(/ .*/, "", tx); sub(/$/, " Mbit/s", tx) } - /^ rx bitrate:/ { rx = $2; sub(/ .*/, "", rx); sub(/$/, " Mbit/s", rx) } - /^ connected time:/ { ct = $2 + 0; ct = int(ct / 60) + " min" } - mac != "" && sig != "" && !seen[mac]++ { - printf "%s|%s|%s|%s|%s\n", mac, sig, tx, rx, ct; sig = "" - }') -W_CN=0; W_CLIST= +# SC2355 may report only associated MACs, with no station metrics. Count the +# association regardless of RSSI and emit after the COMPLETE block, not at +# the signal line. Whitespace splitting leaves the colons inside a MAC intact. +station_rows() { + awk ' + function emit( a, n, i) { + n = split(mac, a, ":") + if (n != 6) return + for (i = 1; i <= n; i++) + if (a[i] !~ /^[[:xdigit:]][[:xdigit:]]$/) return + if (seen[mac]++) return + printf "%s|%s|%s|%s|%s\n", mac, sig, tx, rx, ct + } + /^Station[ \t]+/ { emit(); mac = tolower($2); sig = tx = rx = ct = ""; next } + /^[ \t]+signal:/ && $2 ~ /^-?[0-9]+([.][0-9]+)?$/ { sig = $2 + 0 } + /^[ \t]+tx bitrate:/ && $3 ~ /^[0-9]+([.][0-9]+)?$/ { tx = $3 " Mbit/s" } + /^[ \t]+rx bitrate:/ && $3 ~ /^[0-9]+([.][0-9]+)?$/ { rx = $3 " Mbit/s" } + /^[ \t]+connected time:/ && $3 ~ /^[0-9]+$/ { ct = sprintf("%d min", int($3 / 60)) } + END { emit() }' +} +W_CN=null; W_CLIST=; W_CLIENTS= +if W_STATIONS=$(t3 iw dev "$WIFI_DEVICE" station dump 2>/dev/null); then + W_CLIENTS=$(printf '%s\n' "$W_STATIONS" | station_rows) + W_CN=0 +elif [ ! -d "/sys/class/net/$WIFI_DEVICE" ]; then + W_CN=0 +fi while IFS='|' read -r mac sig txr rxr ct; do [ -n "$mac" ] || continue - umac=$(echo "$mac" | tr 'a-f' 'A-F') - line=$(awk -v m="$umac" '$2 == m { print $3 "|" $4; exit }' /tmp/dhcp.leases 2>/dev/null) + line=$(awk -v m="$mac" 'tolower($2) == m { print $3 "|" $4; exit }' /tmp/dhcp.leases 2>/dev/null) ip=${line%%|*}; host=${line#*|} - [ "$host" = "$line" ] && host= + { [ "$host" = "$line" ] || [ "$host" = '*' ]; } && host= W_CLIST="$W_CLIST{\"mac\":\"$mac\",\"host\":$(qs "$host"),\"ip\":$(qs "$ip"),\"signal\":$(n_or_null "$sig"),\"tx\":$(qs "$txr"),\"rx\":$(qs "$rxr"),\"conn\":$(qs "$ct")}," W_CN=$((W_CN + 1)) done </dev/null 2>&1 && ATD_OK=1 [ "$MODEM_ALIVE" = 1 ] || MODEM_ALIVE=$ATD_OK DATA_PAUSED=0; [ -e /run/mu300-mobile-data-down ] && DATA_PAUSED=1 -CONNS=$(cat /proc/net/nf_conntrack 2>/dev/null | wc -l) +# Constant-size counter works without CONFIG_NF_CONNTRACK_PROCFS. Only older +# platforms lacking this counter need the connection-table fallback. +# Missing/failed reads are unknown (null), never a made-up zero. +conntrack_count() { + local counter=${1:-/proc/sys/net/netfilter/nf_conntrack_count} + local table=${2:-/proc/net/nf_conntrack} count= + # sysctl proc handlers may return EOF after the first small read; ash's + # byte-at-a-time read can truncate this value. Read it in one cat buffer. + if [ -r "$counter" ] && count=$(cat "$counter" 2>/dev/null); then + case "$count" in ''|*[!0-9]*) ;; *) printf '%s\n' "$count"; return ;; esac + fi + if [ -r "$table" ] && count=$(wc -l < "$table" 2>/dev/null); then + count=$((count + 0)) + printf '%s\n' "$count" + return + fi + printf 'null\n' +} +CONNS=$(conntrack_count) # --------------------------------------------------------------------- VPN VPN_ENABLED=0; VPN_ENGINE=""; VPN_UP=0 @@ -252,14 +349,22 @@ printf '"temps":{"soc":%s,"cpu":%s,"modem":%s,"board":%s,"hottest":%s},' \ "$(f_or_null "$T_SOC")" "$(f_or_null "$T_CPU")" "$(f_or_null "$T_NR")" "$(f_or_null "$T_BRD")" "$(f_or_null "$T_HOT")" printf '"power":{"present":%d,"capacity":%s,"status":%s,"volt":%s,"ua":%s,"usb":%s},' \ "$P_PRESENT" "$(n_or_null "$P_CAP")" "$(qs "$P_STATUS")" "$P_V" "$P_I" "$(n_or_null "$P_USB")" +MOBILE_NET=$(net_obj "$DATA_DEVICE") printf '"net":{"mobile":%s,"sipa_eth0":%s,"brlan":%s,"wlan0":%s,"usb0":%s},' \ - "$(net_obj "$DATA_DEVICE")" "$(net_obj "$DATA_DEVICE")" "$(net_obj "$LAN_DEVICE")" "$(net_obj "$WIFI_DEVICE")" "$(net_obj "$USB_DEVICE")" + "$MOBILE_NET" "$MOBILE_NET" "$(net_obj "$LAN_DEVICE")" "$(net_obj "$WIFI_DEVICE")" "$(net_obj "$USB_DEVICE")" printf '"wan":{"up":%d,"uptime":%s,"proto":%s,"apn":%s,"ip4":%s,"ip6":%s,"dns":%s},' \ "$wan_up" "$(n_or_null "$wan_uptime")" "$(qs "$wan_proto")" "$(qs "$apn")" "$(qs "$wan_ip4")" "$(qs "$wan6_ip")" "$(qs "$wan_dns")" -printf '"wifi":{"up":%d,"ssid":%s,"channel":%s,"band":%s,"width":%s,"country":%s,"enc":%s,"hidden":%s,"hostapd":%d,"clients":[%s],"clients_n":%d},' \ +printf '"wifi":{"up":%d,"ssid":%s,"channel":%s,"band":%s,"width":%s,"country":%s,"enc":%s,"hidden":%s,"hostapd":%d,"clients":[%s],"clients_n":%s},' \ "$W_UP" "$(qs "$W_SSID")" "$(qs "$W_CH")" "$(qs "$W_BAND")" "$(qs "$W_WIDTH")" "$(qs "$W_COUNTRY")" "$(qs "$W_ENC")" "$(n_or_null "$W_HIDDEN")" "$W_HOSTAPD" "${W_CLIST:-}" "$W_CN" printf '"lan":{"leases":%s,"ip":%s,"list":[%s]},' "$(n_or_null "$LAN_LEASES")" "$(qs "$LAN_IP")" "${LEASES:-}" printf '"modem":{"alive":%d,"atd":%d,"data_paused":%d},' "$MODEM_ALIVE" "$ATD_OK" "$DATA_PAUSED" printf '"capabilities":{"vpn":%d,"dualboot":%d},' "$CAP_VPN" "$CAP_DUALBOOT" printf '"conns":%s,' "$(n_or_null "$CONNS")" +# The accounting worker publishes one atomic JSON line; no extra RPC or AT +# requests on the dashboard's fast refresh path. +TRAFFIC=null +if [ -r /run/unisoc-modem-traffic/view.json ]; then + IFS= read -r TRAFFIC < /run/unisoc-modem-traffic/view.json || TRAFFIC=null +fi +printf '"traffic":%s,' "${TRAFFIC:-null}" printf '"vpn":{"enabled":%d,"engine":%s,"up":%d}}\n' "$VPN_ENABLED" "$(qs "$VPN_ENGINE")" "$VPN_UP" diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/sms-forward b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/sms-forward new file mode 100644 index 00000000..3585a462 --- /dev/null +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/sms-forward @@ -0,0 +1,702 @@ +#!/bin/sh +# Standalone, opt-in SMS forwarding. Never polls the modem: the platform SMS +# adapter owns AT and writes complete, atomically-renamed files to the pool. +umask 077 +export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin" +. /usr/share/libubox/jshn.sh + +BASE=${MU300_FORWARD_DIR:-/etc/unisoc-modem/forward} +POOL=${MU300_SMS_POOL:-$(uci -q get unisoc_modem.main.sms_pool 2>/dev/null)} +[ -d "${POOL:-/etc/unisoc-modem/sms}/msg" ] || [ ! -d /etc/mu300/sms/msg ] || POOL=/etc/mu300/sms +POOL=${POOL:-/etc/unisoc-modem/sms} +CONFIG=$BASE/config.json +STATE=$BASE/state +RESULT=${MU300_FORWARD_RESULT:-/run/unisoc-modem-forward-result} +SMS=${MU300_SMS_BIN:-$(uci -q get unisoc_modem.main.sms_command 2>/dev/null)} +[ -n "$SMS" ] || SMS=$(command -v mu300-sms 2>/dev/null || true) +case "$SMS" in */*) ;; *) SMS=$(command -v "$SMS" 2>/dev/null || true) ;; esac +BATTERY=${MU300_FORWARD_BATTERY:-/sys/class/power_supply/battery} +NL=' +' +CR=$(printf '\r') + +reply_error() { + json_init + json_add_int ok 0 + json_add_string error "$1" + json_dump +} +reply_ok() { printf '{"ok":1}\n'; } +number() { case "$1" in ''|*[!0-9]*) return 1 ;; *) return 0 ;; esac; } +bool() { [ "$1" = 0 ] || [ "$1" = 1 ]; } +one_line() { + case "$1" in *"$NL"*|*"$CR"*) return 1 ;; esac + [ -z "$(printf '%s' "$1" | LC_ALL=C tr -d '\040-\176\200-\377')" ] +} +phone() { + _digits=${1#+} + number "$_digits" && [ ${#_digits} -ge 3 ] && [ ${#_digits} -le 32 ] +} +host_name() { + case "$1" in ''|*[!a-zA-Z0-9.-]*|.*|*.|*..*|-*|*-|*.-*|*-.*|localhost|*.localhost|*.local|*.internal) return 1 ;; esac + case "$1" in *.*) ;; *) return 1 ;; esac + # Literal IPv4 addresses and numeric pseudo-hostnames are not destinations. + case "$1" in *[a-zA-Z]*) return 0 ;; *) return 1 ;; esac +} +mailbox() { + case "$1" in *'@'*) ;; *) return 1 ;; esac + _local=${1%%@*}; _domain=${1#*@} + case "$_local" in ''|.*|*.|*..*|*[!a-zA-Z0-9._%+-]*) return 1 ;; esac + [ ${#1} -le 254 ] && host_name "$_domain" +} +public_ip() { + case "$1" in + *:*) + _ip_lc=$(printf '%s' "$1" | tr 'A-F' 'a-f') + case "$_ip_lc" in 2001:db8:*|2001:0db8:*) return 1 ;; esac + case "$_ip_lc" in [23]*) return 0 ;; *) return 1 ;; esac ;; + *) + _oldifs=$IFS; IFS=.; set -- $1; IFS=$_oldifs + [ "$#" -eq 4 ] || return 1 + for _octet in "$@"; do + number "$_octet" && [ "$_octet" -le 255 ] || return 1 + done + case "$1" in 0|10|127|224|225|226|227|228|229|230|231|232|233|234|235|236|237|238|239|24[0-9]|25[0-5]) return 1 ;; esac + [ "$1" = 169 ] && [ "$2" = 254 ] && return 1 + [ "$1" = 192 ] && { [ "$2" = 168 ] || [ "$2" = 0 ]; } && return 1 + [ "$1" = 172 ] && [ "$2" -ge 16 ] && [ "$2" -le 31 ] && return 1 + [ "$1" = 100 ] && [ "$2" -ge 64 ] && [ "$2" -le 127 ] && return 1 + [ "$1" = 198 ] && { [ "$2" = 18 ] || [ "$2" = 19 ]; } && return 1 + [ "$1" = 198 ] && [ "$2" = 51 ] && [ "$3" = 100 ] && return 1 + [ "$1" = 192 ] && [ "$2" = 0 ] && [ "$3" = 2 ] && return 1 + [ "$1" = 203 ] && [ "$2" = 0 ] && [ "$3" = 113 ] && return 1 + return 0 ;; + esac +} +resolve_public() { # hostname, port -> pinned curl --resolve argument + _resolved=$(nslookup "$1" 2>/dev/null | awk '/^Name:/ {answer=1} answer && /^Address:/ {print $2}') + [ -n "$_resolved" ] || return 1 + _picked= + while IFS= read -r _ip || [ -n "$_ip" ]; do + public_ip "$_ip" || return 1 + case "$_ip" in *:*) [ -n "$_picked" ] || { _picked="[$_ip]"; PICKED_IP=$_ip; } ;; + *) _picked=$_ip; PICKED_IP=$_ip ;; + esac + done </dev/null || return 1 + json_get_vars enabled method webhook_url dingtalk_webhook dingtalk_secret sms_to_phone + json_get_vars smtp_host smtp_port smtp_username smtp_to smtp_password + json_get_vars power_forward_enabled blacklist_phone blacklist_keywords nickname + json_get_vars smtp_forward_device_info dingtalk_forward_device_info sms_forward_device_info + json_get_var template_language template_language '' +} +load_state() { + last_id=0 since=0 power_percent=-1 power_status=none + [ -s "$STATE" ] || return 0 + # Ignore the trailing quota fields from older releases. + IFS='|' read -r last_id since power_percent power_status _legacy < "$STATE" || : + number "$last_id" || last_id=0 + number "$since" || since=0 +} +ensure_base() { mkdir -p "$BASE" && chmod 700 "$BASE"; } +save_state() { + ensure_base || return 1 + printf '%s|%s|%s|%s\n' "$last_id" "$since" "$power_percent" "$power_status" > "$STATE.tmp.$$" || return 1 + mv -f "$STATE.tmp.$$" "$STATE" +} +save_config() { + ensure_base || return 1 + json_init + json_add_boolean enabled "$enabled" + json_add_string method "$method" + json_add_string template_language "$template_language" + json_add_string webhook_url "$webhook_url" + json_add_string dingtalk_webhook "$dingtalk_webhook" + json_add_string dingtalk_secret "$dingtalk_secret" + json_add_string sms_to_phone "$sms_to_phone" + json_add_string smtp_host "$smtp_host" + json_add_int smtp_port "$smtp_port" + json_add_string smtp_username "$smtp_username" + json_add_string smtp_to "$smtp_to" + json_add_string smtp_password "$smtp_password" + json_add_boolean power_forward_enabled "$power_forward_enabled" + json_add_string blacklist_phone "$blacklist_phone" + json_add_string blacklist_keywords "$blacklist_keywords" + json_add_string nickname "$nickname" + json_add_boolean smtp_forward_device_info "$smtp_forward_device_info" + json_add_boolean dingtalk_forward_device_info "$dingtalk_forward_device_info" + json_add_boolean sms_forward_device_info "$sms_forward_device_info" + json_dump > "$CONFIG.tmp.$$" || return 1 + mv -f "$CONFIG.tmp.$$" "$CONFIG" +} +write_result() { printf '%s|%s\n' "$1" "$2" > "$RESULT.tmp.$$" && mv -f "$RESULT.tmp.$$" "$RESULT"; } +read_result() { + last_result=idle power_last_result=idle + [ -r "$RESULT" ] && IFS='|' read -r last_result power_last_result < "$RESULT" || : +} +power_read() { + power_ok=0 current_percent=-1 current_status=none + [ -r "$BATTERY/present" ] && [ "$(cat "$BATTERY/present" 2>/dev/null)" = 1 ] || return 0 + current_percent=$(cat "$BATTERY/capacity" 2>/dev/null) + current_status=$(cat "$BATTERY/status" 2>/dev/null) + number "$current_percent" && [ "$current_percent" -le 100 ] || return 0 + case "$current_status" in Charging|Discharging|Not\ charging|Full) power_ok=1 ;; esac +} +add_status() { + power_read; read_result + json_add_object status + json_add_boolean supported 1 + json_add_boolean enabled "$enabled" + json_add_string method "$method" + json_add_boolean power_supported "$power_ok" + json_add_boolean power_forward_enabled "$power_forward_enabled" + json_add_string last_result "$last_result" + json_add_string power_last_result "$power_last_result" + json_close_object +} +get_view() { + load_config || { reply_error invalid_config; return; } + load_state + json_init + json_add_object config + json_add_boolean enabled "$enabled" + json_add_string method "$method" + json_add_string template_language "$template_language" + json_add_string webhook_url "$webhook_url" + json_add_string dingtalk_webhook "$dingtalk_webhook" + json_add_boolean dingtalk_secret_configured "$([ -n "$dingtalk_secret" ] && echo 1 || echo 0)" + json_add_string sms_to_phone "$sms_to_phone" + json_add_object smtp + json_add_string host "$smtp_host" + json_add_int port "$smtp_port" + json_add_string username "$smtp_username" + json_add_string to "$smtp_to" + json_add_boolean password_configured "$([ -n "$smtp_password" ] && echo 1 || echo 0)" + json_close_object + json_add_boolean power_forward_enabled "$power_forward_enabled" + json_add_string blacklist_phone "$blacklist_phone" + json_add_string blacklist_keywords "$blacklist_keywords" + json_add_string nickname "$nickname" + json_add_boolean smtp_forward_device_info "$smtp_forward_device_info" + json_add_boolean dingtalk_forward_device_info "$dingtalk_forward_device_info" + json_add_boolean sms_forward_device_info "$sms_forward_device_info" + json_close_object + add_status + json_dump +} +status_only() { + load_config || { reply_error invalid_config; return; } + load_state + json_init + add_status + json_dump +} +set_config() { + ensure_base || { reply_error forward_storage_failed; return; } + exec 8> "$BASE/state.lock" + flock -x 8 || { reply_error forward_storage_failed; return; } + _payload=$(cat) + [ ${#_payload} -le 12288 ] && json_load "$_payload" 2>/dev/null || + { reply_error invalid_config; return; } + json_get_var new_enabled enabled + json_get_var new_method method + json_get_var new_template_language template_language + json_get_var new_webhook_url webhook_url + json_get_var new_dingtalk_webhook dingtalk_webhook + json_get_var new_dingtalk_secret dingtalk_secret + json_get_var new_sms_to_phone sms_to_phone + json_get_var new_smtp_host smtp_host + json_get_var new_smtp_port smtp_port + json_get_var new_smtp_username smtp_username + json_get_var new_smtp_to smtp_to + json_get_var new_smtp_password smtp_password + json_get_var new_power_forward_enabled power_forward_enabled + json_get_var new_blacklist_phone blacklist_phone + json_get_var new_blacklist_keywords blacklist_keywords + json_get_var new_nickname nickname + json_get_var new_smtp_forward_device_info smtp_forward_device_info + json_get_var new_dingtalk_forward_device_info dingtalk_forward_device_info + json_get_var new_sms_forward_device_info sms_forward_device_info + json_get_vars clear_smtp_password clear_dingtalk_secret + load_config || { reply_error invalid_config; return; } + old_enabled=$enabled old_method=$method + enabled=${new_enabled:-0}; method=${new_method:-webhook} + # Older clients omit this field; retain the saved language in that case. + template_language=${new_template_language:-${template_language:-zh}} + webhook_url=${new_webhook_url:-}; dingtalk_webhook=${new_dingtalk_webhook:-} + sms_to_phone=${new_sms_to_phone:-}; smtp_host=${new_smtp_host:-} + smtp_port=${new_smtp_port:-465}; smtp_username=${new_smtp_username:-}; smtp_to=${new_smtp_to:-} + power_forward_enabled=${new_power_forward_enabled:-0} + blacklist_phone=${new_blacklist_phone:-}; blacklist_keywords=${new_blacklist_keywords:-} + nickname=${new_nickname:-} + smtp_forward_device_info=${new_smtp_forward_device_info:-0} + dingtalk_forward_device_info=${new_dingtalk_forward_device_info:-0} + sms_forward_device_info=${new_sms_forward_device_info:-0} + if [ "${clear_smtp_password:-0}" = 1 ]; then + smtp_host= smtp_username= smtp_to= smtp_password= + smtp_port=465 + fi + [ -n "${new_smtp_password:-}" ] && smtp_password=$new_smtp_password + [ "${clear_dingtalk_secret:-0}" = 1 ] && dingtalk_secret= + [ -n "${new_dingtalk_secret:-}" ] && dingtalk_secret=$new_dingtalk_secret + for _bit in "$enabled" "$power_forward_enabled" "$smtp_forward_device_info" \ + "$dingtalk_forward_device_info" "$sms_forward_device_info"; do + bool "$_bit" || { reply_error invalid_config; return; } + done + case "$method" in webhook|dingtalk|smtp|sms) ;; *) reply_error invalid_config; return ;; esac + case "$template_language" in zh|en|tr) ;; *) reply_error invalid_config; return ;; esac + [ -z "$webhook_url" ] || https_url "$webhook_url" || { reply_error invalid_destination; return; } + [ -z "$dingtalk_webhook" ] || { + https_url "$dingtalk_webhook" && + case "$dingtalk_webhook" in https://oapi.dingtalk.com/robot/send*) true ;; *) false ;; esac + } || { reply_error invalid_destination; return; } + list_valid "$sms_to_phone" 3 phone && + list_valid "$blacklist_phone" 64 phone && + list_valid "$blacklist_keywords" 32 keyword || + { reply_error invalid_forward_config; return; } + [ ${#nickname} -le 255 ] && one_line "$nickname" && + [ ${#dingtalk_secret} -le 256 ] && one_line "$dingtalk_secret" && + [ ${#smtp_password} -le 512 ] && one_line "$smtp_password" || + { reply_error invalid_forward_config; return; } + case "$smtp_port" in 465|587) ;; *) reply_error invalid_forward_config; return ;; esac + if [ -n "$smtp_host$smtp_username$smtp_to$smtp_password" ]; then + host_name "$smtp_host" && mailbox "$smtp_username" && mailbox "$smtp_to" && + [ -n "$smtp_password" ] || + { reply_error invalid_forward_config; return; } + fi + if [ "$enabled" = 1 ]; then + case "$method" in + webhook) [ -n "$webhook_url" ] ;; + dingtalk) [ -n "$dingtalk_webhook" ] ;; + smtp) [ -n "$smtp_host$smtp_username$smtp_to$smtp_password" ] ;; + sms) [ -n "$sms_to_phone" ] ;; + esac || { reply_error invalid_forward_config; return; } + [ -r "$POOL/next_id" ] || { reply_error sms_list_unavailable; return; } + fi + power_read + [ "$power_forward_enabled" = 0 ] || [ "$power_ok" = 1 ] || + { reply_error power_unavailable; return; } + load_state + if [ "$enabled" = 1 ] && { [ "$old_enabled" != 1 ] || [ "$old_method" != "$method" ]; }; then + _max=$(cat "$POOL/next_id" 2>/dev/null) + number "$_max" || { reply_error sms_list_unavailable; return; } + last_id=$_max + since=$(date +%s) + fi + if [ "$power_forward_enabled" = 1 ] && [ "$power_ok" = 1 ]; then + power_percent=$current_percent; power_status=$current_status + fi + # Save the replay barrier before making the new enabled configuration visible. + save_state && save_config || { reply_error forward_storage_failed; return; } + write_result idle idle || : + reply_ok +} +message_file() { printf '%s/msg/%06d' "$POOL" "$1"; } +msg_field() { sed -n "1,/^$/s/^$2: //p" "$1" | head -n1; } +msg_body() { sed -n '1,/^$/!p' "$1"; } +blocked() { + _peer=${1#+} + while IFS= read -r _item || [ -n "$_item" ]; do + [ -n "$_item" ] || continue + [ "${_item#+}" = "$_peer" ] && return 0 + done </dev/null) + _uptime=$(cut -d. -f1 /proc/uptime 2>/dev/null) + printf '%s: %s%s\n%s: %s\n%s: %s %s' "$T_DEVICE" "$_model" "${nickname:+ ($nickname)}" \ + "$T_FIRMWARE" "$(sed -n "s/^DISTRIB_DESCRIPTION='\(.*\)'$/\1/p" /etc/openwrt_release 2>/dev/null)" \ + "$T_UPTIME" "$_uptime" "$T_SECONDS" +} +device_info_sms() { + _model=$(cat /tmp/sysinfo/model 2>/dev/null) + printf '%s%s' "$_model" "${nickname:+ ($nickname)}" +} +sms_units() { + printf '%s' "$1" | LC_ALL=C awk ' + BEGIN { for (i=1; i<256; i++) ord[sprintf("%c",i)]=i; count=0 } + NR>1 { count++ } + { + for (i=1; i<=length($0); ) { + b=ord[substr($0,i,1)] + if (b<128) { i++; count++ } + else if (b<224) { i+=2; count++ } + else if (b<240) { i+=3; count++ } + else if (b<245) { i+=4; count+=2 } + else { i++; count++ } + } + } + END { print count }' +} +deliver() { # kind, sender, body, date. Returns a finite result code in DELIVER_RESULT. + _kind=$1 _from=$2 _text=$3 _date=${4:-}; DELIVER_RESULT=delivery_failed + [ "$enabled" = 1 ] || { DELIVER_RESULT=disabled; return 1; } + format_message "$_kind" "$_from" "$_text" + # Webhooks keep raw SMS bodies and stable JSON keys; only generated test + # and power text is localized, just like the human-readable channels. + [ "$_kind" != test ] || _text=$_content + _include=0 + case "$method" in + smtp) _include=$smtp_forward_device_info ;; + dingtalk) _include=$dingtalk_forward_device_info ;; + sms) _include=$sms_forward_device_info ;; + esac + if [ "$_include" = 1 ]; then + if [ "$method" = sms ]; then _content="$_content$NL$(device_info_sms)" + else _content="$_content + +$(device_info)"; fi + fi + if [ "$method" = sms ]; then + [ -n "$SMS" ] && [ -x "$SMS" ] || { DELIVER_RESULT=source_unavailable; return 1; } + # The local SMS adapter only supports one 70-unit UCS-2 part. Do not + # submit a message longer than that adapter supports. + [ "$(sms_units "$_content")" -le 70 ] || + { DELIVER_RESULT=message_too_long; return 1; } + _delivered=0 + while IFS= read -r _to || [ -n "$_to" ]; do + [ -n "$_to" ] || continue + [ "${_to#+}" = "${_from#+}" ] && continue + "$SMS" send "$_to" "$_content" >/dev/null 2>&1 || + { DELIVER_RESULT=delivery_failed; return 1; } + _delivered=1 + done </dev/null 2>&1 || { DELIVER_RESULT=delivery_failed; return 1; } + resolve_public "$smtp_host" "$smtp_port" || + { DELIVER_RESULT=invalid_destination; return 1; } + # msmtp pins the public DNS answer as the connection host, while + # tls_host_override verifies the original DNS name against the cert. + # Password lives only in a mode-0600 tmpfs file, never argv or logs. + printf '%s\n' "$smtp_password" > "$_tmp.pass" + { + printf 'defaults\nauth on\ntls on\ntls_certcheck on\n' + printf 'tls_trust_file /etc/ssl/certs/ca-certificates.crt\n' + printf 'timeout 20\naccount mu300_forward\n' + printf 'host %s\nport %s\ntls_host_override %s\n' "$PICKED_IP" "$smtp_port" "$smtp_host" + [ "$smtp_port" = 465 ] && printf 'tls_starttls off\n' || printf 'tls_starttls on\n' + printf 'from %s\nuser %s\npasswordeval cat %s\n' "$smtp_username" "$smtp_username" "$_tmp.pass" + } > "$_tmp.config" + { + printf 'From: <%s>\r\nTo: <%s>\r\nSubject: %s\r\n' "$smtp_username" "$smtp_to" "$(mime_subject "$_subject")" + printf 'MIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n' + printf '%s' "$_content" | openssl base64 + } > "$_tmp.body" + _err=$(msmtp -C "$_tmp.config" -a mu300_forward "$smtp_to" < "$_tmp.body" 2>&1) + _rc=$? + rm -f "$_tmp.config" "$_tmp.pass" "$_tmp.body" + case "$_err" in *'authentication failed'*|*'535 '*) + DELIVER_RESULT=smtp_auth_failed ;; + esac + else + command -v curl >/dev/null 2>&1 || { DELIVER_RESULT=delivery_failed; return 1; } + if [ "$method" = dingtalk ]; then _host=oapi.dingtalk.com; _port=443 + else + _authority=${webhook_url#https://}; _authority=${_authority%%/*}; _authority=${_authority%%\?*} + _host=${_authority%%:*}; _port=443 + [ "$_authority" = "$_host" ] || _port=${_authority#*:} + fi + resolve_public "$_host" "$_port" || + { DELIVER_RESULT=invalid_destination; return 1; } + json_init + if [ "$method" = dingtalk ]; then + json_add_string msgtype text + json_add_object text; json_add_string content "$_content"; json_close_object + _url=$dingtalk_webhook + if [ -n "$dingtalk_secret" ]; then + _stamp="$(date +%s)000" + _sig=$(printf '%s\n%s' "$_stamp" "$dingtalk_secret" | + openssl dgst -sha256 -hmac "$dingtalk_secret" -binary 2>/dev/null | + openssl base64 -A 2>/dev/null | + sed -e 's/+/%2B/g' -e 's|/|%2F|g' -e 's/=/%3D/g') + [ -n "$_sig" ] || { DELIVER_RESULT=delivery_failed; return 1; } + case "$_url" in *\?*) _url="$_url×tamp=$_stamp&sign=$_sig" ;; + *) _url="$_url?timestamp=$_stamp&sign=$_sig" ;; esac + fi + else + [ "$_kind" = power ] && json_add_string kind power + json_add_string from "$_from" + json_add_string text "$_text" + json_add_string date "$_date" + [ "$_include" = 1 ] && json_add_string device_info "$(device_info)" + _url=$webhook_url + fi + json_dump > "$_tmp.body" + curl -q --noproxy '*' --proto '=https' --resolve "$RESOLVE" --max-redirs 0 --connect-timeout 4 \ + --max-time 12 --max-filesize 4096 --fail -sS -H 'Content-Type: application/json; charset=utf-8' \ + --data-binary "@$_tmp.body" -o "$_tmp.reply" "$_url" >/dev/null 2>&1 + _rc=$? + if [ "$_rc" -eq 0 ] && [ "$method" = dingtalk ]; then + [ "$(jsonfilter -i "$_tmp.reply" -e '@.errcode' 2>/dev/null)" = 0 ] || _rc=1 + fi + rm -f "$_tmp.body" "$_tmp.reply" + fi + [ "$_rc" -eq 0 ] && { DELIVER_RESULT=sent; return 0; } + return 1 +} +scts_epoch() { + # Text-mode AT timestamps use signed quarter-hours; the PDU adapter emits + # ISO timestamps with an explicit UTC offset. Pure POSIX awk avoids GNU + # date/mktime dependencies and the router's unrelated local timezone. + printf '%s\n' "$1" | LC_ALL=C awk ' + function leap(y) { return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) } + { + if ($0 ~ /^[0-9][0-9]\/[0-9][0-9]\/[0-9][0-9],[0-9][0-9]:[0-9][0-9]:[0-9][0-9][+-][0-9][0-9]$/) { + y=2000+substr($0,1,2); mo=substr($0,4,2)+0; d=substr($0,7,2)+0 + h=substr($0,10,2)+0; mi=substr($0,13,2)+0; s=substr($0,16,2)+0 + sign=substr($0,18,1); offset=substr($0,19,2)*15 + } else if ($0 ~ /^20[0-9][0-9]-[0-9][0-9]-[0-9][0-9][ T][0-9][0-9]:[0-9][0-9]:[0-9][0-9][+-][0-9][0-9]:[0-9][0-9]$/) { + y=substr($0,1,4)+0; mo=substr($0,6,2)+0; d=substr($0,9,2)+0 + h=substr($0,12,2)+0; mi=substr($0,15,2)+0; s=substr($0,18,2)+0 + sign=substr($0,20,1); om=substr($0,24,2)+0 + if (om > 59) exit 1 + offset=substr($0,21,2)*60+om + } else exit 1 + split("31 28 31 30 31 30 31 31 30 31 30 31", days, " ") + days[2]+=leap(y) + if (mo<1 || mo>12 || d<1 || d>days[mo] || h>23 || mi>59 || s>59 || offset>840) exit 1 + n=10957 # days from 1970-01-01 to 2000-01-01 + for (i=2000; i/dev/null) + number "$_max" || return 0 + _processed=0 _start_id=$last_id + while [ "$last_id" -lt "$_max" ] && [ "$_processed" -lt 1 ]; do + _id=$((last_id + 1)) + _file=$(message_file "$_id") + # next_id is written before the message rename. Keep the newest + # missing ID pending until the next poll; older missing IDs were + # deleted, so those may be skipped. + if [ ! -f "$_file" ]; then + if [ "$_id" -eq "$_max" ]; then + [ "$last_id" = "$_start_id" ] || save_state + return 0 + fi + last_id=$_id + continue + fi + _dir=$(msg_field "$_file" dir) + _from=$(msg_field "$_file" from) + _received=$(msg_field "$_file" received) + _scts=$(msg_field "$_file" scts) + _source=$(msg_field "$_file" source) + _coding=$(msg_field "$_file" coding) + _body=$(msg_body "$_file") + last_id=$_id + save_state || { write_result storage_failed "$power_last_result"; return 1; } + _processed=$((_processed + 1)) + [ "$_dir" = mt ] || continue + # A raw SIM PDU has no trustworthy original timestamp; the importer + # uses local time only as a display fallback. Keep it local, not mail. + [ "$_source" = direct ] || [ "$_coding" != raw-pdu ] || continue + sms_is_new "$_source" "$_scts" "$_received" || continue + blocked "$_from" "$_body" && continue + deliver sms "$_from" "$_body" "$_scts" || : + write_result "$DELIVER_RESULT" "$power_last_result" || : + done + [ "$_processed" -gt 0 ] || [ "$last_id" = "$_start_id" ] || save_state +} +process_power() { + power_read + [ "$power_ok" = 1 ] || return 0 + [ "$power_percent" = "$current_percent" ] && [ "$power_status" = "$current_status" ] && return 0 + _old_percent=$power_percent; _old_status=$power_status + power_percent=$current_percent; power_status=$current_status + save_state || return 1 + [ "$enabled" = 1 ] && [ "$power_forward_enabled" = 1 ] || return 0 + # Match the ZWRT power policy: a status transition, or one notification + # when crossing any threshold (including a jump over several points). + _point= + if number "$_old_percent" && [ "$_old_percent" -le 100 ]; then + for _threshold in 5 20 40 60 80 100; do + if [ "$current_percent" -gt "$_old_percent" ] && + [ "$_old_percent" -lt "$_threshold" ] && + [ "$current_percent" -ge "$_threshold" ]; then + _point=$_threshold + elif [ "$current_percent" -lt "$_old_percent" ] && + [ "$_old_percent" -gt "$_threshold" ] && + [ "$current_percent" -le "$_threshold" ] && [ -z "$_point" ]; then + _point=$_threshold + fi + done + fi + [ "$_old_status" != "$current_status" ] || [ -n "$_point" ] || return 0 + _detail=$(power_message "$current_status" "$current_percent" "$_point" "$_old_status") + deliver power PowerMonitor "$_detail" || : + write_result "$last_result" "$DELIVER_RESULT" || : +} +test_send() { + ensure_base || exit 1 + exec 8> "$BASE/state.lock" + flock -x 8 || exit 1 + load_config || exit 1 + load_state; read_result + deliver test NMS '' || : + write_result "$DELIVER_RESULT" "$power_last_result" || : +} +run_daemon() { + ensure_base || exit 1 + # procd owns the process. A second manual start exits without stealing work. + exec 9> "$BASE/daemon.lock" + flock -n 9 || exit 0 + while :; do + exec 8> "$BASE/state.lock" + flock -x 8 || exit 1 + if load_config; then + if [ "$enabled" = 1 ] && [ ! -s "$STATE" ]; then + # A manually restored config without replay state is not a + # license to forward the whole historical local pool. + last_id=$(cat "$POOL/next_id" 2>/dev/null) + if ! number "$last_id"; then + flock -u 8 + sleep "${MU300_FORWARD_POLL:-5}" + continue + fi + since=$(date +%s) + power_read + power_percent=$current_percent; power_status=$current_status + save_state || exit 1 + fi + load_state; read_result + process_sms || : + process_power || : + fi + flock -u 8 + sleep "${MU300_FORWARD_POLL:-5}" + done +} +case "${1:-}" in + get) get_view ;; + status) status_only ;; + set) set_config ;; + test-run) test_send ;; + run) run_daemon ;; + *) echo 'usage: sms-forward {get|status|set|test-run|run}' >&2; exit 2 ;; +esac diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/traffic b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/traffic new file mode 100644 index 00000000..b2a8e302 --- /dev/null +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/traffic @@ -0,0 +1,123 @@ +#!/usr/bin/ucode +import * as fs from 'fs'; +import * as uloop from 'uloop'; +import * as ubus from 'ubus'; +import * as uci from 'uci'; +import * as core from './traffic-core.uc'; + +const BASE = getenv('MU300_TRAFFIC_DIR') || '/etc/unisoc-modem/traffic'; +const RUN = getenv('MU300_TRAFFIC_RUN') || '/run/unisoc-modem-traffic'; +const NET = getenv('MU300_TRAFFIC_SYS') || '/sys/class/net'; +const BUS = getenv('MU300_TRAFFIC_BUS') || 'unisoc.traffic'; +const boot = trim(fs.readfile('/proc/sys/kernel/random/boot_id') || ''); +fs.mkdir('/etc/unisoc-modem', 448); +fs.mkdir(BASE, 448); fs.mkdir(RUN, 448); +function read_json(path) { + let text = fs.readfile(path); + if (text == null) return null; + try { return json(text); } catch (e) { die('Invalid traffic database: ' + path + '\n'); } +} +function atomic(path, value) { + let text = sprintf('%J\n', value), tmp = path + '.new'; + if (fs.writefile(tmp, text) != length(text)) return false; + fs.chmod(tmp, 384); + return fs.rename(tmp, path); +} +let db = read_json(RUN + '/state.json') ?? read_json(BASE + '/state.json') ?? core.fresh(time()); +if (db.version != 1 || type(db.days) != 'object' || type(db.months) != 'object') + die('Unsupported traffic database\n'); +db.config = core.config(db.config); +let saved_at = 0, storage_error = false, resolved = '', resolve_at = 0; +uloop.init(); +const bus = ubus.connect(null, 2); +if (!bus) die('Traffic ubus connection failed\n'); + +function resolve_device(now) { + if (db.config.device) return db.config.device; + if (now >= resolve_at && now < resolve_at + 30 && resolved) return resolved; + resolve_at = now; + let cfg = uci.cursor(); + let explicit = cfg.get('unisoc_modem', 'main', 'data_device'); + let iface = cfg.get('unisoc_modem', 'main', 'data_interface') || 'wan'; + let net = explicit ? null : bus.call('network.interface.' + iface, 'status', {}); + let name = explicit || net?.l3_device || net?.device; + if (name && match(name, /^[a-zA-Z0-9_.:-]{1,15}$/)) resolved = name; + return resolved; +} +function snapshot(now) { + let name = resolve_device(now); + if (!name) return null; + let rx = trim(fs.readfile(NET + '/' + name + '/statistics/rx_bytes') || ''); + let tx = trim(fs.readfile(NET + '/' + name + '/statistics/tx_bytes') || ''); + let idx = trim(fs.readfile(NET + '/' + name + '/ifindex') || ''); + if (!match(rx, /^[0-9]+$/) || !match(tx, /^[0-9]+$/) || !match(idx, /^[0-9]+$/)) return null; + return { device: name, boot: boot, ifindex: int(idx), rx: int(rx), tx: int(tx) }; +} +function view(now) { + let s = core.status(db, now); + s.storage_error = storage_error; + return s; +} +function checkpoint(force) { + let now = time(); + if (!atomic(RUN + '/state.json', db)) storage_error = true; + if (force || now - saved_at >= 60 || now < saved_at) { + if (atomic(BASE + '/state.json', db)) { saved_at = now; storage_error = false; } + else storage_error = true; + } + atomic(RUN + '/view.json', view(now)); +} +function sample(force) { + let now = time(); + core.advance(db, snapshot(now), now); + checkpoint(force); +} +function get_data() { + let days = [], months = []; + for (let date in reverse(sort(keys(db.days)))) { + if (length(days) >= 31) break; + push(days, { date: date, rx: db.days[date].rx, tx: db.days[date].tx }); + } + for (let date in reverse(sort(keys(db.months)))) { + if (length(months) >= 12) break; + push(months, { date: date, rx: db.months[date].rx, tx: db.months[date].tx }); + } + return { config: db.config, status: view(time()), days: days, months: months }; +} +const obj = bus.publish(BUS, { + get: { call: function(req) { return get_data(); } }, + set: { args: { payload: '' }, call: function(req) { + let input; + try { + if (length(req.args.payload || '') > 4096) die('invalid_config'); + input = json(req.args.payload); + core.config(input); + if (input.used_gb != null && time() < 1704067200) return { ok: 0, error: 'clock_unsynced' }; + } catch (e) { return { ok: 0, error: 'invalid_config' }; } + sample(false); + let previous = db.config, adjustment = db.adjustment, last = db.last; + try { core.update_config(db, input, time()); } + catch (e) { return { ok: 0, error: 'invalid_config' }; } + // Persist the full transaction before acknowledging changed settings. + if (!atomic(BASE + '/state.json', db)) { + db.config = previous; db.adjustment = adjustment; db.last = last; + storage_error = true; + return { ok: 0, error: 'storage_failed' }; + } + resolved = ''; resolve_at = 0; + sample(true); + return { ok: 1 }; + } }, + flush: { call: function(req) { sample(true); return { ok: !storage_error }; } } +}); +if (!obj) die('Traffic service already running or publish failed\n'); +sample(true); +let ticker; +ticker = uloop.timer(10000, function() { + sample(false); + ticker.set(10000); +}); +let term = uloop.signal(15, function() { sample(true); uloop.end(); }); +let intr = uloop.signal(2, function() { sample(true); uloop.end(); }); +uloop.run(); +sample(true); diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/traffic-core.uc b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/traffic-core.uc new file mode 100644 index 00000000..c8b00c77 --- /dev/null +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/traffic-core.uc @@ -0,0 +1,135 @@ +// Pure accounting rules shared by the daemon and deterministic boundary tests. +export const defaults = { plan_name: '', monthly_gb: 0, daily_gb: 0, + reset_day: 1, count_mode: 'total', device: '' }; + +export function config(input) { + if (type(input) != 'object') die('invalid_config'); + let c = {}; + for (let k, v in defaults) c[k] = input[k] ?? v; + if (type(c.plan_name) != 'string' || length(c.plan_name) > 128 || + match(c.plan_name, /[[:cntrl:]]/)) die('invalid_config'); + if (type(c.device) != 'string' || (c.device != '' && + !match(c.device, /^[a-zA-Z0-9_.:-]{1,15}$/))) die('invalid_config'); + for (let k in ['monthly_gb', 'daily_gb']) { + if ((type(c[k]) != 'int' && type(c[k]) != 'double') || + !(c[k] >= 0 && c[k] <= 100000)) die('invalid_config'); + } + if (type(c.reset_day) != 'int' || c.reset_day < 1 || c.reset_day > 31 || + index(['total', 'rx', 'tx'], c.count_mode) < 0) die('invalid_config'); + return c; +}; + +export function day_key(now) { + let t = localtime(now); + return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday); +}; +function date_epoch(y, m, d) { + while (m < 1) { m += 12; y--; } + while (m > 12) { m -= 12; y++; } + return timelocal({ year: y, mon: m, mday: d, hour: 0, min: 0, sec: 0, isdst: -1 }); +} +function reset_epoch(y, m, d) { + let first = localtime(date_epoch(y, m, 1)); + let last = localtime(date_epoch(first.year, first.mon + 1, 1) - 1).mday; + return date_epoch(first.year, first.mon, d < last ? d : last); +} +export function cycle(now, reset_day) { + let t = localtime(now), start = reset_epoch(t.year, t.mon, reset_day), offset = 0; + if (now < start) { offset = -1; start = reset_epoch(t.year, t.mon - 1, reset_day); } + let end = reset_epoch(t.year, t.mon + offset + 1, reset_day); + return { start: day_key(start), end: day_key(end), start_ts: start, end_ts: end }; +}; +export function fresh(now) { + return { version: 1, config: config({}), started_at: now, last: null, + days: {}, months: {}, pending_rx: 0, pending_tx: 0, adjustment: null }; +}; +function add(db, at, rx, tx) { + let day = day_key(at), month = substr(day, 0, 7); + for (let pair in [[db.days, day], [db.months, month]]) { + let bucket = pair[0][pair[1]] ?? { rx: 0, tx: 0 }; + bucket.rx += rx; bucket.tx += tx; + pair[0][pair[1]] = bucket; + } +} +function prune(obj, keep) { + let list = sort(keys(obj)); + for (let i = 0; i < length(list) - keep; i++) delete(obj, list[i]); +} +export function advance(db, sample, now) { + db.updated_at = now; + db.clock_ok = now >= 1704067200; + db.available = sample != null; + if (!sample) return; + let prev = db.last, rx = 0, tx = 0; + if (prev) { + if (prev.boot == sample.boot && prev.ifindex == sample.ifindex && prev.device == sample.device) { + rx = sample.rx >= prev.rx ? sample.rx - prev.rx : sample.rx; + tx = sample.tx >= prev.tx ? sample.tx - prev.tx : sample.tx; + } + else { rx = sample.rx; tx = sample.tx; } + } + // First activation only establishes a baseline: earlier traffic cannot be + // honestly assigned to a day. A reboot/recreated interface adds its new counters. + db.last = { boot: sample.boot, ifindex: sample.ifindex, device: sample.device, + rx: sample.rx, tx: sample.tx, at: now }; + if (!db.clock_ok) { db.pending_rx += rx; db.pending_tx += tx; return; } + let from = prev?.at ?? now; + if (db.pending_rx || db.pending_tx) { + rx += db.pending_rx; tx += db.pending_tx; + db.pending_rx = 0; db.pending_tx = 0; from = now; + } + // Split the short sampling interval at local midnight (including DST). + // After a reboot or clock jump the exact temporal split is unknowable; + // retain every byte and assign it to the current valid date. + if (prev && prev.boot == sample.boot && from >= 1704067200 && + now > from && now - from <= 120 && day_key(from) != day_key(now)) { + let t = localtime(from), boundary = date_epoch(t.year, t.mon, t.mday + 1); + let part_rx = int(rx * (boundary - from) / (now - from)); + let part_tx = int(tx * (boundary - from) / (now - from)); + add(db, from, part_rx, part_tx); + add(db, now, rx - part_rx, tx - part_tx); + } + else add(db, now, rx, tx); + prune(db.days, 93); prune(db.months, 24); +}; +export function counted(pair, mode) { + return mode == 'rx' ? pair.rx : mode == 'tx' ? pair.tx : pair.rx + pair.tx; +}; +export function status(db, now) { + let c = db.config, range = cycle(now, c.reset_day), today = day_key(now); + let day = db.days[today] ?? { rx: 0, tx: 0 }; + let month = db.months[substr(today, 0, 7)] ?? { rx: 0, tx: 0 }; + let period = { rx: 0, tx: 0 }; + for (let date, data in db.days) if (date >= range.start && date < range.end) { + period.rx += data.rx; period.tx += data.tx; + } + let adjusted = db.adjustment; + let offset = adjusted && adjusted.start == range.start && adjusted.reset_day == c.reset_day && + adjusted.mode == c.count_mode ? adjusted.bytes : 0; + let used = counted(period, c.count_mode) + offset; + if (used < 0) used = 0; + let quota = int(c.monthly_gb * 1000000000), daily_quota = int(c.daily_gb * 1000000000); + let daily_used = counted(day, c.count_mode); + return { available: db.available ?? false, clock_ok: now >= 1704067200, + updated_at: db.updated_at ?? 0, started_at: db.started_at, + device: db.last?.device ?? '', today: day, month: month, period: period, + today_used: daily_used, month_used: counted(month, c.count_mode), + cycle_used: used, cycle_adjustment: offset, cycle_start: range.start, cycle_end: range.end, + monthly_limit: quota, daily_limit: daily_quota, + remaining: quota ? (quota > used ? quota - used : 0) : null, + daily_remaining: daily_quota ? (daily_quota > daily_used ? daily_quota - daily_used : 0) : null, + over_limit: quota > 0 && used >= quota, daily_over_limit: daily_quota > 0 && daily_used >= daily_quota }; +}; +export function update_config(db, input, now) { + let next = config(input); + if (input.used_gb != null && ((type(input.used_gb) != 'int' && type(input.used_gb) != 'double') || + !(input.used_gb >= 0 && input.used_gb <= 100000))) die('invalid_config'); + let changed_device = next.device != db.config.device; + db.config = next; + if (changed_device) db.last = null; + if (input.used_gb != null) { + let view = status(db, now); + db.adjustment = { start: view.cycle_start, reset_day: next.reset_day, mode: next.count_mode, + bytes: int(input.used_gb * 1000000000) - counted(view.period, next.count_mode) }; + } +}; 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 4fd9f783..9d9d3ea0 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 @@ -46,9 +46,16 @@ } }, + "admin/modem/forward": { + "title": "短信转发", + "order": 3, + "action": { "type": "view", "path": "mu300/forward" }, + "depends": { "acl": [ "luci-app-mu300" ] } + }, + "admin/modem/at": { "title": "AT 终端", - "order": 3, + "order": 4, "action": { "type": "view", "path": "mu300/at" @@ -60,7 +67,7 @@ "admin/modem/settings": { "title": "适配设置", - "order": 5, + "order": 7, "action": { "type": "view", "path": "mu300/settings" @@ -71,8 +78,14 @@ }, "admin/modem/device": { "title": "设备管理", - "order": 4, + "order": 6, "action": { "type": "view", "path": "mu300/device" }, "depends": { "acl": [ "luci-app-mu300" ] } + }, + "admin/modem/traffic": { + "title": "流量池", + "order": 5, + "action": { "type": "view", "path": "mu300/traffic" }, + "depends": { "acl": [ "luci-app-mu300" ] } } } diff --git a/openwrt/overlay/etc/uci-defaults/90-mu300 b/openwrt/overlay/etc/uci-defaults/90-mu300 index 4813bbf1..a3eaf3b5 100755 --- a/openwrt/overlay/etc/uci-defaults/90-mu300 +++ b/openwrt/overlay/etc/uci-defaults/90-mu300 @@ -17,7 +17,9 @@ set system.@system[0].zonename='Europe/Istanbul' set system.@system[0].timezone='<+03>-3' set system.mu300_leds=mu300_leds set system.mu300_leds.signal='1' +set system.mu300_leds.signal_brightness='255' set system.mu300_leds.wifi='1' +set system.mu300_leds.wifi_brightness='127' set network.lan.ipaddr='$lan_ip' set network.lan.netmask='255.255.255.0' set network.lan.ip6assign='64' diff --git a/openwrt/overlay/www/luci-static/resources/view/system/leds.js b/openwrt/overlay/www/luci-static/resources/view/system/leds.js index b45241b8..902835fd 100644 --- a/openwrt/overlay/www/luci-static/resources/view/system/leds.js +++ b/openwrt/overlay/www/luci-static/resources/view/system/leds.js @@ -14,6 +14,37 @@ const callLeds = rpc.declare({ expect: { '': {} } }); +/* This device page is copied into the rootfs independently of the MU300 LuCI + * plugin, so its small catalog must not depend on the plugin being installed. + * Upstream trigger plugins still use LuCI's own _() translations. */ +const labels = { + 'LED Configuration': ['LED 配置', 'LED yapılandırması'], + 'Configure physical status lamps and optional LED trigger actions.': ['配置物理状态灯与可选的 LED 触发动作。', 'Fiziksel durum ışıklarını ve isteğe bağlı LED tetikleyicilerini yapılandırın.'], + 'Physical status lamps': ['物理状态灯', 'Fiziksel durum ışıkları'], + 'Signal lamp (LTE / 5G / no service)': ['信号灯(4G / 5G / 无信号)', 'Sinyal ışığı (4G / 5G / servis yok)'], + 'Signal lamp brightness': ['信号灯亮度', 'Sinyal ışığı parlaklığı'], + 'Wi-Fi hotspot lamp': ['Wi-Fi 热点灯', 'Wi-Fi erişim noktası ışığı'], + 'Wi-Fi lamp brightness': ['Wi-Fi 灯亮度', 'Wi-Fi ışığı parlaklığı'], + '0–255; 0 is dark. LTE stays blue, 5G white, and no service red.': ['0–255;0 为熄灭。4G 仍为蓝色、5G 为白色、无信号为红色。', '0–255; 0 ışığı kapatır. 4G mavi, 5G beyaz, servis yoksa kırmızı kalır.'], + '0 is dark. Hardware maximum: ': ['0 为熄灭。硬件最大值:', '0 ışığı kapatır. Donanım üst sınırı: '], + 'Add LED action': ['添加 LED 动作', 'LED eylemi ekle'], + 'Name': ['名称', 'Ad'], + 'LED Name': ['LED 名称', 'LED adı'], + 'Trigger': ['触发器', 'Tetikleyici'], + 'Interval': ['间隔', 'Aralık'], + 'milliseconds': ['毫秒', 'milisaniye'] +}; + +function label(key) { + let lang = (L.env && L.env.lang) || document.documentElement.lang || navigator.language || 'en'; + if (lang === 'auto') lang = document.documentElement.lang || navigator.language || 'en'; + lang = String(lang).toLowerCase().replace('_', '-'); + const entry = labels[key]; + if (entry && lang.indexOf('zh') === 0) return entry[0]; + if (entry && lang.indexOf('tr') === 0) return entry[1]; + return _(key); +} + return view.extend({ load() { return Promise.all([ @@ -42,41 +73,53 @@ return view.extend({ render([leds, plugins]) { let m, s, o; + let wifiMax = leds['keyboard-backlight'] && Number(leds['keyboard-backlight'].max_brightness); + if (!Number.isInteger(wifiMax) || wifiMax < 1 || wifiMax > 255) wifiMax = 255; const triggers = []; for (let k in leds) for (let t of leds[k].triggers) triggers.push(t); m = new form.Map('system', - _('LED Configuration'), - _('Customizes the behaviour of the device LEDs if possible.')); + label('LED Configuration'), + label('Configure physical status lamps and optional LED trigger actions.')); /* One RGB signal lamp and one separate Wi-Fi lamp. A single sysfs LED * action cannot disable all RGB channels, while led-status would also * overwrite its brightness at the next state change. */ - s = m.section(form.NamedSection, 'mu300_leds', 'mu300_leds', _('Physical status lamps')); + s = m.section(form.NamedSection, 'mu300_leds', 'mu300_leds', label('Physical status lamps')); s.anonymous = true; s.addremove = false; - o = s.option(form.Flag, 'signal', _('Signal lamp (LTE / 5G / no service)')); + o = s.option(form.Flag, 'signal', label('Signal lamp (LTE / 5G / no service)')); o.default = '1'; o.rmempty = false; - o = s.option(form.Flag, 'wifi', _('Wi-Fi hotspot lamp')); + o = s.option(form.Value, 'signal_brightness', label('Signal lamp brightness'), + label('0–255; 0 is dark. LTE stays blue, 5G white, and no service red.')); + o.datatype = 'range(0,255)'; + o.default = '255'; + o.rmempty = false; + o = s.option(form.Flag, 'wifi', label('Wi-Fi hotspot lamp')); o.default = '1'; o.rmempty = false; + o = s.option(form.Value, 'wifi_brightness', label('Wi-Fi lamp brightness'), + label('0 is dark. Hardware maximum: ') + wifiMax); + o.datatype = 'range(0,' + wifiMax + ')'; + o.default = String(Math.min(127, wifiMax)); + o.rmempty = false; s = m.section(form.GridSection, 'led', ''); s.anonymous = true; s.addremove = true; s.sortable = true; - s.addbtntitle = _('Add LED action'); + s.addbtntitle = label('Add LED action'); s.nodescriptions = true; - s.option(form.Value, 'name', _('Name')); - o = s.option(form.ListValue, 'sysfs', _('LED Name')); + s.option(form.Value, 'name', label('Name')); + o = s.option(form.ListValue, 'sysfs', label('LED Name')); Object.keys(leds).sort().forEach(function(name) { o.value(name); }); - o = s.option(form.ListValue, 'trigger', _('Trigger')); + o = s.option(form.ListValue, 'trigger', label('Trigger')); for (let plugin of plugins) { if (plugin.form.kernel == false) { o.value(plugin.name, plugin.form.trigger); @@ -124,7 +167,7 @@ return view.extend({ opts[optname].remove = removeIfNoneActive.bind(opts[optname], opts[optname].remove); } }; - o = s.option(form.Value, 'interval', _('Interval'), _('milliseconds')); + o = s.option(form.Value, 'interval', label('Interval'), label('milliseconds')); o.placeholder = '50'; return m.render(); diff --git a/rootfs/overlay/opt/mu300/bin/led-status b/rootfs/overlay/opt/mu300/bin/led-status index 714f798f..6682daec 100755 --- a/rootfs/overlay/opt/mu300/bin/led-status +++ b/rootfs/overlay/opt/mu300/bin/led-status @@ -18,16 +18,18 @@ # led-status current print the last set state export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin" +LED_ROOT=${MU300_LED_SYSFS_ROOT:-/sys/class/leds} +RUN_DIR=${MU300_LED_RUN_DIR:-/run} # --- detect LED paths (F50 sc27xx vs V50 plain) -if [ -d /sys/class/leds/sc27xx:blue ]; then - LED_R=/sys/class/leds/sc27xx:red/brightness - LED_W=/sys/class/leds/sc27xx:green/brightness # physically white on the F50 - LED_B=/sys/class/leds/sc27xx:blue/brightness -elif [ -d /sys/class/leds/blue ]; then - LED_R=/sys/class/leds/red/brightness - LED_W=/sys/class/leds/white/brightness - LED_B=/sys/class/leds/blue/brightness +if [ -d "$LED_ROOT/sc27xx:blue" ]; then + LED_R=$LED_ROOT/sc27xx:red/brightness + LED_W=$LED_ROOT/sc27xx:green/brightness # physically white on the F50 + LED_B=$LED_ROOT/sc27xx:blue/brightness +elif [ -d "$LED_ROOT/blue" ]; then + LED_R=$LED_ROOT/red/brightness + LED_W=$LED_ROOT/white/brightness + LED_B=$LED_ROOT/blue/brightness else exit 0 fi @@ -38,18 +40,42 @@ fi # front-panel function. Keeping this separate also guarantees that LTE stays # pure blue (B=255, R=W=0), 5G pure white and offline pure red. WIFI_LED= -if [ "$(mu300-device 2>/dev/null)" = f50 ] && [ -w /sys/class/leds/keyboard-backlight/brightness ]; then - WIFI_LED=/sys/class/leds/keyboard-backlight/brightness +if [ "$(mu300-device 2>/dev/null)" = f50 ] && [ -w "$LED_ROOT/keyboard-backlight/brightness" ]; then + WIFI_LED=$LED_ROOT/keyboard-backlight/brightness fi -STATE_FILE=/run/led-status.state -WIFI_FILE=/run/led-status.wifi -BLINK_PID=/run/led-status.blink.pid +STATE_FILE=$RUN_DIR/led-status.state +WIFI_FILE=$RUN_DIR/led-status.wifi +BLINK_PID=$RUN_DIR/led-status.blink.pid SIGNAL_ENABLED=$(uci -q get system.mu300_leds.signal 2>/dev/null) WIFI_ENABLED=$(uci -q get system.mu300_leds.wifi 2>/dev/null) [ "$SIGNAL_ENABLED" = 0 ] || SIGNAL_ENABLED=1 [ "$WIFI_ENABLED" = 0 ] || WIFI_ENABLED=1 +level() { # validated 0-255 UCI value, otherwise the legacy brightness + value=$1 fallback=$2 + case $value in ''|*[!0-9]*) echo "$fallback"; return ;; esac + while [ "${value#0}" != "$value" ]; do value=${value#0}; done + [ -n "$value" ] || value=0 + [ "$value" -le 255 ] && echo "$value" || echo "$fallback" +} +hw_max() { + value=$(cat "$(dirname "$1")/max_brightness" 2>/dev/null) + level "$value" 255 +} +SIGNAL_BRIGHTNESS=$(level "$(uci -q get system.mu300_leds.signal_brightness 2>/dev/null)" 255) +WIFI_BRIGHTNESS=$(level "$(uci -q get system.mu300_leds.wifi_brightness 2>/dev/null)" 127) +R_MAX=$(hw_max "$LED_R") +W_MAX=$(hw_max "$LED_W") +B_MAX=$(hw_max "$LED_B") +[ -n "$WIFI_LED" ] && WIFI_MAX=$(hw_max "$WIFI_LED") || WIFI_MAX=255 + +scaled() { # channel intensity, configured brightness, hardware maximum + value=$(( ($1 * $2 + 127) / 255 )) + [ "$value" -le "$3" ] || value=$3 + echo "$value" +} + # Status reads must be side-effect free. In particular, dashboards and event # handlers may query this during boot and must not stop the chase animation. if [ "${1:-}" = current ]; then @@ -78,7 +104,11 @@ wifi-on|wifi-off) echo "$wifi_state" > "$WIFI_FILE" if [ -n "$WIFI_LED" ]; then echo none > "$(dirname "$WIFI_LED")/trigger" 2>/dev/null - [ "$wifi_state" = on ] && [ "$WIFI_ENABLED" = 1 ] && echo 127 > "$WIFI_LED" || echo 0 > "$WIFI_LED" + if [ "$wifi_state" = on ] && [ "$WIFI_ENABLED" = 1 ]; then + scaled 255 "$WIFI_BRIGHTNESS" "$WIFI_MAX" > "$WIFI_LED" + else + echo 0 > "$WIFI_LED" + fi fi exit 0 ;; esac @@ -94,9 +124,9 @@ done set_rgb() { # R W B (0-255) [ "$SIGNAL_ENABLED" = 1 ] || set -- 0 0 0 - echo "${1:-0}" > "$LED_R" 2>/dev/null - echo "${2:-0}" > "$LED_W" 2>/dev/null - echo "${3:-0}" > "$LED_B" 2>/dev/null + scaled "${1:-0}" "$SIGNAL_BRIGHTNESS" "$R_MAX" > "$LED_R" 2>/dev/null + scaled "${2:-0}" "$SIGNAL_BRIGHTNESS" "$W_MAX" > "$LED_W" 2>/dev/null + scaled "${3:-0}" "$SIGNAL_BRIGHTNESS" "$B_MAX" > "$LED_B" 2>/dev/null } pause_us() { @@ -113,13 +143,9 @@ start_blink() { # R W B ON_MS OFF_MS _r=$1; _w=$2; _b=$3; _on=$4; _off=$5 ( while :; do - echo "$_r" > "$LED_R" 2>/dev/null - echo "$_w" > "$LED_W" 2>/dev/null - echo "$_b" > "$LED_B" 2>/dev/null + set_rgb "$_r" "$_w" "$_b" pause_us "$_on" - echo 0 > "$LED_R" 2>/dev/null - echo 0 > "$LED_W" 2>/dev/null - echo 0 > "$LED_B" 2>/dev/null + set_rgb 0 0 0 pause_us "$_off" done ) & @@ -130,9 +156,9 @@ start_chase() { [ "$SIGNAL_ENABLED" = 1 ] || { set_rgb 0 0 0; return 0; } ( while :; do - echo 255 > "$LED_R" 2>/dev/null; echo 0 > "$LED_W" 2>/dev/null; echo 0 > "$LED_B" 2>/dev/null; pause_us 120000 - echo 0 > "$LED_R" 2>/dev/null; echo 255 > "$LED_W" 2>/dev/null; echo 0 > "$LED_B" 2>/dev/null; pause_us 120000 - echo 0 > "$LED_R" 2>/dev/null; echo 0 > "$LED_W" 2>/dev/null; echo 255 > "$LED_B" 2>/dev/null; pause_us 120000 + set_rgb 255 0 0; pause_us 120000 + set_rgb 0 255 0; pause_us 120000 + set_rgb 0 0 255; pause_us 120000 done ) & echo $! > "$BLINK_PID" diff --git a/rootfs/overlay/opt/mu300/bin/mu300-atd b/rootfs/overlay/opt/mu300/bin/mu300-atd index 5ab44943..2aa0561a 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-atd +++ b/rootfs/overlay/opt/mu300/bin/mu300-atd @@ -20,6 +20,7 @@ # sbuf_read until the modem says something - possibly for ever. # bash and busybox ash both implement -t with poll(), which this driver does support, so run under one of them. set -u +umask 077 # URC logs may contain SMS content; only root may read them # OpenWrt keeps the applets this needs (timeout, dd) in the static busybox next to us export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin" if [ -n "$(read -t 1 _probe &1)" ]; then @@ -97,7 +98,29 @@ open_tty || { echo "mu300-atd: cannot open $DEV" >&2; exit 1; } # purpose: reopening a SIPC channel is the one operation that can lose it. URCDIR=$DIR/urc URCMAX=${MU300_AT_URC_MAX:-65536} +CMT_SPOOL=${MU300_CMT_SPOOL_BIN:-/opt/mu300/bin/mu300-cmt-spool} mkdir -p "$URCDIR" +CMT_PENDING_FILE=$URCDIR/$(basename "$DEV").cmt-pending +# +CMT is a two-line unsolicited frame. A capped RAM log is not a safe inbox: +# persist the PDU before mu300-smsd acknowledges it to the network. This runs +# for both nr0 and nr1 (a +CMT can arrive on either channel), including while +# the command channel is collecting an unrelated AT reply. +capture_cmt() { + # collect() runs in a command-substitution subshell. Keep the header in a + # per-channel tmpfs file so a PDU arriving in the next drain() is paired + # with it, never with a header from another AT channel. + if [ -s "$CMT_PENDING_FILE" ]; then + case $1 in + ''|*[!0123456789abcdefABCDEF]*) ;; + *) if [ "$(( $(date +%s) - $(date -r "$CMT_PENDING_FILE" +%s 2>/dev/null || echo 0) ))" -le 10 ]; then + printf '%s\n%s\n' "$(cat "$CMT_PENDING_FILE")" "$1" | "$CMT_SPOOL" || + echo "mu300-atd: could not persist direct SMS" >&2 + fi ;; + esac + rm -f "$CMT_PENDING_FILE" + fi + case $1 in '+CMT:'*) printf '%s\n' "$1" > "$CMT_PENDING_FILE" ;; esac +} # Use '-' rather than ':-': an explicitly empty value means this secondary # daemon must not open any URC channel. With ':-', atd2 and atd3 both fell back # to nr0 and three readers split/lost the unsolicited stream. @@ -108,9 +131,12 @@ for n in ${MU300_AT_URC_CHANNELS-0}; do ( exec 3<&- # the command channel belongs to the parent, not to a drainer log=$URCDIR/$(basename "$other").log + CMT_PENDING_FILE=$URCDIR/$(basename "$other").cmt-pending : > "$log" while IFS= read -r urc; do - printf '%s\n' "${urc%"$CR"}" >> "$log" + urc=${urc%"$CR"} + capture_cmt "$urc" + printf '%s\n' "$urc" >> "$log" # cheap cap: start over rather than grow without end, /run is RAM [ "$(wc -c < "$log" 2>/dev/null || echo 0)" -gt "$URCMAX" ] && : > "$log" done < "$other" @@ -153,7 +179,11 @@ drain() { # throw away whatever the modem sent while nobody was asking (URCs), # Thrown away for the purpose of the next command, but not lost: answers that arrive after their OK # land here, and some of them matter. +CUSD is the plain case - the network's reply to *101# comes # seconds after the modem has already said OK - and +CMTI, announcing a new SMS, is another. - [ -n "$junk" ] && printf '%s\n' "${junk%"$CR"}" >> "$URCDIR/$(basename "$DEV").log" 2>/dev/null + if [ -n "$junk" ]; then + junk=${junk%"$CR"} + capture_cmt "$junk" + printf '%s\n' "$junk" >> "$URCDIR/$(basename "$DEV").log" 2>/dev/null + fi done } @@ -164,6 +194,7 @@ collect() { # collect TIMEOUT -> the reply lines, up to the final result code IFS= read -r -t 2 l <&3 || continue l=${l%"$CR"} [ -n "$l" ] || continue + capture_cmt "$l" echo "$l" case $l in OK|ERROR|+CME\ ERROR*|+CMS\ ERROR*|CONNECT*|NO\ CARRIER) return 0 ;; diff --git a/rootfs/overlay/opt/mu300/bin/mu300-cmt-spool b/rootfs/overlay/opt/mu300/bin/mu300-cmt-spool new file mode 100644 index 00000000..a24c4d85 --- /dev/null +++ b/rootfs/overlay/opt/mu300/bin/mu300-cmt-spool @@ -0,0 +1,21 @@ +#!/bin/sh +# Persist one unsolicited +CMT PDU before the modem is acknowledged. The AT +# daemon supplies header and PDU on stdin; SMS data never appears in argv. +set -eu +umask 077 +POOL=${MU300_SMS_POOL:-/etc/mu300/sms} +SPOOL=$POOL/incoming +IFS= read -r header || exit 1 +IFS= read -r pdu || exit 1 +case $header in '+CMT:'*) ;; *) exit 1 ;; esac +case $pdu in ''|*[!0123456789abcdefABCDEF]*) exit 1 ;; esac +[ $(( ${#pdu} % 2 )) = 0 ] && [ ${#pdu} -le 1024 ] || exit 1 +mkdir -p "$SPOOL" +part=$(mktemp "$SPOOL/.cmt.XXXXXXXX") || exit 1 +trap 'rm -f "$part"' EXIT INT TERM +printf '%s\n' "$pdu" > "$part" +mv "$part" "$part.ready" +trap - EXIT INT TERM +# Persist this PDU and the directory entry before any network acknowledgement. +# A global sync needlessly flushes the whole TF card and can stall receipt. +sync "$part.ready" "$SPOOL" 2>/dev/null || sync diff --git a/rootfs/overlay/opt/mu300/bin/mu300-sms b/rootfs/overlay/opt/mu300/bin/mu300-sms index 4ff9a4d9..c3df14a0 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-sms +++ b/rootfs/overlay/opt/mu300/bin/mu300-sms @@ -10,12 +10,16 @@ # mu300-sms sync pull everything AT+CMGL lists into the pool # All AT traffic goes through mu300-atd (via mu300-at); the AT channel is never opened here. set -u +umask 077 export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin" -POOL=${MU300_SMS_POOL:-/var/lib/mu300/sms} +POOL=${MU300_SMS_POOL:-/etc/mu300/sms} MSGDIR=$POOL/msg ATDIR=${MU300_AT_DIR:-/run/mu300-at} PAGE=${MU300_SMS_PAGE:-10} +PDU_AWK=${MU300_SMS_PDU_AWK:-/opt/mu300/lib/sms-pdu.awk} +DIRECT_FLAG=${MU300_SMS_DIRECT_FLAG:-/run/mu300-sms-direct} +OPLOCK=${MU300_SMS_OP_LOCK:-/tmp/mu300-sms-op.lock} die() { echo "mu300-sms: $*" >&2; exit 1; } @@ -50,8 +54,37 @@ pool_lock() { echo $$ > "$lock/pid" } +# Do not install an EXIT trap for this lock: ash/dash also run it when a +# command-substitution subshell exits, silently unlocking the live writer. +# A killed writer leaves a PID-marked lock that pool_lock safely reclaims. pool_unlock() { rm -rf "$POOL/.lock" 2>/dev/null || true; } +# A SIM slot can be reused between CMGR and CMGD. Serialize the script's SIM +# readers/deleters and mode changes, including a concurrent LuCI manual sync. +sms_op_lock() { + local owner n=0 + while ! mkdir "$OPLOCK" 2>/dev/null; do + owner=$(cat "$OPLOCK/pid" 2>/dev/null || true) + if [ -n "$owner" ] && [ -d "/proc/$owner" ] && + tr '\0' ' ' < "/proc/$owner/cmdline" 2>/dev/null | grep -q mu300-sms; then + n=$((n + 1)) + [ "$n" -ge 30 ] && die "SMS operation is busy" + sleep 1 + else + rm -f "$OPLOCK/pid" + rmdir "$OPLOCK" 2>/dev/null || die "stale SMS operation lock could not be removed" + fi + done + echo $$ > "$OPLOCK/pid" +} +sms_op_unlock() { + if [ "$(cat "$OPLOCK/pid" 2>/dev/null)" = "$$" ]; then + rm -f "$OPLOCK/pid" + rmdir "$OPLOCK" 2>/dev/null || true + fi + return 0 +} + hdr() { # hdr FILE field (headers only: the body may legitimately repeat any "field: " line) sed -n "1,/^$/s/^$2: //p" "$1" 2>/dev/null | head -1 } @@ -72,13 +105,13 @@ fingerprint() { next_id() { local id id=$(($(cat "$POOL/next_id" 2>/dev/null || echo 0) + 1)) - echo "$id" > "$POOL/next_id" + echo "$id" > "$POOL/next_id" || return 1 printf '%06d' "$id" } -store_msg() { # store_msg dir status peer scts sim_index coding body -> id on stdout +store_msg() { # store_msg dir status peer scts sim_index coding body [fingerprint ref total part source] local dir=$1 status=$2 peer=$3 scts=$4 simidx=$5 coding=$6 text=$7 id f part - id=$(next_id) + id=$(next_id) || return 1 f=$MSGDIR/$id part=$f.part { @@ -88,14 +121,18 @@ store_msg() { # store_msg dir status peer scts sim_index coding body -> id on s if [ "$dir" = mt ]; then printf 'from: %s\n' "$peer"; else printf 'to: %s\n' "$peer"; fi printf 'scts: %s\n' "$scts" printf 'received: %s\n' "$(date +%s)" + printf 'source: %s\n' "${12:-sim}" printf 'sim_index: %s\n' "$simidx" printf 'coding: %s\n' "$coding" - printf 'fingerprint: %s\n' "$(fingerprint "$peer" "$scts" "$text")" + printf 'fingerprint: %s\n' "${8:-$(fingerprint "$peer" "$scts" "$text")}" + [ -n "${9:-}" ] && printf 'multipart_ref: %s\n' "$9" + [ -n "${10:-}" ] && printf 'multipart_total: %s\n' "${10}" + [ -n "${11:-}" ] && printf 'multipart_part: %s\n' "${11}" printf 'length: %s\n' "$(printf '%s' "$text" | wc -c | tr -d ' ')" printf '\n' printf '%s\n' "$text" - } > "$part" - mv "$part" "$f" + } > "$part" || return 1 + mv "$part" "$f" || return 1 echo "$id" } @@ -270,7 +307,11 @@ select_storage() { if [ -s "$cache" ]; then s=$(cat "$cache" 2>/dev/null) case $s in SM|MT|ME) - at "AT+CPMS=\"$s\"" 6 >/dev/null 2>&1 && { echo "$s"; return 0; } + reply=$(at "AT+CPMS=\"$s\"" 6 2>/dev/null) && { + record_storage "$s" "$reply" + echo "$s" + return 0 + } ;; esac rm -f "$cache" @@ -286,17 +327,34 @@ select_storage() { case "$used:$total" in *[!0-9:]*|:*) continue ;; esac if [ "$used" -gt 0 ]; then echo "$s" > "$cache" + record_storage "$s" "$reply" echo "$s" return 0 fi [ "$total" -gt 0 ] && [ -z "$best" ] && best=$s done [ -n "$best" ] || best=ME - at "AT+CPMS=\"$best\"" 6 >/dev/null || return 1 + reply=$(at "AT+CPMS=\"$best\"" 6) || return 1 echo "$best" > "$cache" + record_storage "$best" "$reply" echo "$best" } +# The daemon syncs periodically; expose its last CPMS reading to the UI without +# adding another AT consumer to the five-second page refresh. Never infer free +# capacity from the local pool size (it can contain messages no longer on SIM). +record_storage() { + local store=$1 reply=$2 line used total part + line=$(printf '%s\n' "$reply" | grep '^+CPMS:' | head -1) + used=$(printf '%s\n' "$line" | awk -F'[,:]' '{gsub(/ /,"",$2); print $2}') + total=$(printf '%s\n' "$line" | awk -F'[,:]' '{gsub(/ /,"",$3); print $3}') + case "$used:$total" in *[!0-9:]*|:*|*:) return 0 ;; esac + [ "$total" -gt 0 ] || return 0 + part=$POOL/storage.part.$$ + printf '%s %s %s %s\n' "$store" "$used" "$total" "$(date +%s)" > "$part" && + mv "$part" "$POOL/storage" +} + # List the SIM as TSV records, by whichever door this firmware opens. The measured cases: # * CMGF=1 refused -> report; nothing to list with # * AT+CMGL="ALL" refused -> some firmwares only take the numeric stat (CMGL=4) in text mode @@ -339,6 +397,14 @@ sim_list() { # ------------------------------------------------------------------ commands cmd_sync() { + # Direct delivery is PDU-only. The legacy text-mode reader would leave + # CMGF=1 behind and turn the next +CMT into an undecodable body. PDU + # archival both imports and frees the exceptional SIM-resident messages. + if [ -f "$DIRECT_FLAG" ]; then + cmd_archive_sim + return $? + fi + sms_op_lock pool_init local reply tmp new=0 total=0 tmp=$(mktemp "${TMPDIR:-/tmp}/mu300-sms.XXXXXX") || die mktemp @@ -363,7 +429,6 @@ cmd_sync() { END { for (i = 1; i <= n; i++) { k = order[i]; split(k, a, "|"); print idx[k] "\t" stat[k] "\t" a[1] "\t" a[2] "\t" body[k] } } ' "$tmp" > "$merged" && mv "$merged" "$tmp" pool_lock - trap pool_unlock EXIT INT TERM # fingerprints of what the pool already holds, so a sync is idempotent and the SIM index of # a still-present message stays current (indexes shift whenever anything deletes from the SIM) local fpfile idx stat oa scts body f fpid @@ -410,7 +475,128 @@ cmd_sync() { rm -f "$tmp" "$fpfile" echo "sync: $new new, $total on the SIM, $(ids_newest_first | wc -l | tr -d ' ') in the pool" pool_unlock - trap - EXIT INT TERM + sms_op_unlock +} + +# Called by mu300-smsd for a PDU that atd has already persisted from +CMT. +# Idempotent: a network retry with the same PDU must not duplicate the inbox. +# The modem is acknowledged only *after* this command returns successfully. +cmd_import_pdu() { + local file=${1:-} pdu decoded idx peer scts ref total part body hash text_hash f known= newid= coding=pdu + local source=${2:-direct} + case $source in direct|sim) ;; *) die "invalid SMS source" ;; esac + [ -f "$file" ] || die "direct SMS spool file is missing" + IFS= read -r pdu < "$file" || die "direct SMS spool file is empty" + case $pdu in ''|*[!0123456789abcdefABCDEF]*) die "invalid direct SMS PDU" ;; esac + [ $(( ${#pdu} % 2 )) = 0 ] || die "odd-length direct SMS PDU" + [ -r "$PDU_AWK" ] || die "SMS PDU decoder is missing" + # The decoder emits UTF-8 bytes with %c; force byte-oriented awk even on + # systems whose default locale treats %c values as Unicode code points. + decoded=$(printf '0\t%s\n' "$pdu" | LC_ALL=C awk -F '\t' -v mode=decode -f "$PDU_AWK") || decoded= + if [ -n "$decoded" ]; then + # Tabs are IFS whitespace: read collapses an empty reference field + # on single-part messages and shifts the body into multipart_part. + # A non-whitespace separator preserves every optional field. + IFS="$(printf '\001')" read -r idx peer scts ref total part body </dev/null || sync + fi + pool_unlock +} + +# Some SMS classes are SIM-resident even with CNMI direct routing. Copy each +# original PDU to persistent storage, import it into the local pool and read it +# back before deleting *that exact slot*. A failed step keeps the SIM original. +# Never issue CMGD=1,4 (wipe all): indices can move as messages arrive/delete. +cmd_archive_sim() { + sms_op_lock + pool_init + local reply tmp sorted idx stat pdu check hash archive part count=0 planned used + reply=$(at 'AT+CPMS="SM"' 6) || die "cannot select SIM storage" + printf '%s\n' "$reply" | grep -q '^OK' || die "SIM storage was refused" + used=$(printf '%s\n' "$reply" | awk -F'[,:]' '/^\+CPMS:/ { gsub(/ /,"",$2); print $2; exit }') + case $used in ''|*[!0-9]*) die "SIM capacity response was invalid" ;; esac + record_storage SM "$reply" + if [ "$used" -eq 0 ]; then + echo "SIM archive: no stored messages" + sms_op_unlock + return 0 + fi + reply=$(at 'AT+CMGF=0' 6) || die "cannot select PDU mode" + printf '%s\n' "$reply" | grep -q '^OK' || die "PDU mode was refused" + reply=$(at 'AT+CMGL=4' 20) || die "cannot list SIM PDUs" + printf '%s\n' "$reply" | grep -q '^OK' || die "SIM PDU listing was incomplete" + tmp=$(mktemp "${TMPDIR:-/tmp}/mu300-sms.XXXXXX") || die mktemp + sorted=$(mktemp "${TMPDIR:-/tmp}/mu300-sms.XXXXXX") || { rm -f "$tmp"; die mktemp; } + printf '%s\n' "$reply" | awk ' + /^\+CMGL: *[0-9]+,[0-3],/ { + h=$0; sub(/^\+CMGL: */, "", h) + split(h, a, ","); idx=a[1]; stat=a[2]; next + } + /^[0-9A-Fa-f]+$/ { if (idx != "") { print idx "\t" stat "\t" $0; idx="" } } + ' > "$tmp" + sort -rn "$tmp" > "$sorted" + planned=$(wc -l < "$sorted" | tr -d ' ') + [ "$planned" -ge "$used" ] || { rm -f "$tmp" "$sorted"; die "SIM listing omitted stored messages; nothing deleted"; } + mkdir -p "$POOL/archive" + while IFS="$(printf '\t')" read -r idx stat pdu; do + [ -n "$idx" ] || continue + case $pdu in ''|*[!0123456789abcdefABCDEF]*) break ;; esac + [ $(( ${#pdu} % 2 )) = 0 ] || break + # Re-read the slot just before deletion; a concurrent arrival or user + # action must not turn an old listing into deletion of another message. + reply=$(at "AT+CMGR=$idx" 6) || break + check=$(printf '%s\n' "$reply" | awk '/^\+CMGR:/ { seen=1; next } seen && /^[0-9A-Fa-f]+$/ { print; exit }') + [ "$check" = "$pdu" ] || break + hash=$(printf '%s' "$pdu" | md5sum | cut -d' ' -f1) + archive=$POOL/archive/$hash.pdu + if [ ! -f "$archive" ]; then + part=$archive.part.$$ + printf '%s\n' "$pdu" > "$part" && mv "$part" "$archive" || break + fi + [ "$(cat "$archive" 2>/dev/null)" = "$pdu" ] || break + sync "$archive" "$POOL/archive" 2>/dev/null || sync + case $stat in 0|1) "$0" import-pdu "$archive" sim || break ;; esac + reply=$(at "AT+CMGD=$idx" 6) || break + printf '%s\n' "$reply" | grep -q '^OK' || break + count=$((count + 1)) + done < "$sorted" + rm -f "$tmp" "$sorted" + reply=$(at 'AT+CPMS="SM"' 6 2>/dev/null || true) + record_storage SM "$reply" + echo "SIM archive: $count slot(s) freed; original PDUs retained in $POOL/archive" + sms_op_unlock + [ "$count" -eq "$planned" ] || return 1 } cmd_list() { @@ -528,6 +714,7 @@ cmd_send() { len=$(( (${#pdu} - 2) / 2 )) echo "submitting to $num ($len octets, $((udl / 2)) UCS-2 units)" + sms_op_lock local r0 r2 submit r0=$(at 'AT+CAVIMS=1' 6) case $r0 in *OK*) ;; *) die "modem refused AT+CAVIMS=1: $r0" ;; esac @@ -535,10 +722,8 @@ cmd_send() { case $r0 in *OK*) ;; *) die "modem refused AT+CMGF=0: $r0" ;; esac submit=$(printf 'AT+CMGS=%s\r%s\032' "$len" "$pdu") r2=$(at "$submit" 25) - # back to text mode whatever happened: this firmware boots in PDU mode, where a manual - # AT+CMGL="ALL" answers +CMS ERROR: 302, and leaving PDU behind after every submit is how - # the next reader gets confused - at 'AT+CMGF=1' 6 >/dev/null || true + # Stay in PDU mode. Switching back to text here corrupts direct +CMT + # delivery; the legacy SIM reader selects text explicitly when needed. if ! printf '%s\n' "$r2" | grep -q '^+CMGS:'; then die "submit failed: $(printf '%s\n' "$r2" | grep -E 'CMS|ERROR' | head -1)" fi @@ -549,6 +734,7 @@ cmd_send() { [ -n "$(printf '%s' "$text" | LC_ALL=C tr -d '\000-\177')" ] && coding=ucs2 store_msg mo sent "$num" "$(date '+%y/%m/%d,%H:%M:%S')" "" "$coding" "$text" >/dev/null pool_unlock + sms_op_unlock echo "sent ($(printf '%s\n' "$r2" | sed -n 's/^+CMGS: //p' | head -1))" } @@ -568,14 +754,13 @@ cmd_delete() { printf '%s\n' "$(hdr "$1" fingerprint)" >> "$POOL/deleted" 2>/dev/null; } if [ "$what" = all ]; then for id in $(ids_newest_first); do + [ "$wantsim" = true ] && sim_delete "$id" || [ "$wantsim" = false ] || + die "SIM deletion failed for $id; remaining messages were kept" + pool_lock tombstone "$MSGDIR/$id" - [ "$wantsim" = true ] && sim_delete "$id" + rm -f "$MSGDIR/$id" + pool_unlock done - pool_lock - trap pool_unlock EXIT INT TERM - rm -f "$MSGDIR"/[0-9]* 2>/dev/null - pool_unlock - trap - EXIT INT TERM echo "pool emptied" return 0 fi @@ -584,16 +769,48 @@ cmd_delete() { id=$(printf '%06d' "$n") f=$MSGDIR/$id [ -f "$f" ] || die "no message $what" + if [ "$wantsim" = true ]; then + sim_delete "$id" || die "SIM deletion failed; local copy was kept" + fi + pool_lock tombstone "$f" - [ "$wantsim" = true ] && sim_delete "$id" rm -f "$f" + pool_unlock echo "deleted $what" } # CMGD by index alone is dangerous (indexes shift with every deletion), so the SIM is re-listed -# and the slot whose fingerprint matches the pool entry is the one deleted. No match: nothing -# happens to the SIM, which is also the answer for a message the SIM never held. +# and the slot whose fingerprint matches the pool entry is the one deleted. +SMS_DELETE_PAUSED=0 +sim_delete_restore() { + [ "$SMS_DELETE_PAUSED" = 1 ] || return 0 + SMS_DELETE_PAUSED=0 + if at 'AT+CMGF=0' 6 | grep -q '^OK' && + at 'AT+CNMI=3,2,2,1,1' 6 | grep -q '^OK'; then + return 0 + fi + rm -f "$DIRECT_FLAG" + at 'AT+CNMI=2,1,0,0,0' 6 >/dev/null 2>&1 || true + echo "mu300-sms: direct SMS delivery could not be restored; SIM fallback enabled" >&2 + return 1 +} sim_delete() { + local rc + sms_op_lock + if [ -f "$DIRECT_FLAG" ]; then + if ! at 'AT+CNMI=2,1,0,0,0' 6 | grep -q '^OK'; then + sms_op_unlock + return 1 + fi + SMS_DELETE_PAUSED=1 + fi + sim_delete_unlocked "$@" + rc=$? + sim_delete_restore || rc=1 + sms_op_unlock + return "$rc" +} +sim_delete_unlocked() { local id=$1 f=$MSGDIR/$id want simidx reply idx stat oa scts body fpid [ -f "$f" ] || return 0 want=$(hdr "$f" fingerprint) @@ -606,15 +823,21 @@ sim_delete() { *[!0-9A-Fa-f]*|"") ;; *) [ $(( ${#body} % 4 )) -eq 0 ] && body=$(printf '%b' "$(printf '%s\n' "$body" | ucs2_to_esc)") ;; esac + oa=$(peer_decode "$oa") [ "$(fingerprint "$oa" "$scts" "$body")" = "$want" ] && { simidx=$idx; break; } done <&2 + return 1 + fi + if at "AT+CMGD=$simidx" 6 | grep -q '^OK'; then + echo "deleted SIM slot $simidx for message $id" return 0 fi - at "AT+CMGD=$simidx" 6 | grep -q '^OK' && echo "deleted SIM slot $simidx for message $id" + echo "mu300-sms: modem refused to delete SIM slot $simidx" >&2 + return 1 } usage() { @@ -625,6 +848,8 @@ usage: mu300-sms list [PAGE] paged inbox, newest first (MU300_SMS_PAGE per p mu300-sms delete ID|all pool only; --sim also deletes the matching SIM slot mu300-sms mark ID read|unread mu300-sms sync pull everything AT+CMGL lists into the pool + mu300-sms import-pdu FILE save a persisted +CMT PDU before acknowledging it + mu300-sms archive-sim verify local PDU copies, then free SIM slots pool: $POOL (MU300_SMS_POOL to move it) EOF } @@ -637,6 +862,8 @@ case ${1:-list} in del) shift; cmd_delete "$@" ;; mark) shift; cmd_mark "$@" ;; sync) cmd_sync ;; + import-pdu) shift; cmd_import_pdu "$@" ;; + archive-sim) cmd_archive_sim ;; -h|--help|help) usage ;; *) usage; exit 2 ;; esac diff --git a/rootfs/overlay/opt/mu300/bin/mu300-smsd b/rootfs/overlay/opt/mu300/bin/mu300-smsd index 722bb999..61de9778 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-smsd +++ b/rootfs/overlay/opt/mu300/bin/mu300-smsd @@ -1,23 +1,30 @@ #!/bin/sh -# Keep the local SMS pool in step with the SIM (see mu300-sms). +# Keep the local SMS pool in step with direct +CMT delivery and the SIM fallback. # # Receiving is +CMTI-driven where it can be: mu300-atd logs every unsolicited line of every # channel into /run/mu300-at/urc/*.log, so a new "+CMTI:" anywhere changes the md5 of the # +CMTI lines and that is the trigger. The logs are capped and truncated, not rotated - a # truncation changes the signature too, and a sync is idempotent, so a spurious trigger costs -# one paced AT+CMGL. A full sync also runs once per MU300_SMS_SYNC_INTERVAL regardless, as the +# one paced AT+CMGL. A SIM archive also runs once per MU300_SMS_SYNC_INTERVAL regardless, as the # safety net for an announcement missed while nobody watched. # -# Nothing here ever deletes from the SIM; deletion is the operator's explicit "delete --sim". +# A direct SMS is acknowledged only after atd has spooled its PDU and mu300-sms +# has committed it to the persistent pool. The SIM fallback is archived before +# any of its slots are released. set -u export PATH="$PATH:/opt/mu300/bin:/opt/mu300/busybox-bin:/usr/sbin:/sbin" +# A dead/busy AT client must not hold the receiver behind the 90 s CLI default. +export MU300_AT_LOCK_WAIT=${MU300_AT_LOCK_WAIT:-8} -POOL=${MU300_SMS_POOL:-/var/lib/mu300/sms} +POOL=${MU300_SMS_POOL:-/etc/mu300/sms} +export MU300_SMS_POOL=$POOL ATDIR=${MU300_AT_DIR:-/run/mu300-at} URCDIR=$ATDIR/urc POLL=${MU300_SMS_POLL:-5} -SYNC_INTERVAL=${MU300_SMS_SYNC_INTERVAL:-30} +SYNC_INTERVAL=${MU300_SMS_SYNC_INTERVAL:-300} SMS=${MU300_SMS_BIN:-$(command -v mu300-sms 2>/dev/null || echo /opt/mu300/bin/mu300-sms)} +DIRECT_FLAG=${MU300_SMS_DIRECT_FLAG:-/run/mu300-sms-direct} +SPOOL=$POOL/incoming # one daemon, the house pattern: a second instance (procd respawning, a service started twice) # waits for the lock only as long as the holder is alive, then takes over @@ -50,11 +57,48 @@ until mu300-at -t 4 'AT+CPIN?' 2>/dev/null | grep -q READY; do [ "$n" -gt 60 ] && { echo "mu300-smsd: SIM never became ready, syncing anyway" >&2; break; } sleep 10 done -# Without CNMI the modem files incoming messages silently (measured 0,0,0,1,0), -# the +CMTI trigger below never fires and arrival waits for the 30 s net. Ask -# for storage indications; a refusal still leaves the periodic sync working. -mu300-at -t 4 'AT+CNMI=2,1,0,0,0' >/dev/null 2>&1 || true -"$SMS" sync +at_ok() { mu300-at -t 5 "$1" 2>/dev/null | grep -q '^OK'; } +rm -f "$DIRECT_FLAG" +# Import anything already on SIM before enabling direct delivery. If direct +# routing is rejected, the old +CMTI/periodic-sync path remains functional. +at_ok 'AT+CNMI=2,1,0,0,0' || true +"$SMS" archive-sim || { + echo "mu300-smsd: PDU archive incomplete; attempting read-only legacy import" >&2 + "$SMS" sync || true +} +if at_ok 'AT+CMGF=0' && at_ok 'AT+CSMS=1' && + at_ok 'AT+CNMI=3,2,2,1,1'; then + : > "$DIRECT_FLAG" + echo "mu300-smsd: direct +CMT delivery enabled" >&2 +else + at_ok 'AT+CNMI=2,1,0,0,0' || true + echo "mu300-smsd: direct delivery rejected; using SIM indications" >&2 +fi + +process_spool() { + local f reply + # The CMT writer uses hidden mktemp names. Keep accepting visible spool + # files too; shell '*' alone never matches the writer's .cmt.* names. + for f in "$SPOOL"/*.ready "$SPOOL"/.cmt.*.ready; do + [ -f "$f" ] || continue + if ! "$SMS" import-pdu "$f"; then + echo "mu300-smsd: could not import $f" >&2 + return 1 + fi + reply=$(mu300-at -t 5 'AT+CNMA=1' 2>/dev/null || true) + if ! printf '%s\n' "$reply" | grep -q '^OK'; then + echo "mu300-smsd: direct SMS confirmation failed" >&2 + return 1 + fi + rm -f "$f" + done +} + +sync_fallback() { + # PDU archival leaves direct delivery's CMGF=0 untouched. No text-mode + # window, no lost +CMT, and fewer commands on the shared AT channel. + "$SMS" archive-sim +} signature() { cat "$URCDIR"/*nr*.log 2>/dev/null | grep -aF '+CMTI' | md5sum 2>/dev/null | cut -d' ' -f1 @@ -65,17 +109,34 @@ elapsed=0 echo "mu300-smsd: pooling into $POOL (poll ${POLL}s, full sync every ${SYNC_INTERVAL}s)" >&2 while :; do sleep "$POLL" + if process_spool; then + spool_failures=0 + else + spool_failures=$((${spool_failures:-0} + 1)) + if [ "$spool_failures" -ge 3 ]; then + # Never spin AT+CNMA against a CP that refuses acknowledgement. + # Keep the saved PDU, revert to SIM indications, and let the archive + # path continue to free SIM slots after each successful sync. + rm -f "$DIRECT_FLAG" + at_ok 'AT+CNMI=2,1,0,0,0' || true + for f in "$SPOOL"/*.ready "$SPOOL"/.cmt.*.ready; do + [ -f "$f" ] && mv "$f" "${f%.ready}.ack-failed" + done + echo "mu300-smsd: direct mode disabled after repeated import/ack failures" >&2 + spool_failures=0 + fi + fi s=$(signature) if [ "$s" != "$last" ]; then last=$s sleep 2 # let the message land in the SIM storage before listing it - "$SMS" sync || echo "mu300-smsd: sync failed, will retry on the next trigger" >&2 + sync_fallback || echo "mu300-smsd: sync failed, will retry on the next trigger" >&2 elapsed=0 continue fi elapsed=$((elapsed + POLL)) if [ "$elapsed" -ge "$SYNC_INTERVAL" ]; then elapsed=0 - "$SMS" sync || true + sync_fallback || true fi done diff --git a/rootfs/overlay/opt/mu300/lib/sms-pdu.awk b/rootfs/overlay/opt/mu300/lib/sms-pdu.awk index f0823a1c..35f5940b 100644 --- a/rootfs/overlay/opt/mu300/lib/sms-pdu.awk +++ b/rootfs/overlay/opt/mu300/lib/sms-pdu.awk @@ -121,14 +121,19 @@ function bcd_decode(h, off, digits, i, b, lo, hi, out) { } return out } -function ts_decode(h, off, i, b, d, p) { +function ts_decode(h, off, i, b, d, p, quarters, sign) { d = "" for (i = 0; i < 6; i++) { b = byteat(h, off + i) d = d substr("0123456789", b_and(b, 15) + 1, 1) substr("0123456789", b_rshift(b, 4) + 1, 1) if (i == 2) d = d " "; else if (i < 2) d = d "-"; else if (i < 5) d = d ":" } - return "20" d + # TP-SCTS carries a signed quarter-hour UTC offset in swapped BCD. + # Do not discard it: the host timezone need not match the SIM network. + b = byteat(h, off + 6) + sign = b_and(b, 8) ? "-" : "+" + quarters = b_and(b, 7) * 10 + b_rshift(b, 4) + return "20" d sprintf("%s%02d:%02d", sign, int(quarters / 4), (quarters % 4) * 15) } function esc_field(s) { gsub(/\t/, " ", s); gsub(/\n/, " ", s); gsub(/\r/, "", s); return s } diff --git a/tests/test_container_support.py b/tests/test_container_support.py new file mode 100644 index 00000000..99727113 --- /dev/null +++ b/tests/test_container_support.py @@ -0,0 +1,137 @@ +"""Fail closed when KVM is only requested, or optional modules never get shipped.""" +import hashlib +import importlib.util +import io +import tarfile +import tempfile +import unittest +from pathlib import Path + +from helpers import TOP + +spec = importlib.util.spec_from_file_location('container_support', TOP / 'upstream/check-container-support.py') +support = importlib.util.module_from_spec(spec) +spec.loader.exec_module(support) + + +class ContainerSupport(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.out = Path(self.tmp.name) + (self.out / 'modules').mkdir() + for name in ('modules.builtin', 'modules.builtin.modinfo'): + (self.out / name).write_bytes(b'builtin metadata') + self.config = {key: 'y' for key in support.BUILTIN} + self.config.update({key: 'm' for key in support.MODULES}) + (self.out / 'Image').write_bytes(b'Linux version 6.18.54 test Image') + for name in support.MODULES.values(): + (self.out / 'modules' / f'{name}.ko').write_bytes(name.encode() + b'\0vermagic=6.18.54 SMP\0') + (self.out / 'modules/dependency.ko').write_bytes(b'needed dependency\0vermagic=6.18.54 SMP\0') + self.write_config() + (self.out / 'modules.in-tree').write_text('\n'.join(p.name for p in (self.out / 'modules').glob('*.ko')) + '\n') + self.manifests() + + def write_config(self): + (self.out / 'kernel.config').write_text(''.join(f'CONFIG_{k}={v}\n' for k, v in self.config.items())) + + def manifests(self): + for manifest, names in [('kernel.sha256', ['Image', 'kernel.config']), + ('modules.sha256', ['Image', 'kernel.config'] + + sorted(f'modules/{p.name}' for p in (self.out / 'modules').glob('*.ko')))]: + (self.out / manifest).write_text(''.join( + f'{hashlib.sha256((self.out / n).read_bytes()).hexdigest()} {n}\n' for n in names)) + + def test_complete_output_passes(self): + support.check(self.out) + + def test_config_without_kvm_cannot_ship(self): + self.config['KVM'] = 'n' + self.write_config() + self.manifests() + with self.assertRaisesRegex(ValueError, 'KVM'): + support.check(self.out) + + def test_missing_builtin_index_rejected_before_any_packaging(self): + (self.out / 'modules.builtin').unlink() + with self.assertRaisesRegex(ValueError, 'modules.builtin missing'): + support.check(self.out) + + def test_missing_required_module_even_if_manifest_is_regenerated(self): + (self.out / 'modules/vhost_net.ko').unlink() + self.manifests() + with self.assertRaisesRegex(ValueError, 'vhost_net'): + support.check(self.out) + + def test_missing_non_shortlisted_dependency(self): + (self.out / 'modules/dependency.ko').unlink() + self.manifests() + with self.assertRaisesRegex(ValueError, 'dependency'): + support.check(self.out) + + def test_changed_image_or_config_invalidates_old_modules(self): + (self.out / 'Image').write_bytes(b'new build same release') + # A kernel-only rebuild refreshes kernel.sha256, never modules.sha256. + (self.out / 'kernel.sha256').write_text(''.join( + f'{hashlib.sha256((self.out / n).read_bytes()).hexdigest()} {n}\n' + for n in ['Image', 'kernel.config'])) + with self.assertRaisesRegex(ValueError, 'modules.sha256'): + support.check(self.out) + + def test_modified_or_extra_module_rejected(self): + (self.out / 'modules/vhost_net.ko').write_bytes(b'old module') + with self.assertRaisesRegex(ValueError, 'no longer matches'): + support.check(self.out) + self.manifests() + (self.out / 'modules/stale.ko').write_bytes(b'stale') + with self.assertRaisesRegex(ValueError, 'stale'): + support.check(self.out) + + def test_hyphen_underscore_collision_rejected(self): + (self.out / 'modules/vhost-net.ko').write_bytes(b'alias\0vermagic=6.18.54 SMP\0') + self.manifests() + with self.assertRaisesRegex(ValueError, 'collide'): + support.check(self.out) + + def test_mixed_kernel_modules_rejected_even_with_fresh_hashes(self): + (self.out / 'modules/vhost_net.ko').write_bytes(b'vermagic=7.2.8 SMP\0') + self.manifests() + with self.assertRaisesRegex(ValueError, 'vermagic'): + support.check(self.out) + + def test_fragment_and_packaging_routes_keep_support(self): + support.config_check(TOP / 'upstream/mu300-mainline.config') + for path in ['upstream/make-bundle.sh', 'tools/build-openwrt-tf-magisk.sh', + 'openwrt/build-rootfs.sh']: + self.assertIn('check-container-support.py', (TOP / path).read_text()) + builder = (TOP / 'upstream/build-modules.sh').read_text() + self.assertIn('INSTALL_MOD_STRIP=1', builder) + self.assertIn('modules_install', builder) + self.assertIn('modules.in-tree.names', builder) + early = (TOP / 'upstream/module-order.txt').read_text() + self.assertNotIn('vhost_net', early) + self.assertNotIn('br_netfilter', early) + + def test_final_rootfs_requires_identical_modules_and_builtin_indexes(self): + for name in ('modules.builtin', 'modules.builtin.modinfo'): + (self.out / name).write_bytes(b'builtin metadata') + archive = self.out / 'rootfs.tar.gz' + paths = list((self.out / 'modules').glob('*.ko')) + [ + self.out / 'modules.builtin', self.out / 'modules.builtin.modinfo'] + def write_tar(skip=None, damage=None): + with tarfile.open(archive, 'w:gz') as tar: + for path in paths: + if path.name == skip: + continue + data = b'wrong' if path.name == damage else path.read_bytes() + info = tarfile.TarInfo('./lib/modules/6.18.54/' + path.name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + write_tar() + support.check_rootfs(self.out, archive, '6.18.54') + write_tar(skip='modules.builtin') + with self.assertRaisesRegex(ValueError, 'missing'): + support.check_rootfs(self.out, archive, '6.18.54') + write_tar(damage='vhost_net.ko') + with self.assertRaisesRegex(ValueError, 'differs'): + support.check_rootfs(self.out, archive, '6.18.54') diff --git a/tests/test_dashboard_identity.py b/tests/test_dashboard_identity.py new file mode 100644 index 00000000..870720d6 --- /dev/null +++ b/tests/test_dashboard_identity.py @@ -0,0 +1,113 @@ +"""Optional own-number lookup stays in the infrequent SIM identity tier.""" +import json + +from helpers import ShellTest, TOP + + +CELL = TOP / 'openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/cell' + + +class DashboardIdentity(ShellTest): + def test_ims_uri_parsing(self): + source = CELL.read_text(encoding='utf-8') + helper = source[source.index('ims_number() {'):source.index('# --------------------------------------------------------------- one collector')] + cases = [ + ('+SPPAURI: sip:+8613800000000@ims.example.org\nOK\n', '+8613800000000'), + ('+SPPAURI: "sip:+8613800000000@ims.example.org","tel:+905551234567"\n', '+905551234567'), + ('+SPPAURI: \n', '13800000000'), + ('+SPPAURI: sips:+90-555-1234567@ims.example.org;user=phone\n', '+905551234567'), + ('+SPPAURI: sip:460011234567890@ims.example.org\n', ''), + ('+SPPAURI: sip:alice@ims.example.org\n', ''), + ('+SPPAURI: tel:+1234567890123456\n', ''), + ('+SPPAURI: ""\nOK\n', ''), ('ERROR\n', ''), + ] + for shell in self.each_shell(): + for reply, expected in cases: + result = self.sh(shell, helper + '\nprintf "%s" "$REPLY" | ims_number', REPLY=reply) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), expected) + + def test_cnum_parsing(self): + source = CELL.read_text(encoding='utf-8') + helper = source[source.index('cnum_number() {'):source.index('# --------------------------------------------------------------- one collector')] + cases = [ + ('AT+CNUM\r\n+CNUM: "","+8613800000000",145\r\nOK\r\n', '+8613800000000'), + ('+CNUM: "SIM, voice","8613800000000",145,,,4\nOK\n', '+8613800000000'), + ('+CNUM: "","13800000000",129\nOK\n', '13800000000'), + ('+CNUM: "","",129\n+CNUM: "voice","+90 555 123 4567",145\n', '+905551234567'), + ('OK\n', ''), ('ERROR\n', ''), + ('+CNUM: "my number","",129\n', ''), + ('+CNUM: "","unknown",129\n', ''), + ] + for shell in self.each_shell(): + for reply, expected in cases: + result = self.sh(shell, helper + '\nprintf "%s" "$REPLY" | tr -d "\\r" | cnum_number', REPLY=reply) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), expected) + + def test_empty_number_is_cached_and_old_cache_migrates_once(self): + self.stub('uci', 'exit 1') + self.stub('fake-at', '''printf '%s\\n' "$*" >> "$STUBLOG/at-commands" +case "$*" in + *AT+CFUN?*) printf '+CFUN: 1\\nOK\\n' ;; + *AT+CIMI*) printf '460011234567890\\nOK\\n' ;; + *) printf 'OK\\n' ;; +esac''') + for i, shell in enumerate(self.each_shell()): + ident = self.tmp / f'ident-{i}' + ident.mkdir() + (ident / 'sim.json').write_text('{"imsi":"460011234567890"}') + log = self.tmp / 'at-commands' + log.unlink(missing_ok=True) + env = dict(MU300_AT=self.stubs / 'fake-at', MU300_DASH_IDENT_DIR=ident, + MU300_DASH_DIR=self.tmp / f'cache-{i}', MU300_DASH_POOL_DIR=self.tmp / f'pool-{i}') + for mode in ('full', 'full', 'fast'): + result = self.script(shell, CELL, mode, **env) + self.assertEqual(result.returncode, 0, result.stderr) + cached = json.loads((ident / 'sim.json').read_text()) + self.assertIn('msisdn', cached) + self.assertIsNone(cached['msisdn']) + self.assertEqual(log.read_text().count('AT+CNUM'), 1) + self.assertEqual(log.read_text().count('AT+SPPAURI?'), 1) + data = json.loads((self.tmp / f'cache-{i}' / 'cell.json').read_text()) + self.assertIsNone(data['ident']['msisdn']) + + def test_ims_fallback_and_reboot_invalidation(self): + self.stub('uci', 'exit 1') + self.stub('fake-at', '''printf '%s\\n' "$*" >> "$STUBLOG/at-commands" +case "$*" in + *AT+CFUN?*) printf '+CFUN: 1\\nOK\\n' ;; + *AT+CIMI*) printf '460011234567890\\nOK\\n' ;; + *AT+CNUM*) printf '%s\\n' "$CNUM_REPLY" ;; + *AT+SPPAURI?*) printf '+SPPAURI: sip:+8613800000000@ims.example.org\\nOK\\n' ;; + *) printf 'OK\\n' ;; +esac''') + for i, shell in enumerate(self.each_shell()): + ident = self.tmp / f'ims-ident-{i}' + ident.mkdir() + cache = ident / 'sim.json' + cache.write_text(json.dumps({'msisdn': '+905550000000', 'boot_id': 'previous-boot'})) + log = self.tmp / 'at-commands' + log.unlink(missing_ok=True) + env = dict(MU300_AT=self.stubs / 'fake-at', MU300_DASH_IDENT_DIR=ident, + MU300_DASH_DIR=self.tmp / f'ims-cache-{i}', MU300_DASH_POOL_DIR=self.tmp / f'ims-pool-{i}', + CNUM_REPLY='+CME ERROR: 22') + result = self.script(shell, CELL, 'full', **env) + self.assertEqual(result.returncode, 0, result.stderr) + cached = json.loads(cache.read_text()) + self.assertEqual(cached['msisdn'], '+8613800000000') + self.assertEqual(cached['msisdn_source'], 'ims') + self.assertNotEqual(cached['boot_id'], 'previous-boot') + # Same boot serves the cache; no extra IMS request per refresh. + result = self.script(shell, CELL, 'full', **env) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(log.read_text().count('AT+SPPAURI?'), 1) + cached['boot_id'] = 'previous-boot' + cache.write_text(json.dumps(cached)) + env['CNUM_REPLY'] = '+CNUM: "","+905551234567",145\nOK' + result = self.script(shell, CELL, 'full', **env) + self.assertEqual(result.returncode, 0, result.stderr) + cached = json.loads(cache.read_text()) + self.assertEqual(cached['msisdn'], '+905551234567') + self.assertEqual(cached['msisdn_source'], 'sim') + self.assertEqual(log.read_text().count('AT+SPPAURI?'), 1) diff --git a/tests/test_dashboard_info.py b/tests/test_dashboard_info.py new file mode 100644 index 00000000..f4fecb10 --- /dev/null +++ b/tests/test_dashboard_info.py @@ -0,0 +1,88 @@ +"""Hot-path shell helpers must preserve the dashboard's JSON wire values.""" +import json +import shlex + +from helpers import ShellTest, TOP + + +INFO = TOP / 'openwrt' / 'luci-app-mu300' / 'root' / 'usr' / 'libexec' / 'unisoc-modem' / 'dashboard-info' + + +class DashboardInfo(ShellTest): + def station_code(self): + script = INFO.read_text() + helpers = script[script.index('n_or_null() {'):script.index('# ------------------------------------------------------------- temperature')] + stations = script[script.index('station_rows() {'):script.index('LAN_LEASES=')] + leases = self.tmp / 'leases' + leases.write_text('9999999999 E6:7A:77:59:7E:47 192.168.77.105 Xiaomi-17-Pro *\n' + '9999999999 aa:bb:cc:dd:ee:ff 192.168.77.106 * *\n') + stations = stations.replace('/tmp/dhcp.leases', str(leases)) + return helpers + '\nt3() { cat; return "${IW_RC:-0}"; }\n' + stations + '\nprintf \'{"count":%s,"clients":[%s]}\' "$W_CN" "$W_CLIST"' + + def test_mac_only_station_is_counted_without_fabricated_metrics(self): + for shell in self.each_shell(): + result = self.sh(shell, self.station_code(), + stdin='Station e6:7a:77:59:7e:47 (on wlan0)\n\tcurrent time: 1791393862131 ms\n') + self.assertEqual(result.returncode, 0, result.stderr) + data = json.loads(result.stdout) + self.assertEqual(data['count'], 1) + self.assertEqual(data['clients'][0], dict(mac='e6:7a:77:59:7e:47', host='Xiaomi-17-Pro', + ip='192.168.77.105', signal=None, tx=None, rx=None, conn=None)) + + def test_complete_station_blocks_and_deduplication(self): + dump = ('Station E6:7A:77:59:7E:47 (on wlan0)\n\tsignal: -42 [-42] dBm\n' + '\ttx bitrate: 866.7 MBit/s VHT-MCS 9\n\trx bitrate: 433.3 MBit/s\n' + '\tconnected time: 125 seconds\nStation aa:bb:cc:dd:ee:ff (on wlan0)\n' + 'Station e6:7a:77:59:7e:47 (on wlan0)\nStation invalid (on wlan0)\n') + for shell in self.each_shell(): + result = self.sh(shell, self.station_code(), stdin=dump) + self.assertEqual(result.returncode, 0, result.stderr) + data = json.loads(result.stdout) + self.assertEqual(data['count'], 2) + self.assertEqual(data['clients'][0]['signal'], -42) + self.assertEqual(data['clients'][0]['tx'], '866.7 Mbit/s') + self.assertEqual(data['clients'][0]['rx'], '433.3 Mbit/s') + self.assertEqual(data['clients'][0]['conn'], '2 min') + self.assertIsNone(data['clients'][1]['host']) + + def test_empty_station_table_and_query_failure_are_distinct(self): + for shell in self.each_shell(): + for rc, device, expected in [('0', 'lo', 0), ('1', 'lo', None), ('1', 'mu300-missing-test', 0)]: + result = self.sh(shell, self.station_code(), stdin='', IW_RC=rc, WIFI_DEVICE=device) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout), dict(count=expected, clients=[])) + + def test_conntrack_prefers_scalar_and_falls_back_only_when_needed(self): + script = INFO.read_text() + helper = script[script.index('conntrack_count() {'):script.index('CONNS=$(conntrack_count)')] + counter, table = self.tmp / 'counter', self.tmp / 'table' + command = helper + '\nconntrack_count ' + shlex.quote(str(counter)) + ' ' + shlex.quote(str(table)) + for shell in self.each_shell(): + for scalar, rows, expected in [('163\n', None, '163'), ('0\n', 'x\ny\n', '0'), + (None, 'x\ny\n', '2'), ('bad\n', 'x\n', '1'), + (None, '', '0'), (None, None, 'null')]: + for path, content in [(counter, scalar), (table, rows)]: + if content is None: + path.unlink(missing_ok=True) + else: + path.write_text(content) + result = self.sh(shell, command) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), expected) + + def test_json_string_escaping_matches_original_contract(self): + script = INFO.read_text() + helpers = script[script.index("CR=$(printf '\\r')"):script.index('# ------------------------------------------------------------- temperature')] + values = ['', 'normal', 'A\\B"C', '中文热点 🛜', 'line1\nline2\rline3'] + for shell in self.each_shell(): + for value in values: + result = self.sh(shell, helpers + '\nqs "$CASE"', CASE=value) + self.assertEqual(result.returncode, 0, result.stderr) + expected = (json.dumps(value.replace('\n', '').replace('\r', ''), ensure_ascii=False) + if value else 'null') + self.assertEqual(result.stdout, expected) + + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/tests/test_dashboard_layout.py b/tests/test_dashboard_layout.py new file mode 100644 index 00000000..53a87c29 --- /dev/null +++ b/tests/test_dashboard_layout.py @@ -0,0 +1,72 @@ +"""Client lists share their own responsive row, not the device/SIM column.""" +import json +import shutil +import subprocess +import unittest +from html.parser import HTMLParser + +from helpers import TOP + + +HOME = TOP / 'openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js' +COMMON = TOP / 'openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js' + + +class Layout(HTMLParser): + def __init__(self): + super().__init__() + self.stack = [] + self.ids = {} + + def handle_starttag(self, tag, attrs): + node = dict(attrs) + node['parent'] = self.stack[-1] if self.stack else None + if 'id' in node: + if node['id'] in self.ids: + raise AssertionError('duplicate id: ' + node['id']) + self.ids[node['id']] = node + if tag not in ('br', 'hr', 'input', 'img', 'meta', 'link'): + self.stack.append(node) + + def handle_endtag(self, tag): + self.stack.pop() + + +@unittest.skipUnless(shutil.which('node'), 'Node.js required') +class DashboardLayout(unittest.TestCase): + def test_lists_are_sibling_columns_below_device_details(self): + js = """ +const fs = require('fs'); +const home = new Function('view', 'uci', 'M', fs.readFileSync(process.argv[2], 'utf8'))( + { extend: obj => obj }, {}, {}); +process.stdout.write(JSON.stringify(home.html())); +""" + result = subprocess.run(['node', '-', str(HOME)], input=js, capture_output=True, + text=True, encoding='utf-8', check=True) + layout = Layout() + layout.feed(json.loads(result.stdout)) + clients = layout.ids['mud-clist']['parent'] + leases = layout.ids['mud-leases']['parent'] + self.assertIsNot(clients, leases) + self.assertIs(clients['parent'], leases['parent']) + self.assertIn('mud-client-cols', clients['parent']['class'].split()) + self.assertIs(layout.ids['mud-wcl']['parent']['parent'], clients) + self.assertIs(layout.ids['mud-wleases']['parent']['parent'], leases) + self.assertIsNot(layout.ids['mud-model']['parent']['parent']['parent'], clients) + self.assertIsNot(layout.ids['mud-model']['parent']['parent']['parent'], leases) + self.assertEqual(layout.stack, []) + self.assertIs(layout.ids['mud-fwos']['parent']['parent'], + layout.ids['mud-lanip']['parent']['parent']) + ids = list(layout.ids) + self.assertEqual(ids[ids.index('mud-lanip') + 1], 'mud-fwos') + + def test_layout_can_shrink_and_wrap_long_device_names(self): + css = COMMON.read_text(encoding='utf-8') + self.assertIn('minmax(min(100%,300px),1fr)', css) + self.assertIn('.mud-client-cols>div{min-width:0}', css) + self.assertIn('.mud-client-cols .mud-cli .t{flex-wrap:wrap;overflow-wrap:anywhere}', css) + self.assertIn('.mud-client-cols .mud-cli .s{overflow-wrap:anywhere}', css) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_dashboard_neighbors.py b/tests/test_dashboard_neighbors.py new file mode 100644 index 00000000..293ef96d --- /dev/null +++ b/tests/test_dashboard_neighbors.py @@ -0,0 +1,74 @@ +"""The dashboard must use the modem's NR band and parse LTE neighbor blocks.""" +import json + +from helpers import ShellTest, TOP + + +CELL = TOP / 'openwrt' / 'luci-app-mu300' / 'root' / 'usr' / 'libexec' / 'unisoc-modem' / 'cell' +NR_REPLY = ( + '78,78,78,78,78,78-627264,627264,627264,627264,627264,627264-' + '687,973,234,232,709,954--10865,-10542,-10889,-10995,-11825,-11497-' + '-1195,-1137,-1846,-1632,-1836,-1499-336,649,-749,-456,-766,-277-' + '32,32,32,32,32,32-1,1,1,1,1,1' +) +LTE_REPLY = ( + '1650,211,-9500,-800,0,0,0,0,0,0,0,0-' + '46600,123,-11000,-1500,0,0,0,0,0,0,0,0' +) + + +class DashboardNeighbors(ShellTest): + def setUp(self): + super().setUp() + self.stub('uci', 'exit 1') + + def collect(self, nr_reply, lte_reply, shell, suffix): + self.stub('fake-at', f'''printf '%s\\n' "$*" >> "$STUBLOG/at-commands" +case "$*" in + *AT+CFUN?*) printf '+CFUN: 1\\nOK\\n' ;; + *AT+CEREG?*) printf '+CEREG: 2,1,"899C10","09C6D007",11\\nOK\\n' ;; + *AT+C5GREG?*) printf '+C5GREG: 2,1,"899C10","899C6D007",11\\nOK\\n' ;; + *AT+SPENGMD=0,6,6*) printf '%s\\nOK\\n' '{lte_reply}' ;; + *AT+SPENGMD=0,14,2*) printf '%s\\nOK\\n' '{nr_reply}' ;; + *AT+SPQ5GNCELLEX*) printf '+SPQ5GNCELLEX: 0,0,0,0,0,0,0,0,1,627264,687,-10830,-1100,330,0,0,0\\nOK\\n' ;; + *) printf 'OK\\n' ;; +esac''') + out = self.tmp / f'cache-{suffix}' + result = self.script( + shell, CELL, 'full', MU300_AT=self.stubs / 'fake-at', + MU300_DASH_DIR=out, MU300_DASH_POOL_DIR=self.tmp / f'pool-{suffix}', + MU300_DASH_IDENT_DIR=self.tmp / f'ident-{suffix}', + ) + self.assertEqual(result.returncode, 0, result.stderr) + return json.loads((out / 'cell.json').read_text()) + + def test_nr_band_from_modem_and_lte_csv_blocks(self): + for i, shell in enumerate(self.each_shell()): + (self.tmp / 'at-commands').unlink(missing_ok=True) + cell = self.collect(NR_REPLY, LTE_REPLY, shell, str(i)) + nr = [n for n in cell['neigh'] if n['rat'] == 'nr'] + lte = [n for n in cell['neigh'] if n['rat'] == 'lte'] + self.assertEqual(len(nr), 6) + self.assertEqual({n['band'] for n in nr}, {78}) + self.assertEqual(nr[0]['arfcn'], 627264) + self.assertEqual(nr[0]['sinr'], 3.4) + self.assertEqual([(n['band'], n['arfcn'], n['pci']) for n in lte], + [(3, 1650, 211), (45, 46600, 123)]) + self.assertEqual(lte[0]['rsrp'], -95.0) + commands = (self.tmp / 'at-commands').read_text() + self.assertIn('AT+SPENGMD=0,14,2', commands) + self.assertNotIn('AT+SPQ5GNCELLEX', commands) + + def test_nr_fallback_does_not_guess_overlapping_band(self): + for i, shell in enumerate(self.each_shell()): + cell = self.collect('ERROR', '', shell, f'fallback-{i}') + nr = [n for n in cell['neigh'] if n['rat'] == 'nr'] + self.assertEqual(len(nr), 1) + self.assertIsNone(nr[0]['band']) + self.assertEqual(nr[0]['band_candidates'], [77, 78]) + self.assertEqual(nr[0]['arfcn'], 627264) + + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/tests/test_led_settings.py b/tests/test_led_settings.py new file mode 100644 index 00000000..6a880b8e --- /dev/null +++ b/tests/test_led_settings.py @@ -0,0 +1,147 @@ +"""Physical F50 lamps keep independent, localized brightness settings.""" +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from helpers import TOP + + +LED = TOP / 'rootfs/overlay/opt/mu300/bin/led-status' +UI = TOP / 'openwrt/overlay/www/luci-static/resources/view/system/leds.js' +DEFAULTS = TOP / 'openwrt/overlay/etc/uci-defaults/90-mu300' + + +class LedSettings(unittest.TestCase): + def test_signal_and_wifi_brightness_are_independent_and_persistent(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + leds = base / 'leds' + for name in ('sc27xx:red', 'sc27xx:green', 'sc27xx:blue', 'keyboard-backlight'): + led = leds / name + led.mkdir(parents=True) + (led / 'brightness').write_text('0\n') + (led / 'trigger').write_text('none\n') + (led / 'max_brightness').write_text('255\n') + bindir = base / 'bin' + bindir.mkdir() + uci = bindir / 'uci' + uci.write_text('''#!/bin/sh +case "$3" in + system.mu300_leds.signal) echo "${TEST_SIGNAL_ENABLED:-1}" ;; + system.mu300_leds.wifi) echo "${TEST_WIFI_ENABLED:-1}" ;; + system.mu300_leds.signal_brightness) echo "${TEST_SIGNAL_BRIGHTNESS:-255}" ;; + system.mu300_leds.wifi_brightness) echo "${TEST_WIFI_BRIGHTNESS:-127}" ;; +esac +''') + uci.chmod(0o755) + device = bindir / 'mu300-device' + device.write_text('#!/bin/sh\necho f50\n') + device.chmod(0o755) + run_dir = base / 'run' + run_dir.mkdir() + env = dict(os.environ, PATH=f'{bindir}:{os.environ["PATH"]}', + MU300_LED_SYSFS_ROOT=str(leds), MU300_LED_RUN_DIR=str(run_dir), + TEST_SIGNAL_BRIGHTNESS='64', TEST_WIFI_BRIGHTNESS='32') + + def apply(state): + result = subprocess.run([str(LED), state], env=env, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + + def level(name): + return (leds / name / 'brightness').read_text().strip() + + apply('online-4g') + self.assertEqual(tuple(level('sc27xx:' + c) for c in ('red', 'green', 'blue')), + ('0', '0', '64')) + apply('wifi-on') + self.assertEqual(level('keyboard-backlight'), '32') + apply('online-5g') + self.assertEqual(tuple(level('sc27xx:' + c) for c in ('red', 'green', 'blue')), + ('0', '64', '0')) + self.assertEqual(level('keyboard-backlight'), '32') + env['TEST_SIGNAL_BRIGHTNESS'] = '96' + env['TEST_WIFI_BRIGHTNESS'] = '48' + apply('refresh') + self.assertEqual(level('sc27xx:green'), '96') + self.assertEqual(level('keyboard-backlight'), '48') + env['TEST_SIGNAL_ENABLED'] = '0' + env['TEST_WIFI_ENABLED'] = '0' + apply('refresh') + self.assertEqual(tuple(level('sc27xx:' + c) for c in ('red', 'green', 'blue')), + ('0', '0', '0')) + self.assertEqual(level('keyboard-backlight'), '0') + env['TEST_SIGNAL_ENABLED'] = '1' + env['TEST_WIFI_ENABLED'] = '1' + env['TEST_SIGNAL_BRIGHTNESS'] = '0' + env['TEST_WIFI_BRIGHTNESS'] = '255' + (leds / 'keyboard-backlight/max_brightness').write_text('100\n') + apply('refresh') + self.assertEqual(level('sc27xx:green'), '0') + self.assertEqual(level('keyboard-backlight'), '100') + env['TEST_SIGNAL_BRIGHTNESS'] = 'bad' + env['TEST_WIFI_BRIGHTNESS'] = '999' + (leds / 'keyboard-backlight/max_brightness').write_text('255\n') + apply('refresh') + self.assertEqual(level('sc27xx:green'), '255') + self.assertEqual(level('keyboard-backlight'), '127') + + def test_defaults_and_animations_use_brightness(self): + defaults = DEFAULTS.read_text(encoding='utf-8') + script = LED.read_text(encoding='utf-8') + self.assertIn("set system.mu300_leds.signal_brightness='255'", defaults) + self.assertIn("set system.mu300_leds.wifi_brightness='127'", defaults) + self.assertIn('set_rgb "$_r" "$_w" "$_b"', script) + self.assertIn('set_rgb 255 0 0; pause_us 120000', script) + + @unittest.skipUnless(shutil.which('node'), 'Node.js is needed for LuCI JS smoke tests') + def test_page_has_chinese_english_turkish_and_validated_controls(self): + harness = r''' +const fs = require('fs'); +const src = fs.readFileSync(process.argv[2], 'utf8'); +let lang = 'en'; +const L = { env: { get lang() { return lang; } } }; +const form = { NamedSection: {}, GridSection: {}, Flag: {}, Value: {}, ListValue: {} }; +form.Map = function() { + const map = { sections: [], section(_type, name, _id, title) { + const section = { name, title, options: [], option(_type, key, label, description) { + const option = { key, label, description, value() {} }; + this.options.push(option); return option; + } }; + this.sections.push(section); return section; + }, render() { return this; } }; + return map; +}; +const view = { extend: obj => obj }; +const rpc = { declare: () => () => ({}) }; +const page = new Function('view', 'uci', 'rpc', 'form', 'fs', 'L', 'document', 'navigator', '_', src)( + view, {}, rpc, form, {}, L, { documentElement: { lang: 'en' } }, { language: 'en' }, s => s); +for (const [locale, title, signal, wifi] of [ + ['en', 'LED Configuration', 'Signal lamp brightness', 'Wi-Fi lamp brightness'], + ['zh_cn', 'LED 配置', '信号灯亮度', 'Wi-Fi 灯亮度'], + ['tr_TR', 'LED yapılandırması', 'Sinyal ışığı parlaklığı', 'Wi-Fi ışığı parlaklığı'] +]) { + lang = locale; + const map = page.render([{}, []]); + if (map.sections[0].title !== (locale === 'en' ? 'Physical status lamps' : + locale.startsWith('zh') ? '物理状态灯' : 'Fiziksel durum ışıkları')) throw Error(locale + ': section'); + const options = map.sections[0].options; + const sig = options.find(o => o.key === 'signal_brightness'); + const wf = options.find(o => o.key === 'wifi_brightness'); + if (sig.label !== signal || wf.label !== wifi) throw Error(locale + ': brightness labels'); + if (sig.datatype !== 'range(0,255)' || wf.datatype !== 'range(0,255)') throw Error('fallback range'); + if (sig.default !== '255' || wf.default !== '127') throw Error('defaults'); + const actual = page.render([{ 'keyboard-backlight': { max_brightness: 127, triggers: [] } }, []]); + const realWifi = actual.sections[0].options.find(o => o.key === 'wifi_brightness'); + if (realWifi.datatype !== 'range(0,127)' || realWifi.default !== '127') throw Error('hardware maximum'); +} +''' + result = subprocess.run(['node', '-', str(UI)], input=harness, capture_output=True, + text=True, encoding='utf-8') + self.assertEqual(result.returncode, 0, result.stderr) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_mu300_i18n.py b/tests/test_mu300_i18n.py index 96c5d4f7..8be6f9c6 100644 --- a/tests/test_mu300_i18n.py +++ b/tests/test_mu300_i18n.py @@ -12,6 +12,7 @@ from helpers import TOP COMMON = TOP / 'openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js' HOME = TOP / 'openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/home.js' +FORWARD = TOP / 'openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/forward.js' PACKAGE = TOP / 'openwrt/luci-app-mu300' @@ -24,7 +25,12 @@ class DashboardI18n(unittest.TestCase): self.assertIn('$(CP) ./lmo/. $(1)/usr/lib/lua/luci/i18n/', makefile) self.assertNotIn('uci set luci.languages.zh_cn', makefile) self.assertIn('/etc/init.d/unisoc-modem-ui enable', makefile) - for name in ('home', 'at', 'locks', 'sms', 'settings', 'device'): + self.assertIn('/etc/init.d/unisoc-sms-forward enable', makefile) + self.assertIn('+msmtp', makefile) + self.assertIn('+curl', makefile) + self.assertTrue((PACKAGE / 'root/etc/init.d/unisoc-sms-forward').is_file()) + self.assertTrue((PACKAGE / 'root/usr/libexec/unisoc-modem/sms-forward').is_file()) + for name in ('home', 'at', 'locks', 'sms', 'forward', 'traffic', 'settings', 'device'): self.assertTrue((PACKAGE / f'htdocs/luci-static/resources/view/mu300/{name}.js').is_file()) def test_global_menu_catalogs_are_complete(self): @@ -148,7 +154,7 @@ if (M.translate('删除这条短信') !== '删除这条短信') throw Error('Chi def test_visible_chinese_literals_have_translations(self): literals = [] - for name in ('home', 'at', 'locks', 'sms', 'settings'): + for name in ('home', 'at', 'locks', 'sms', 'forward', 'traffic', 'settings'): source = (PACKAGE / f'htdocs/luci-static/resources/view/mu300/{name}.js').read_text(encoding='utf-8') for line in source.splitlines(): stripped = line.lstrip() @@ -166,6 +172,38 @@ for (const locale of ['en', 'tr']) { } ''' % json.dumps(literals, ensure_ascii=True)) + def test_forward_page_static_html_has_three_languages(self): + source = FORWARD.read_text(encoding='utf-8') + html = re.search(r'root\.innerHTML = `(.*?)`;', source, re.S) + self.assertIsNotNone(html) + visible = re.sub(r'|<[^>]+>', ' ', html.group(1), flags=re.S) + self.run_js(r''' +const visible = %s; +for (const locale of ['en', 'tr']) { + lang = locale; + const translated = M.translate(visible); + if (/[\u3400-\u9fff]/.test(translated)) + throw Error(locale + ': untranslated forward page: ' + + translated.match(/[\u3400-\u9fff]+/)[0]); +} +lang = 'zh'; +if (!M.translate(visible).includes('短信转发')) throw Error('Chinese source lost'); +''' % json.dumps(visible, ensure_ascii=True)) + + def test_traffic_page_static_html_has_three_languages(self): + source = (PACKAGE / 'htdocs/luci-static/resources/view/mu300/traffic.js').read_text(encoding='utf-8') + html = re.search(r'root\.innerHTML = `(.*?)`;', source, re.S) + self.assertIsNotNone(html) + visible = re.sub(r'|<[^>]+>', ' ', html.group(1), flags=re.S) + self.run_js(r''' +const visible = %s; +for (const locale of ['en', 'tr']) { + lang = locale; + if (/[\u3400-\u9fff]/.test(M.translate(visible))) + throw Error(locale + ': untranslated data-plan page'); +} +''' % json.dumps(visible, ensure_ascii=True)) + if __name__ == '__main__': unittest.main() diff --git a/tests/test_sms_capacity.py b/tests/test_sms_capacity.py new file mode 100644 index 00000000..2511455d --- /dev/null +++ b/tests/test_sms_capacity.py @@ -0,0 +1,294 @@ +"""SIM capacity is reported without AT on page refresh; SIM deletes must be honest.""" +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from helpers import TOP + + +SMS = TOP / 'rootfs/overlay/opt/mu300/bin/mu300-sms' +RPC = TOP / 'openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash' +UI = TOP / 'openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/sms.js' +I18N = TOP / 'openwrt/luci-app-mu300/htdocs/luci-static/resources/mu300/common.js' +SPOOL = TOP / 'rootfs/overlay/opt/mu300/bin/mu300-cmt-spool' +PDU_AWK = TOP / 'rootfs/overlay/opt/mu300/lib/sms-pdu.awk' + + +class SmsCapacity(unittest.TestCase): + def test_direct_pdu_is_persisted_and_imported_idempotently(self): + # SMS-DELIVER from 1234, GSM-7 "hello"; direct delivery must survive + # duplicate network attempts without producing duplicate inbox rows. + pdu = '00040481214300006201702143650005E8329BFD06' + with tempfile.TemporaryDirectory() as tmp: + pool = Path(tmp) / 'pool' + env = dict(os.environ, MU300_SMS_POOL=str(pool), MU300_SMS_PDU_AWK=str(PDU_AWK)) + spooled = subprocess.run([str(SPOOL)], input='+CMT: ,20\n' + pdu + '\n', + env=env, capture_output=True, text=True) + self.assertEqual(spooled.returncode, 0, spooled.stderr) + ready = list((pool / 'incoming').glob('*.ready')) + self.assertEqual(len(ready), 1) + self.assertEqual(ready[0].read_text().strip(), pdu) + self.assertEqual(ready[0].stat().st_mode & 0o077, 0) + for _ in range(2): + result = subprocess.run([str(SMS), 'import-pdu', str(ready[0])], env=env, + capture_output=True, text=True, encoding='utf-8') + self.assertEqual(result.returncode, 0, result.stderr) + messages = list((pool / 'msg').glob('[0-9]*')) + self.assertEqual(len(messages), 1) + headers, body = messages[0].read_text().split('\n\n', 1) + self.assertEqual(body, 'hello\n') + self.assertIn('source: direct\n', headers + '\n') + self.assertNotIn('multipart_ref:', headers) + self.assertIn('multipart_total: 1\n', headers + '\n') + self.assertIn('multipart_part: 1\n', headers + '\n') + + def test_receiver_scans_hidden_spool_and_acknowledges_after_import(self): + daemon = (TOP / 'rootfs/overlay/opt/mu300/bin/mu300-smsd').read_text() + process = daemon[daemon.index('process_spool() {'):daemon.index('sync_fallback() {')] + with tempfile.TemporaryDirectory() as tmp: + temp = Path(tmp) + pool = temp / 'pool' + env = dict(os.environ, MU300_SMS_POOL=str(pool), MU300_SMS_PDU_AWK=str(PDU_AWK), + SMS=str(SMS), SPOOL=str(pool / 'incoming'), TEST_POOL=str(pool), + TEST_ACK=str(temp / 'ack.log'), TEST_ACK_FAIL='1') + spooled = subprocess.run([str(SPOOL)], + input='+CMT: ,20\n00040481214300006201702143650005E8329BFD06\n', + env=env, capture_output=True, text=True, timeout=15) + self.assertEqual(spooled.returncode, 0, spooled.stderr) + ready = list((pool / 'incoming').glob('*.ready')) + self.assertEqual(len(ready), 1) + self.assertTrue(ready[0].name.startswith('.cmt.')) + code = ''' +mu300-at() { + [ -f "$TEST_POOL/msg/000001" ] || return 1 + printf '%s\\n' "$*" >> "$TEST_ACK" + [ "$TEST_ACK_FAIL" != 1 ] || { printf 'ERROR\\n'; return 1; } + printf 'OK\\n' +} +''' + process + '\nprocess_spool\n' + result = subprocess.run(['bash', '-c', code], env=env, capture_output=True, + text=True, timeout=15) + self.assertNotEqual(result.returncode, 0) + self.assertTrue(ready[0].exists(), 'failed modem ACK must retain the original PDU') + env['TEST_ACK_FAIL'] = '0' + result = subprocess.run(['bash', '-c', code], env=env, capture_output=True, + text=True, timeout=15) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((temp / 'ack.log').read_text(), '-t 5 AT+CNMA=1\n' * 2) + self.assertFalse(ready[0].exists()) + self.assertEqual((pool / 'next_id').read_text(), '1\n') + self.assertEqual((pool / 'msg/000001').read_text().split('\n\n', 1)[1], 'hello\n') + + def test_import_preserves_body_with_empty_ref_and_multipart_ref(self): + # UCS-2 avoids relying on a mock decoder and includes Chinese plus + # punctuation that must not be interpreted by the shell. + text = '中文 $(id) \\"quoted"' + payload = text.encode('utf-16-be').hex().upper() + with tempfile.TemporaryDirectory() as tmp: + temp = Path(tmp) + for multipart in (False, True): + ud = ('0500032A0201' if multipart else '') + payload + pdu = ('0044' if multipart else '0004') + '04812143000862017021436500' + pdu += f'{len(ud) // 2:02X}' + ud + raw = temp / 'input.pdu' + raw.write_text(pdu + '\n') + pool = temp / ('multi' if multipart else 'single') + env = dict(os.environ, MU300_SMS_POOL=str(pool), MU300_SMS_PDU_AWK=str(PDU_AWK), + LC_ALL='C.UTF-8') + result = subprocess.run([str(SMS), 'import-pdu', str(raw)], env=env, + capture_output=True, text=True, timeout=15) + self.assertEqual(result.returncode, 0, result.stderr) + headers, body = (pool / 'msg/000001').read_text().split('\n\n', 1) + self.assertEqual(body, text + '\n') + if multipart: + self.assertIn('multipart_ref: 42\n', headers + '\n') + self.assertIn('multipart_total: 2\n', headers + '\n') + else: + self.assertNotIn('multipart_ref:', headers) + self.assertIn('multipart_part: 1\n', headers + '\n') + + def test_unsupported_pdu_keeps_recoverable_local_original(self): + with tempfile.TemporaryDirectory() as tmp: + temp = Path(tmp) + raw = temp / 'unknown.pdu' + raw.write_text('00\n') + pool = temp / 'pool' + env = dict(os.environ, MU300_SMS_POOL=str(pool), MU300_SMS_PDU_AWK=str(PDU_AWK)) + result = subprocess.run([str(SMS), 'import-pdu', str(raw)], env=env, + capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + messages = list((pool / 'msg').glob('[0-9]*')) + self.assertEqual(len(messages), 1) + self.assertIn('Undecoded SMS PDU: 00', messages[0].read_text()) + + def test_direct_mode_never_switches_to_text_during_manual_sync_or_send(self): + sms = SMS.read_text(encoding='utf-8') + daemon = (TOP / 'rootfs/overlay/opt/mu300/bin/mu300-smsd').read_text(encoding='utf-8') + self.assertIn('if [ -f "$DIRECT_FLAG" ]; then\n cmd_archive_sim', sms) + send = sms.split('cmd_send() {', 1)[1].split('cmd_delete() {', 1)[0] + self.assertNotIn("at 'AT+CMGF=1'", send) + fallback = daemon.split('sync_fallback() {', 1)[1].split('signature() {', 1)[0] + self.assertNotIn('AT+CMGF=1', fallback) + self.assertNotIn('AT+CNMI=', fallback) + + def test_sim_original_is_deleted_only_after_verified_local_archive(self): + pdu = '00040481214300006201702143650005E8329BFD06' + with tempfile.TemporaryDirectory() as tmp: + temp = Path(tmp) + modem = temp / 'mu300-at' + modem.write_text('''#!/bin/sh +case "$3" in + 'AT+CPMS="SM"') printf '+CPMS: 1,50,0,0,0,0\\nOK\\n' ;; + 'AT+CMGF=0') printf 'OK\\n' ;; + 'AT+CMGL=4') printf '+CMGL: 3,0,,20\\n''' + pdu + '''\\nOK\\n' ;; + 'AT+CMGR=3') + if [ "$SMS_MOCK_BAD_READ" = 1 ]; then printf '+CMGR: 0,,20\\n00\\nOK\\n'; + else printf '+CMGR: 0,,20\\n''' + pdu + '''\\nOK\\n'; fi ;; + 'AT+CMGD=3') + printf '%s\\n' "$3" >> "$SMS_MOCK_LOG" + if [ "$SMS_MOCK_FAIL_DELETE" = 1 ]; then printf '+CMS ERROR: 500\\n'; else printf 'OK\\n'; fi ;; + *) printf 'ERROR\\n' ;; +esac +''', encoding='utf-8') + modem.chmod(0o755) + pool = temp / 'pool' + env = dict(os.environ, PATH=f'{tmp}:{os.environ["PATH"]}', + MU300_SMS_POOL=str(pool), MU300_SMS_PDU_AWK=str(PDU_AWK), + SMS_MOCK_LOG=str(temp / 'delete.log'), + SMS_MOCK_BAD_READ='1', SMS_MOCK_FAIL_DELETE='0') + def archive(): + return subprocess.run([str(SMS), 'archive-sim'], env=env, + capture_output=True, text=True, encoding='utf-8') + + self.assertNotEqual(archive().returncode, 0) + self.assertFalse((temp / 'delete.log').exists(), 'mismatched slot must not be deleted') + env['SMS_MOCK_BAD_READ'] = '0' + env['SMS_MOCK_FAIL_DELETE'] = '1' + self.assertNotEqual(archive().returncode, 0) + self.assertEqual(len(list((pool / 'archive').glob('*.pdu'))), 1) + self.assertEqual(len(list((pool / 'msg').glob('[0-9]*'))), 1) + self.assertIn('source: sim\n', (pool / 'msg/000001').read_text()) + env['SMS_MOCK_FAIL_DELETE'] = '0' + self.assertEqual(archive().returncode, 0) + self.assertEqual((temp / 'delete.log').read_text().splitlines(), + ['AT+CMGD=3', 'AT+CMGD=3']) + + def test_incomplete_sim_listing_never_deletes_any_slot(self): + with tempfile.TemporaryDirectory() as tmp: + temp = Path(tmp) + modem = temp / 'mu300-at' + modem.write_text('''#!/bin/sh +case "$3" in + 'AT+CPMS="SM"') printf '+CPMS: 2,50,0,0,0,0\\nOK\\n' ;; + 'AT+CMGF=0') printf 'OK\\n' ;; + 'AT+CMGL=4') printf '+CMGL: 3,0,,20\\n00040481214300006201702143650005E8329BFD06\\nOK\\n' ;; + 'AT+CMGD='*) printf '%s\\n' "$3" >> "$SMS_MOCK_LOG"; printf 'OK\\n' ;; + *) printf 'ERROR\\n' ;; +esac +''', encoding='utf-8') + modem.chmod(0o755) + log = temp / 'delete.log' + env = dict(os.environ, PATH=f'{tmp}:{os.environ["PATH"]}', + MU300_SMS_POOL=str(temp / 'pool'), SMS_MOCK_LOG=str(log)) + result = subprocess.run([str(SMS), 'archive-sim'], env=env, + capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(log.exists()) + + def test_manual_sim_delete_restores_direct_delivery_on_failure(self): + with tempfile.TemporaryDirectory() as tmp: + temp = Path(tmp) + pool = temp / 'pool' + raw = temp / 'direct.pdu' + raw.write_text('00040481214300006201702143650005E8329BFD06\n') + flag = temp / 'direct.flag' + flag.touch() + modem = temp / 'mu300-at' + modem.write_text('''#!/bin/sh +printf '%s\\n' "$3" >> "$SMS_MOCK_LOG" +case "$3" in + 'AT+CPMS="SM"') printf '+CPMS: 0,50,0,0,0,0\\nOK\\n' ;; + *) printf 'OK\\n' ;; +esac +''', encoding='utf-8') + modem.chmod(0o755) + log = temp / 'at.log' + env = dict(os.environ, PATH=f'{tmp}:{os.environ["PATH"]}', + MU300_SMS_POOL=str(pool), MU300_SMS_PDU_AWK=str(PDU_AWK), + MU300_SMS_DIRECT_FLAG=str(flag), SMS_MOCK_LOG=str(log)) + saved = subprocess.run([str(SMS), 'import-pdu', str(raw)], env=env, + capture_output=True, text=True) + self.assertEqual(saved.returncode, 0, saved.stderr) + result = subprocess.run([str(SMS), 'delete', '1', '--sim'], env=env, + capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertTrue((pool / 'msg/000001').exists()) + self.assertTrue(flag.exists()) + commands = log.read_text().splitlines() + self.assertEqual(commands[0], 'AT+CNMI=2,1,0,0,0') + self.assertEqual(commands[-2:], ['AT+CMGF=0', 'AT+CNMI=3,2,2,1,1']) + + def test_sim_delete_failure_is_not_downgraded_to_local_delete(self): + rpc = RPC.read_text(encoding='utf-8') + self.assertIn('if [ "$sim" = 1 ]; then\n out=$("$SMS" delete "$id" --sim 2>&1)', rpc) + self.assertIn('printf \'{"ok":0,"error":"%s"}', rpc) + + def test_capacity_warning_is_localized(self): + ui = UI.read_text(encoding='utf-8') + catalog = I18N.read_text(encoding='utf-8') + self.assertIn('st.sim_used >= st.sim_total', ui) + self.assertIn("'SIM 存储已满;自动归档尚未释放空间,请检查短信服务。':", catalog) + + def test_full_sim_keeps_local_copy_when_modem_refuses_delete(self): + with tempfile.TemporaryDirectory() as tmp: + temp = Path(tmp) + phone = '17674544422' + hex_phone = phone.encode().hex().upper() + modem = temp / 'mu300-at' + modem.write_text('''#!/bin/sh +case "$3" in + 'AT+CPMS="SM"') printf '+CPMS: 50,50,0,0,0,0\\nOK\\n' ;; + 'AT+CMGF=1') printf 'OK\\n' ;; + 'AT+CMGL="ALL"') printf '+CMGL: 3,"REC READ","''' + hex_phone + '''",,"26/10/07,12:00:00+08"\\nhello\\nOK\\n' ;; + 'AT+CMGD=3') + printf '%s\\n' "$3" >> "$SMS_MOCK_LOG" + if [ "$SMS_MOCK_FAIL_DELETE" = 1 ]; then printf '+CMS ERROR: 500\\n'; else printf 'OK\\n'; fi ;; + *) printf 'ERROR\\n' ;; +esac +''', encoding='utf-8') + modem.chmod(0o755) + env = dict(os.environ, PATH=f'{tmp}:{os.environ["PATH"]}', + MU300_SMS_POOL=str(temp / 'pool'), + MU300_SMS_STORE_CACHE=str(temp / 'store-cache'), + SMS_MOCK_LOG=str(temp / 'delete.log'), + SMS_MOCK_FAIL_DELETE='1') + def sms(*args): + return subprocess.run([str(SMS), *args], env=env, capture_output=True, + text=True, encoding='utf-8') + + synced = sms('sync') + self.assertEqual(synced.returncode, 0, synced.stderr) + self.assertEqual((temp / 'pool/storage').read_text().split()[:3], ['SM', '50', '50']) + msg = temp / 'pool/msg/000001' + self.assertTrue(msg.exists()) + self.assertIn('from: ' + phone, msg.read_text()) + self.assertIn('source: sim\n', msg.read_text()) + + refused = sms('delete', '1', '--sim') + self.assertNotEqual(refused.returncode, 0) + self.assertTrue(msg.exists(), 'a failed SIM delete must retain the local copy') + self.assertFalse((temp / 'pool/deleted').exists()) + + env['SMS_MOCK_FAIL_DELETE'] = '0' + deleted = sms('delete', '1', '--sim') + self.assertEqual(deleted.returncode, 0, deleted.stderr) + self.assertFalse(msg.exists()) + self.assertTrue((temp / 'pool/deleted').exists()) + self.assertEqual((temp / 'delete.log').read_text().splitlines(), + ['AT+CMGD=3', 'AT+CMGD=3']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_sms_forward_history.py b/tests/test_sms_forward_history.py new file mode 100644 index 00000000..e122b6e0 --- /dev/null +++ b/tests/test_sms_forward_history.py @@ -0,0 +1,130 @@ +"""History imports are not live SMS events, including on legacy adapters.""" +from datetime import datetime +import subprocess + +from helpers import ShellTest, TOP + + +FORWARD = TOP / 'openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/sms-forward' +SMS = TOP / 'rootfs/overlay/opt/mu300/bin/mu300-sms' +PDU = TOP / 'rootfs/overlay/opt/mu300/lib/sms-pdu.awk' + + +def epoch(iso): + return int(datetime.fromisoformat(iso).timestamp()) + + +class ForwardHistory(ShellTest): + def setUp(self): + super().setUp() + text = FORWARD.read_text() + self.code = '\n'.join([ + text[text.index('number() {'):text.index('bool() {')], + text[text.index('load_state() {'):text.index('save_config() {')], + text[text.index('write_result() {'):text.index('read_result() {')], + text[text.index('message_file() {'):text.index('template_strings() {')], + text[text.index('scts_epoch() {'):text.index('process_power() {')], + 'deliver() { printf "%s\\n" "$3" >> "$DELIVERIES"; DELIVER_RESULT=sent; }', + ]) + self.barrier = epoch('2026-10-07T12:00:00+08:00') + + def test_timestamp_offsets_and_calendar_independent_of_host_timezone(self): + cases = [ + ('26/10/07,12:34:56+32', '2026-10-07T12:34:56+08:00'), + ('26/10/07,12:34:56-14', '2026-10-07T12:34:56-03:30'), + ('26/10/07,00:00:00+23', '2026-10-07T00:00:00+05:45'), + ('00/02/29,00:00:00+00', '2000-02-29T00:00:00+00:00'), + ('28/02/29,23:59:59+56', '2028-02-29T23:59:59+14:00'), + ('2026-10-07 12:34:56+08:00', '2026-10-07T12:34:56+08:00'), + ('2026-10-07T12:34:56-03:30', '2026-10-07T12:34:56-03:30'), + ] + for shell in self.each_shell(): + for value, iso in cases: + for tz in ('UTC0', 'EST5', 'JST-9'): + result = self.sh(shell, self.code + '\nscts_epoch "$STAMP"', STAMP=value, TZ=tz) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(int(result.stdout), epoch(iso), (value, tz)) + + def test_unknown_or_invalid_sim_timestamps_are_not_guessed(self): + cases = ['', 'garbage', '26/10/07,12:00:00', '2026-10-07 12:00:00', + '26/02/29,12:00:00+32', '26/04/31,12:00:00+32', + '26/13/01,12:00:00+32', '26/10/00,12:00:00+32', + '26/10/07,24:00:00+32', '26/10/07,12:60:00+32', + '26/10/07,12:00:60+32', '26/10/07,12:00:00+99', + '2026-10-07 12:00:00+08:60', '26/10/07,12:00:00+32\n123'] + for shell in self.each_shell(): + for value in cases: + result = self.sh(shell, self.code + '\nscts_epoch "$STAMP"', STAMP=value) + self.assertNotEqual(result.returncode, 0, value) + + def test_live_delayed_delivery_and_sim_boundary(self): + for shell in self.each_shell(): + for source in ('sim', ''): + for stamp, expected in [('26/09/29,12:00:00+32', False), + ('26/10/07,11:59:59+32', False), + ('26/10/07,12:00:00+32', True), + ('26/10/07,12:00:01+32', True)]: + result = self.sh(shell, self.code + '\nsms_is_new "$SOURCE" "$STAMP" "$RECEIVED"', + SOURCE=source, STAMP=stamp, RECEIVED=self.barrier + 500, + since=self.barrier) + self.assertEqual(result.returncode == 0, expected) + # A direct SMS received now can have an old SMSC timestamp; do not + # suppress genuine delayed network delivery just because it is old. + result = self.sh(shell, self.code + '\nsms_is_new direct old "$RECEIVED"', + RECEIVED=self.barrier + 500, since=self.barrier) + self.assertEqual(result.returncode, 0) + result = self.sh(shell, self.code + '\nsms_is_new direct old "$RECEIVED"', + RECEIVED=self.barrier - 1, since=self.barrier) + self.assertNotEqual(result.returncode, 0) + + def test_mixed_batch_downtime_restart_blacklist_and_no_replay(self): + for index, shell in enumerate(self.each_shell()): + base = self.tmp / str(index) + pool = base / 'pool' + (pool / 'msg').mkdir(parents=True) + # Import all of these AFTER enabling. Old SIM history must not + # masquerade as new mail; new arrivals while worker is down must. + records = [ + ('', '26/09/29,12:00:00+32', 'ucs2', 'mt', 'old legacy'), + ('sim', '2026-09-29 12:00:00+08:00', 'pdu', 'mt', 'old PDU'), + ('sim', '26/10/07,12:00:01+32', 'ucs2', 'mt', 'new SIM'), + ('', '26/10/07,12:00:02+32', 'ucs2', 'mt', 'new legacy'), + ('direct', '26/09/29,12:00:00+32', 'pdu', 'mt', 'live delayed'), + ('sim', '26/10/07,12:00:01+32', 'ucs2', 'mt', 'BLOCKME'), + ('direct', '26/10/07,12:00:01+32', 'pdu', 'mo', 'outgoing'), + ('sim', 'unknown', 'pdu', 'mt', 'unknown SIM'), + ('sim', '26/10/07,12:00:01+32', 'raw-pdu', 'mt', 'undecoded SIM'), + ] + for num, (source, stamp, coding, direction, body) in enumerate(records, 1): + (pool / 'msg' / f'{num:06d}').write_text( + f'dir: {direction}\nfrom: 10010\nsource: {source}\nscts: {stamp}\n' + f'received: {self.barrier + 500}\ncoding: {coding}\n\n{body}\n') + (pool / 'next_id').write_text(f'{len(records)}\n') + state = base / 'state' + state.write_text(f'0|{self.barrier}|-1|none\n') + env = dict(BASE=base, POOL=pool, STATE=state, RESULT=base / 'result', + DELIVERIES=base / 'sent', enabled=1, power_last_result='idle', + blacklist_phone='', blacklist_keywords='BLOCKME') + run = self.code + '\nload_state\nfor pass in 1 2 3 4 5 6 7 8 9 10; do process_sms; done' + for _ in range(2): # restart: use saved cursor, not an in-memory flag + result = self.sh(shell, run, **env) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((base / 'sent').read_text().splitlines(), + ['new SIM', 'new legacy', 'live delayed']) + self.assertEqual(state.read_text().split('|')[0], '9') + + def test_pdu_import_marks_source_and_preserves_utc_offset(self): + # Known SMS-DELIVER with +08:00 (0x23), -03:30 (0x49), +05:45 (0x32). + for n, (tzbyte, suffix) in enumerate([('23', '+08:00'), ('49', '-03:30'), ('32', '+05:45')]): + raw = self.tmp / f'input{n}.pdu' + raw.write_text('0004048121430000620170214365' + tzbyte + '05E8329BFD06\n') + for source in ('sim', 'direct'): + pool = self.tmp / f'pool{n}-{source}' + args = [str(SMS), 'import-pdu', str(raw)] + (['sim'] if source == 'sim' else []) + result = subprocess.run(args, env=self.env(MU300_SMS_POOL=pool, MU300_SMS_PDU_AWK=PDU), + capture_output=True, text=True, timeout=30) + self.assertEqual(result.returncode, 0, result.stderr) + headers, body = (pool / 'msg/000001').read_text().split('\n\n', 1) + self.assertIn(f'source: {source}\n', headers + '\n') + self.assertIn(f'scts: 2026-10-07 12:34:56{suffix}\n', headers + '\n') + self.assertEqual(body, 'hello\n') diff --git a/tests/test_sms_forward_templates.py b/tests/test_sms_forward_templates.py new file mode 100644 index 00000000..05971261 --- /dev/null +++ b/tests/test_sms_forward_templates.py @@ -0,0 +1,71 @@ +"""Forwarding localizes generated text without modifying received SMS data.""" +from email.header import decode_header +import shutil + +from helpers import ShellTest, TOP + + +FORWARD = TOP / 'openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/sms-forward' + + +class ForwardTemplates(ShellTest): + def setUp(self): + super().setUp() + source = FORWARD.read_text(encoding='utf-8') + self.code = "NL='\n'\n" + source[source.index('template_strings() {'):source.index('sms_units() {')] + + def test_sms_body_and_sender_are_preserved_in_every_language(self): + body = '验证码 123456\nİstanbul şifre: 654321\n$(reboot); "quoted" \\path' + sender = '+8613800000000' + prefixes = {'zh': '短信来自', 'en': 'SMS from', 'tr': 'SMS gönderen:'} + for shell in self.each_shell(): + for lang, prefix in prefixes.items(): + result = self.sh(shell, self.code + '\nformat_message sms "$SENDER" "$BODY"\nprintf "%s" "$_content"', + template_language=lang, SENDER=sender, BODY=body) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, f'{prefix} {sender}\n{body}') + + def test_test_message_and_rfc2047_subject_round_trip(self): + if not shutil.which('openssl'): + self.skipTest('openssl is needed for encoded email headers') + expected = { + 'zh': ('MU300 转发测试', 'MU300 短信转发测试'), + 'en': ('MU300 forwarding test', 'MU300 SMS forwarding test'), + 'tr': ('MU300 yönlendirme testi', 'MU300 SMS yönlendirme testi'), + } + for shell in self.each_shell(): + for lang, (subject, body) in expected.items(): + result = self.sh(shell, self.code + '\nformat_message test NMS ""\n' + 'mime_subject "$_subject"\nprintf "\\n%s" "$_content"', template_language=lang) + self.assertEqual(result.returncode, 0, result.stderr) + header, text = result.stdout.split('\n', 1) + self.assertTrue(header.isascii()) + self.assertLessEqual(len(header), 75) + decoded, charset = decode_header(header)[0] + self.assertEqual(decoded.decode(charset), subject) + self.assertEqual(text, body) + + def test_power_states_and_device_labels_are_localized(self): + # Shell functions also override ash's built-in applet lookup. + telemetry = '\ncat() { printf "%s" F50; }\ncut() { printf "%s" 1234; }\nsed() { printf "%s" OpenWrt; }\n' + expected = { + 'zh': ('充电状态', '当前电量', '电量提醒', '设备', '固件', '运行时间', '秒', + ['充电中', '放电中', '未充电', '已充满']), + 'en': ('Charging status', 'Battery level', 'Battery alert', 'Device', 'Firmware', 'Uptime', 'seconds', + ['Charging', 'Discharging', 'Not charging', 'Full']), + 'tr': ('Şarj durumu', 'Pil seviyesi', 'Pil uyarısı', 'Cihaz', 'Yazılım', 'Çalışma süresi', 'saniye', + ['Şarj oluyor', 'Pil kullanılıyor', 'Şarj olmuyor', 'Dolu']), + } + for shell in self.each_shell(): + for lang, words in expected.items(): + charge, level, threshold, device, firmware, uptime, seconds, states = words + for status, translated in zip(['Charging', 'Discharging', 'Not charging', 'Full'], states): + result = self.sh(shell, self.code + '\npower_message "$STATUS" 40 40 "$STATUS"', + template_language=lang, STATUS=status) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, f'{threshold}: 40%\n{level}: 40%\n{charge}: {translated}') + result = self.sh(shell, self.code + telemetry + '\ntemplate_strings\ndevice_info', + template_language=lang, nickname='我的设备 / İstanbul') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, f'{device}: F50 (我的设备 / İstanbul)\n' + f'{firmware}: OpenWrt\n{uptime}: 1234 {seconds}') diff --git a/tests/test_static.py b/tests/test_static.py index dd27aa50..bf4c9bcd 100644 --- a/tests/test_static.py +++ b/tests/test_static.py @@ -120,7 +120,8 @@ class Rules(unittest.TestCase): self.assertIn('7.2) DEFAULT_UO=$TOP/upstream/out-7.2', builder) self.assertIn('bootdev=/dev/block/by-name/boot_$linux_slot', customize) self.assertIn('case $slot in a) linux_slot=b ;; b) linux_slot=a', customize) - self.assertIn('--no-reboot', customize) + worker = (TOP / 'tools' / 'tf-install-worker.sh').read_text() + self.assertIn('--no-reboot', worker) self.assertIn('lazy_itable_init=1,lazy_journal_init=1,nodiscard', (TOP / 'tools' / 'android-install.sh').read_text()) self.assertIn("t = t.replace(old, '')", port) @@ -147,6 +148,22 @@ class Rules(unittest.TestCase): self.assertIn('Aurora theme is not the LuCI default', rootfs) self.assertIn('./www/luci-static/aurora/main.css', builder) self.assertIn('built rootfs does not enable Aurora by default', builder) + self.assertIn('apk add --allow-untrusted /in/luci-app-aurora-config.apk', rootfs) + self.assertIn('Aurora config APK checksum mismatch', rootfs) + for path in ('www/luci-static/resources/view/aurora/studio.js', + 'www/luci-static/resources/view/aurora/marketplace.js', + 'usr/share/luci/menu.d/luci-app-aurora.json', + 'usr/share/rpcd/acl.d/luci-app-aurora.json', + 'usr/lib/lua/luci/i18n/aurora-config.zh-cn.lmo', + 'usr/lib/lua/luci/i18n/aurora-config.tr.lmo'): + self.assertIn(path, rootfs) + self.assertIn('./' + path, builder) + pins = (TOP / 'openwrt' / 'aurora-config-packages.sha256').read_text().splitlines() + self.assertEqual(len(pins), 3) + for pin in pins: + checksum, name = pin.split() + self.assertRegex(checksum, r'^[0-9a-f]{64}$') + self.assertIn(name, rootfs) def test_every_device_has_its_files(self): # a device the installers know needs its module order; its modules come from kernel/build-.sh diff --git a/tests/test_tf_reliability.py b/tests/test_tf_reliability.py new file mode 100644 index 00000000..1d9db49c --- /dev/null +++ b/tests/test_tf_reliability.py @@ -0,0 +1,340 @@ +"""Offline fault injection: regular files/mocks only, never a physical disk.""" +import hashlib +import importlib.util +import io +import os +from pathlib import Path +import shutil +import subprocess +import tarfile +import tempfile +import time +import unittest + +from helpers import TOP + +TOOLS = TOP / 'tools' +BB = shutil.which('busybox') + + +def run_shell(code, *args, env=None, timeout=15): + return subprocess.run(['sh', '-c', code, 'test', *map(str, args)], + env=env, capture_output=True, text=True, timeout=timeout) + + +class StoragePrimitives(unittest.TestCase): + def test_only_exited_tasks_without_namespace_may_be_skipped(self): + for state, namespace, gone in [('Z', False, True), ('X', False, True), + ('S', False, False), ('R', False, False), ('Z', True, False)]: + with self.subTest(state=state, namespace=namespace), tempfile.TemporaryDirectory() as tmp: + proc = Path(tmp) + (proc / 'mountinfo').touch() + (proc / 'status').write_text(f'State:\t{state} (test)\n') + (proc / 'ns').mkdir() + if namespace: (proc / 'ns/mnt').symlink_to('mnt:[123]') + r = run_shell('. "$1"; tf_namespace_gone "$2"', TOOLS / 'tf-storage.sh', proc) + self.assertEqual(r.returncode == 0, gone, r.stdout + r.stderr) + + def test_alias_mounts_matched_by_devnum_not_path(self): + with tempfile.TemporaryDirectory() as tmp: + mounts = Path(tmp) / 'mountinfo' + mounts.write_text('31 1 179:33 / /mnt/media_rw/CARD rw - ext4 /dev/block/vold/public:179,33 rw\n' + '32 1 8:1 / /mnt/OTHER rw - vfat /dev/block/sda1 rw\n' + '33 1 179:33 /sub /storage/CARD rw - ext4 /dev/alias rw\n') + r = run_shell('. "$1"; tf_mounts_for_ids " 179:33" "$2"', TOOLS / 'tf-storage.sh', mounts) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stdout.splitlines(), ['31 /mnt/media_rw/CARD', '33 /storage/CARD']) + + def test_aligned_read_rejects_short_or_failed_read(self): + for sectors, length, fail, success in [(8, 4096, False, True), (7, 4096, False, False), + (8, 4095, False, False), (8, 4096, True, False)]: + with self.subTest(sectors=sectors, length=length, fail=fail), tempfile.TemporaryDirectory() as tmp: + disk = Path(tmp) / 'disk' + disk.write_bytes(b'x' * length) + code = '''. "$1" +T=$2 +blockdev() { echo "$SECTORS"; } +dd() { [ "$FAIL" = 0 ] || return 1; command dd "$@"; } +tf_read_super "$3" +''' + r = run_shell(code, TOOLS / 'tf-storage.sh', tmp, disk, + env=dict(os.environ, SECTORS=str(sectors), FAIL=str(int(fail)))) + self.assertEqual(r.returncode == 0, success, r.stdout + r.stderr) + if sectors < 8: + self.assertFalse((Path(tmp) / 'tf-super').exists()) + + def test_capacity_including_128_gib_without_size_cap(self): + for sectors, kib, good in [(268435456, 600000, True), (1024, 600000, False), + (-1, 1, False), (0, 1, False)]: + r = run_shell('. "$1"; tf_capacity "$2" "$3" 20000', TOOLS / 'tf-storage.sh', sectors, kib) + self.assertEqual(r.returncode == 0, good) + + def test_release_targets_only_selected_volume_and_refuses_namespace_residue(self): + original = (TOOLS / 'tf-storage.sh').read_text() + cases = [('mounted', 'unmounted', True), ('mounted_ro', 'unmounted', True), + ('mounted', 'unmountable', True), ('unmounted', 'unmounted', True), + ('unmountable', 'unmountable', True), ('mounted', 'mounted', False), + ('checking', 'checking', False), ('ejecting', 'ejecting', False), + ('removed', 'removed', False), ('formatting', 'formatting', False), + ('unknown', 'unknown', False)] + for before, after, safe, residue in [(b, a, s, r) for b, a, s in cases for r in (False, True)]: + with self.subTest(before=before, after=after, residue=residue), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for name, text in [('sys/mmcblk1/dev', '179:32'), ('sys/mmcblk1p1/dev', '179:33'), + ('sys/mmcblk1p2/dev', '179:34'), ('proc/self/mountinfo', ''), + ('proc/42/mountinfo', '30 1 179:33 / /stale rw - ext4 /dev/alias rw\n' if residue else '')]: + p = root / name + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(text) + script = original.replace('/sys/class/block/', str(root / 'sys') + '/') + script = script.replace('/proc/self/mountinfo', str(root / 'proc/self/mountinfo')) + script = script.replace('/proc/[0-9]*/mountinfo', str(root / 'proc') + '/[0-9]*/mountinfo') + path = root / 'storage.sh'; path.write_text(script) + code = '''. "$1" +T=$2 +say_i18n() { echo "$2"; } +readlink() { case "$1" in -f) echo "$2";; *) echo same-namespace;; esac; } +sleep() { :; } +sm() { + if [ "$1" = unmount ]; then echo "$2" >> "$T/unmounts"; touch "$T/released"; return 0; fi + echo 'public:8,1 mounted OTHER' + echo 'public:179,34 mounted OTHER_PARTITION' + if [ -f "$T/released" ]; then echo "public:179,33 $AFTER CARD"; else echo "public:179,33 $BEFORE CARD"; fi +} +tf_release /dev/block/mmcblk1p1 +''' + r = run_shell(code, path, root, env=dict(os.environ, BEFORE=before, AFTER=after)) + self.assertEqual(r.returncode == 0, safe and not residue, r.stdout + r.stderr) + if before in ('mounted', 'mounted_ro'): + self.assertEqual((root / 'unmounts').read_text(), 'public:179,33\n') + else: + self.assertFalse((root / 'unmounts').exists()) + + +class PayloadManifest(unittest.TestCase): + def test_metadata_hashes_requirements_and_unsafe_paths(self): + spec = importlib.util.spec_from_file_location('tf_manifest', TOOLS / 'tf-payload-manifest.py') + module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module) + for unsafe in (False, True): + with self.subTest(unsafe=unsafe), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / 'boot-linux.img').write_bytes(b'boot') + with tarfile.open(root / 'mu300-openwrt.tar.gz', 'w:gz') as archive: + for name in ('./bin/busybox', './sbin/procd', './sbin/init', './etc/uci-defaults/90-mu300', './etc/init.d/mu300-vendor'): + m = tarfile.TarInfo(name); m.size = 4 + archive.addfile(m, io.BytesIO(b'test')) + if unsafe: + m = tarfile.TarInfo('../escape'); archive.addfile(m) + if unsafe: + with self.assertRaises(ValueError): module.manifest(root) + continue + module.manifest(root) + kib, inodes = map(int, (root / 'rootfs.requirements').read_text().split()) + self.assertGreater(kib, 262144) + self.assertGreater(inodes, 16384) + for line in (root / 'payload.sha256').read_text().splitlines(): + digest, name = line.split() + self.assertEqual(digest, hashlib.sha256((root / name).read_bytes()).hexdigest()) + + def test_existing_built_rootfs_is_compatible(self): + rootfs = TOP / 'openwrt/mu300-openwrt-tf-7.2-rootfs.tar.gz' + if not rootfs.exists(): self.skipTest('no local built rootfs') + with tempfile.TemporaryDirectory() as tmp: + stage = Path(tmp) + (stage / 'mu300-openwrt.tar.gz').symlink_to(rootfs) + (stage / 'boot-linux.img').write_bytes(b'test-boot') + r = subprocess.run(['python3', str(TOOLS / 'tf-payload-manifest.py'), tmp], + capture_output=True, text=True, timeout=30) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + +@unittest.skipUnless(shutil.which('mke2fs') and shutil.which('dumpe2fs'), 'e2fsprogs required') +class SparseFormat(unittest.TestCase): + def test_full_capacity_512_mib_and_128_gib(self): + # A regular sparse file under the private temporary directory, never + # a loop device or mount. Verifies real ext4 geometry and inode count. + for size in (512 * 1024**2, 128 * 1024**3): + with self.subTest(size=size), tempfile.TemporaryDirectory() as tmp: + disk = Path(tmp) / 'card.img' + with disk.open('wb') as stream: stream.truncate(size) + args = ['mke2fs', '-t', 'ext4', '-F', '-b', '4096', '-m', '0', '-i', '1048576'] + if size // 1048576 < 21024: args += ['-N', '21024'] + r = subprocess.run(args + ['-E', 'lazy_itable_init=1,lazy_journal_init=1,nodiscard', '-L', 'mu300sd', str(disk)], + capture_output=True, text=True, timeout=30) + self.assertEqual(r.returncode, 0, r.stderr) + r = subprocess.run(['dumpe2fs', '-h', str(disk)], env=dict(os.environ, LC_ALL='C'), + capture_output=True, text=True, check=True, timeout=10) + fields = dict(line.split(':', 1) for line in r.stdout.splitlines() if ':' in line) + self.assertEqual(int(fields['Block count']) * int(fields['Block size']), size) + self.assertGreaterEqual(int(fields['Inode count']), 21024) + self.assertEqual(fields['Filesystem volume name'].strip(), 'mu300sd') + + +@unittest.skipUnless(BB, 'BusyBox required') +class BoundedStages(unittest.TestCase): + def test_corrupt_payload_fails_preflight_before_storage_checks(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + shutil.copy(TOOLS / 'tf-storage.sh', root / 'tf-storage.sh') + (root / 'mu300-install.env').write_text('SD_MODE=1\n') + good = b'original-payload' + (root / 'mu300-openwrt.tar.gz').write_bytes(b'corrupted-payload') + (root / 'payload.sha256').write_text(hashlib.sha256(good).hexdigest() + ' mu300-openwrt.tar.gz\n') + r = subprocess.run([BB, 'sh', str(TOOLS / 'tf-install-worker.sh'), '--preflight'], + env=dict(os.environ, MU300_PAYLOAD_DIR=tmp, MU300_INSTALL_TMP=tmp, + MU300_BUSYBOX=BB), capture_output=True, text=True, timeout=10) + self.assertNotEqual(r.returncode, 0) + self.assertIn('FAILED', r.stdout + r.stderr) + # SD_DEV and BOOTDEV are deliberately unset. Reaching any device + # check would produce a nounset failure instead of the checksum error. + self.assertNotIn('parameter not set', r.stderr) + + def test_success_failure_and_timeout(self): + for command, status in [('echo stage-complete', 0), ('echo injected-failure; exit 7', 1), ('sleep 30', 124)]: + with self.subTest(command=command), tempfile.TemporaryDirectory() as tmp: + start = time.monotonic() + r = subprocess.run([BB, 'sh', str(TOOLS / 'tf-stage.sh'), 'test', '2', 'sh', '-c', command], + env=dict(os.environ, MU300_BUSYBOX=BB, MU300_TF_STATE=tmp), + capture_output=True, text=True, timeout=10) + self.assertEqual(r.returncode, status, r.stdout + r.stderr) + self.assertLess(time.monotonic() - start, 8) + self.assertEqual((Path(tmp) / 'reboot-required').exists(), status == 124) + + def test_worker_gates_boot_and_misc_and_blocks_retry(self): + stages = ['preflight', 'vendor-preflight', 'staging-space', 'rootfs', 'boot-write', 'boot-readback', 'arm-slot'] + source = (TOOLS / 'tf-install-worker.sh').read_text() + for fail in stages + ['none']: + with self.subTest(fail=fail), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + # Replace only command execution with a recorded fault; retain + # real orchestration, set -e, boot-id lock and log allocation. + shim = '''tf_step() { echo "$1" >> "$T/stages"; [ "$1" != "$FAIL" ]; } +tf_die() { echo "$1"; return 1; } +''' + worker = root / 'worker.sh' + worker.write_text(source.replace('. "$P/tf-storage.sh"', shim)) + env = dict(os.environ, MU300_BUSYBOX=BB, MU300_PAYLOAD_DIR=tmp, + MU300_INSTALL_TMP=tmp, FAIL=fail) + r = subprocess.run([BB, 'sh', str(worker)], env=env, capture_output=True, text=True, timeout=10) + self.assertEqual(r.returncode == 0, fail == 'none', r.stdout + r.stderr) + expected = stages if fail == 'none' else stages[:stages.index(fail) + 1] + self.assertEqual((root / 'stages').read_text().splitlines(), expected) + if fail != 'none': + retry = subprocess.run([BB, 'sh', str(worker)], env=env, capture_output=True, text=True, timeout=10) + self.assertNotEqual(retry.returncode, 0) + self.assertEqual((root / 'stages').read_text().splitlines(), expected) + + +class InitBounds(unittest.TestCase): + def test_issue65_boundary_never_probes(self): + source = (TOP / 'boot/init').read_text() + functions = source[source.index('root_region_valid()'):source.index('# A TF-only image')] + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + p = root / 'mmcblk0p1'; p.mkdir() + (root / 'size').write_text('61079552') + (p / 'start').write_text('2048') + (p / 'size').write_text(str(61075456 - 2048)) + functions = functions.replace('/sys/block/mmcblk0', str(root)) + for offset, good in [(31272730624, False), (27762098176, False), (61075456 * 512, True), (-1, False)]: + r = run_shell(functions + '\nroot_region_valid "$1"', offset) + self.assertEqual(r.returncode == 0, good, r.stdout + r.stderr) + # No dd/losetup can execute for the exact reported out-of-disk offset. + r = run_shell(functions + ''' +dd() { echo UNEXPECTED_IO; return 1; } +losetup() { echo UNEXPECTED_IO; return 1; } +is_mu300root 31272730624 +''') + self.assertNotEqual(r.returncode, 0) + self.assertNotIn('UNEXPECTED_IO', r.stdout) + + def test_tf_marker_suppresses_emmc_fallback(self): + source = (TOP / 'boot/init').read_text() + segment = source[source.index('internal_root='):source.index('mkdir -p /newroot')] + for target, should_probe in [('sd', False), ('', True)]: + code = '''root_target=$1; root_mounted=0; sd_root=; ROOT_OFFSET=0 +log() { :; } +find_root_offset() { echo PROBED >&2; return 1; } +''' + segment + r = run_shell(code, target) + self.assertEqual('PROBED' in r.stderr, should_probe) + + +class RootfsTransaction(unittest.TestCase): + def test_real_extract_and_finalization_fail_closed(self): + # Only block-device/vold/mount/mkfs calls are mocked. Run the actual + # tar extraction, .new publication, checksums and success-marker logic. + for fault in ('none', 'extract', 'unmount', 'checksum'): + with self.subTest(fault=fault), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); payload = root / 'payload'; payload.mkdir() + fakebin = root / 'bin'; fakebin.mkdir() + trace = root / 'trace' + def stub(name, body): + p = fakebin / name + p.write_text('#!/bin/sh\n' + body + '\n'); p.chmod(0o755) + return p + stub('mount', 'echo mount >> "$TRACE"') + stub('umount', 'echo umount >> "$TRACE"; [ "$FAULT" != unmount ]') + stub('df', 'echo "Filesystem 1K-blocks Used Available Use% Mounted"; echo "fixture 9999999 1 9999998 1% /"') + stub('blockdev', 'echo 268435456') + mkfs = stub('mke2fs', 'echo format >> "$TRACE"') + disk = root / 'card' + sb = bytearray(4096); sb[1080:1082] = bytes.fromhex('53ef'); sb[1144:1151] = b'mu300sd' + disk.write_bytes(sb) + (payload / 'mu300-install.env').write_text(f'''SD_MODE=1 +SD_DEV={disk} +FORMAT=1 +OSES=openwrt +WIPE_LEGACY=0 +UPDATE=0 +BOOT_OS=openwrt +DEFAULT_LINUX=1 +BOOT_ATTEMPTS=5 +IMPORT_HOTSPOT=0 +KERNEL=7.2 +PWHASH='' +''') + (payload / 'rootfs.requirements').write_text('500000 20000\n') + files = {'sbin/init': b'init', 'sbin/procd': b'procd', 'bin/busybox': b'busybox', + 'etc/init.d/mu300-vendor': b'vendor', 'etc/config/network': b'network', + 'opt/mu300/android/dev-properties/stale': b'build-device'} + vendor = root / 'vendor'; vf = vendor / 'opt/mu300/android/dev-properties/current' + vf.parent.mkdir(parents=True); vf.write_bytes(b'current-device') + (root / 'vendor.sha256').write_text(hashlib.sha256(vf.read_bytes()).hexdigest() + + ' ./opt/mu300/android/dev-properties/current\n') + with tarfile.open(payload / 'mu300-openwrt.tar.gz', 'w:gz') as archive: + for name, data in files.items(): + m = tarfile.TarInfo(name); m.mode = 0o755; m.size = len(data) + archive.addfile(m, io.BytesIO(data)) + if fault == 'extract': + (payload / 'mu300-openwrt.tar.gz').write_bytes(b'not a gzip') + digest = hashlib.sha256(files['sbin/procd']).hexdigest() + if fault == 'checksum': digest = '0' * 64 + (payload / 'rootfs-critical.sha256').write_text(f'{digest} sbin/procd\n') + shutil.copy(TOOLS / 'tf-storage.sh', payload / 'tf-storage.sh') + code = (TOOLS / 'android-install.sh').read_text() + code = code.replace('[ -b "$R" ]', '[ -f "$R" ]') + code = code.replace('tf_release "$R"', 'echo release >> "$TRACE"') + code = code.replace('/system/bin/mke2fs', str(mkfs)) + script = root / 'installer.sh'; script.write_text(code) + env = dict(os.environ, MU300_INSTALL_TMP=tmp, MU300_PAYLOAD_DIR=str(payload), + MU300_TF_STATE=tmp, MU300_KEEP_PAYLOAD='1', TRACE=str(trace), FAULT=fault, + MU300_PREPARED_VENDOR=str(vendor), + PATH=str(fakebin) + os.pathsep + os.environ['PATH']) + r = subprocess.run(['sh', str(script)], env=env, capture_output=True, text=True, timeout=10) + self.assertEqual(r.returncode == 0, fault == 'none', r.stdout + r.stderr) + self.assertEqual('MU300-INSTALL-OK' in r.stdout, fault == 'none', r.stdout) + events = trace.read_text().splitlines() + if fault == 'none': + self.assertEqual(events, ['release', 'format', 'mount', 'umount', 'mount', 'umount']) + self.assertTrue((root / 'mu300root/openwrt/sbin/procd').exists()) + self.assertFalse((root / 'mu300root/openwrt.new').exists()) + self.assertFalse((root / 'mu300root/openwrt/opt/mu300/android/dev-properties/stale').exists()) + self.assertTrue((root / 'mu300root/openwrt/opt/mu300/android/dev-properties/current').exists()) + elif fault in ('extract', 'checksum'): + self.assertNotIn('umount', events) # no error-path global sync/unmount into a bad card + self.assertFalse((root / 'mu300root/openwrt').exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_usb_management.py b/tests/test_usb_management.py index 05663a70..275a6a8d 100644 --- a/tests/test_usb_management.py +++ b/tests/test_usb_management.py @@ -218,7 +218,7 @@ class USBIntegration(unittest.TestCase): self.assertLess(init.index('stage=sd-root dev='), init.index('[ "$root_mounted" = 1 ] && read_usb_boot_policy\nsetup_usb_gadget')) self.assertLess(init.index('[ "$root_mounted" = 1 ] && read_usb_boot_policy\nsetup_usb_gadget'), - init.index('if [ -z "$sd_root" ]; then')) + init.index('if [ "$root_mounted" = 0 ] && [ "$root_target" != sd ]; then')) self.assertIn('/disk/openwrt/etc/unisoc-modem/usb-boot.conf', init) self.assertIn('/run/unisoc-usb-net-applied', init) diff --git a/tests/traffic_core.uc b/tests/traffic_core.uc new file mode 100644 index 00000000..2c826008 --- /dev/null +++ b/tests/traffic_core.uc @@ -0,0 +1,59 @@ +// Run: TZ=UTC0 ucode -L openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem tests/traffic_core.uc +import * as c from 'traffic-core'; +let checks = 0; +function check(value, label) { if (!value) die('FAIL: ' + label + '\n'); checks++; } +function stamp(y, m, d, h, min, sec) { + return timelocal({ year:y, mon:m, mday:d, hour:h ?? 0, min:min ?? 0, sec:sec ?? 0, isdst:-1 }); +} +function sample(rx, tx, boot, idx) { return { rx:rx, tx:tx, boot:boot || 'A', ifindex:idx || 3, device:'cell0' }; } +let now = stamp(2026, 10, 7), db = c.fresh(now); +c.advance(db, sample(1000, 500), now); +check(c.status(db, now).today_used == 0, 'activation baseline'); +c.advance(db, sample(1100, 550), now + 10); +c.advance(db, sample(1100, 550), now + 20); +check(c.status(db, now + 20).today_used == 150, 'delta and duplicate sample'); +c.advance(db, sample(5, 2), now + 30); +check(c.status(db, now + 30).today_used == 157, 'counter reset'); +c.advance(db, null, now + 40); +c.advance(db, sample(10, 4), now + 50); +check(c.status(db, now + 50).today_used == 164, 'temporary missing device'); +c.advance(db, sample(20, 10, 'B'), now + 60); +check(c.status(db, now + 60).today_used == 194, 'reboot current counters'); +c.advance(db, sample(8, 3, 'B', 4), now + 70); +check(c.status(db, now + 70).today_used == 205, 'recreated device'); +let cloned = json(sprintf('%J', db)); +c.advance(cloned, sample(10, 4, 'B', 4), now + 80); +check(c.status(cloned, now + 80).today_used == 208, 'persistent round trip'); + +now = stamp(2026, 1, 31, 23, 59, 55); db = c.fresh(now); +c.advance(db, sample(0, 0), now); +c.advance(db, sample(1000, 200), now + 10); +check(db.days['2026-01-31'].rx == 500 && db.days['2026-02-01'].rx == 500, 'midnight split'); +check(c.status(db, now + 10).month_used == 600, 'natural month rollover'); +check(c.status(db, now + 10).cycle_used == 600, 'default cycle rollover'); +let range = c.cycle(stamp(2026, 2, 28), 31); +check(range.start == '2026-02-28' && range.end == '2026-03-31', 'short month clamp'); +range = c.cycle(stamp(2024, 2, 29), 31); +check(range.start == '2024-02-29' && range.end == '2024-03-31', 'leap year clamp'); +range = c.cycle(stamp(2027, 1, 2), 15); +check(range.start == '2026-12-15' && range.end == '2027-01-15', 'cross-year cycle'); + +c.update_config(db, { monthly_gb:2, daily_gb:1, used_gb:1.5 }, now + 10); +check(c.status(db, now + 10).cycle_used == 1500000000, 'cycle usage calibration'); +check(c.status(db, now + 10).today_used == 600, 'calibration does not corrupt day history'); +check(c.status(db, now + 10).remaining == 500000000, 'decimal GB quota'); +check(c.status(db, stamp(2026, 3, 1)).cycle_used == 0, 'calibration expires next cycle'); +c.update_config(db, { count_mode:'rx', monthly_gb:0 }, now + 10); +check(c.status(db, now + 10).today_used == 500 && c.status(db, now + 10).remaining == null, 'direction and unlimited plan'); +let rejected = false; +try { c.update_config(db, { reset_day:0 }, now); } catch (e) { rejected = true; } +check(rejected, 'invalid reset day rejected'); +rejected = false; +try { c.update_config(db, { count_mode:'invalid' }, now); } catch (e) { rejected = true; } +check(rejected, 'invalid mode rejected'); + +db = c.fresh(0); c.advance(db, sample(0, 0), 0); c.advance(db, sample(300, 20), 10); +check(length(keys(db.days)) == 0 && db.pending_rx == 300, 'unsynced clock defers allocation'); +c.advance(db, sample(400, 40), stamp(2026, 10, 7)); +check(c.status(db, stamp(2026, 10, 7)).today_used == 440, 'NTP sync keeps pending bytes'); +printf('traffic accounting: %d checks passed\n', checks); diff --git a/tools/android-install.sh b/tools/android-install.sh index c5785c7b..721fd163 100755 --- a/tools/android-install.sh +++ b/tools/android-install.sh @@ -24,22 +24,19 @@ say() { echo "[device] $*"; } say_i18n() { if [ "${MU300_INSTALL_LANG:-en}" = zh ]; then say "$1"; else say "$2"; fi; } if [ "${SD_MODE:-0}" = 1 ]; then + . "$P/tf-storage.sh" + mkdir -p "$T" + if [ -n "${MU300_TF_STATE:-}" ]; then + read -r required_kib required_inodes < "$P/rootfs.requirements" + fi R=${SD_DEV:?SD_DEV is not set} [ -b "$R" ] || { say_i18n "找不到块设备 $R(TF 卡是否已插入?)" \ "no block device $R (is the TF card inserted?)"; exit 1; } - vol=$(sm list-volumes 2>/dev/null | sed -n 's/^\(public:[^ ]*\) mounted.*/\1/p') - if [ -n "$vol" ]; then - say_i18n "正在请求 Android 卸载 $vol" "asking vold to unmount $vol" - sm unmount "$vol" 2>/dev/null || true - sm list-volumes 2>/dev/null | grep -q "^$vol mounted" && { - say_i18n "TF 卡仍被 Android 挂载;请先在系统存储设置中卸载" \ - "vold still has the card mounted; unmount it in Android Storage settings"; exit 1; } - fi - for m in $(grep -o '^/dev/block/mmcblk1[^ ]*' /proc/mounts 2>/dev/null); do - umount "$m" 2>/dev/null || umount -f "$m" 2>/dev/null || true - done - magic=$(dd if="$R" bs=1 skip=1080 count=2 2>/dev/null | od -An -tx1 | tr -d ' \n') - label=$(dd if="$R" bs=1 skip=1144 count=16 2>/dev/null | tr -d '\000') + # Never touch an eMMC free-region candidate from the SD branch. + tf_release "$R" + tf_read_super "$R" || { tf_die 'failed/short TF superblock read'; exit 1; } + magic=$(dd if="$T/tf-super" bs=1 skip=1080 count=2 2>/dev/null | od -An -tx1 | tr -d ' \n') + label=$(dd if="$T/tf-super" bs=1 skip=1144 count=16 2>/dev/null | tr -d '\000') if [ "$FORMAT" = 1 ]; then [ "$magic" != 53ef ] || [ "$label" = mu300sd ] || { say_i18n "拒绝格式化非 mu300sd 的 ext4 文件系统 '$label'" \ @@ -54,7 +51,15 @@ if [ "${SD_MODE:-0}" = 1 ]; then # resolves to BusyBox's ext2-only applet, even when Android's real # e2fsprogs is installed. An absolute path bypasses that interception. if [ -x /system/bin/mke2fs ]; then + # Explicit minimum inode count for small TFs; large cards retain + # the sparse 1 MiB/inode layout. No filesystem-size argument/cap. + inode_args= + if [ -n "${MU300_TF_STATE:-}" ]; then + read -r required_kib required_inodes < "$P/rootfs.requirements" + [ $((tf_sectors / 2048)) -ge $((required_inodes + 1024)) ] || inode_args="-N $((required_inodes + 1024))" + fi /system/bin/mke2fs -t ext4 -F -b 4096 -m 0 -i 1048576 \ + $inode_args \ -E lazy_itable_init=1,lazy_journal_init=1,nodiscard \ -L mu300sd "$R" || { say_i18n '快速创建 ext4 文件系统失败' \ 'optimized ext4 format failed'; exit 1; } @@ -69,7 +74,15 @@ if [ "${SD_MODE:-0}" = 1 ]; then fi mkdir -p "$M" mount -t ext4 -o noatime "$R" "$M" - trap 'sync; umount "$M" >/dev/null 2>&1 || true' EXIT + # On failure do not global-sync or launch a second I/O request into a + # possibly wedged card. The bounded Magisk worker leaves a reboot lock. + if [ -n "${MU300_TF_STATE:-}" ]; then + free_kib=$(df -Pk "$M" | awk 'END {print $4}') + free_inodes=$(df -Pi "$M" | awk 'END {print $4}') + [ "$free_kib" -ge "$required_kib" ] && [ "$free_inodes" -ge "$required_inodes" ] || { + tf_die 'insufficient usable space/inodes after format'; exit 1; + } + fi else # --- the region must not overlap any partition (checked again here, on the device itself) end=0 @@ -78,7 +91,8 @@ for p in /sys/block/mmcblk0/mmcblk0p*; do [ $e -gt $end ] && end=$e done disk=$(cat /sys/block/mmcblk0/size) -[ "$OFF_S" -ge $end ] && [ $((OFF_S + SIZE_S)) -le $((disk - 34)) ] || { say "region overlaps partitions or the backup GPT"; exit 1; } +[ "$SIZE_S" -ge 8 ] && [ "$OFF_S" -ge $end ] && [ "$OFF_S" -lt "$disk" ] && \ + [ "$SIZE_S" -le $((disk - 34 - OFF_S)) ] || { say "region overlaps partitions or the backup GPT"; exit 1; } attach() { for o in /sys/block/loop*/loop/offset; do @@ -130,10 +144,20 @@ for os in $OSES; do say_i18n "正在安装 $os" "installing $os" rm -rf $M/$os.new && mkdir $M/$os.new tar -xzpf $tarball -C $M/$os.new + if [ -n "${MU300_TF_STATE:-}" ]; then + (cd "$M/$os.new" && sha256sum -c "$P/rootfs-critical.sha256") + [ -L "$M/$os.new/sbin/init" ] || [ -x "$M/$os.new/sbin/init" ] + fi # prebuilt images: firmware and Android userspace pulled from this device by install.sh (tools/vendor-overlay.py) if [ -f $P/mu300-vendor-$os.tar.gz ]; then tar -xzpf $P/mu300-vendor-$os.tar.gz -C $M/$os.new [ "${MU300_KEEP_PAYLOAD:-0}" = 1 ] || rm -f $P/mu300-vendor-$os.tar.gz + elif [ -n "${MU300_PREPARED_VENDOR:-}" ]; then + # Do not merge stale property snapshots/libraries from the build device + # with this device's vendor tree. + rm -rf "$M/$os.new/opt/mu300/android" + cp -a "$MU300_PREPARED_VENDOR/." "$M/$os.new/" + (cd "$M/$os.new" && sha256sum -c "$MU300_TF_STATE/vendor.sha256" >/dev/null) elif [ "${MU300_VENDOR_FROM_DEVICE:-0}" = 1 ]; then sh "$P/mu300-vendor-from-device.sh" "$M/$os.new" "$os" fi @@ -181,8 +205,8 @@ for os in $OSES; do say_i18n "已保留先前 $os 的配置:$kept" "kept from the previous $os:$kept" [ -n "$extra" ] && say_i18n "已保留启用的服务:$extra" "kept enabled services:$extra" fi - rm -rf $M/$os && mv $M/$os.new $M/$os - R=$M/$os + # Configure and validate the staged tree before publishing its name. + R=$M/$os.new [ "${SD_MODE:-0}" = 1 ] && [ -f $R/etc/fstab ] && \ sed -i 's|LABEL=mu300root|LABEL=mu300sd|' $R/etc/fstab mkdir -p $R/etc/mu300 @@ -200,6 +224,7 @@ for os in $OSES; do openwrt) sed -i "s|^root:[^:]*:|root:$PWHASH:|" $R/etc/shadow ;; esac fi + rm -rf "$M/$os" && mv "$M/$os.new" "$M/$os" [ "${MU300_KEEP_PAYLOAD:-0}" = 1 ] || rm -f $tarball done mkdir -p $M/.mu300 @@ -216,4 +241,24 @@ installed=$(ls -d $M/ubuntu $M/openwrt 2>/dev/null | sed "s|$M/||g" | tr '\n' ' say_i18n "已安装:${installed}启动系统=$BOOT_OS 默认启动 Linux=$DEFAULT_LINUX" \ "installed: ${installed}boot-os=$BOOT_OS default-linux=$DEFAULT_LINUX" [ "${MU300_KEEP_PAYLOAD:-0}" = 1 ] || rm -f $P/mu300-install.env +if [ "${SD_MODE:-0}" = 1 ]; then + say_i18n '正在刷盘、卸载并回读 TF 文件系统' 'flushing, unmounting and reading back TF filesystem' + # umount performs filesystem writeback and reports failure. A read-only + # remount checks the published tree before any boot partition is written. + umount "$M" + if [ -n "${MU300_TF_STATE:-}" ]; then + mount -t ext4 -o ro,noload "$SD_DEV" "$M" + (cd "$M/openwrt" && sha256sum -c "$P/rootfs-critical.sha256") + if [ -n "${MU300_PREPARED_VENDOR:-}" ]; then + (cd "$M/openwrt" && sha256sum -c "$MU300_TF_STATE/vendor.sha256" >/dev/null) + fi + [ "$(cat "$M/.mu300/boot-os")" = "$BOOT_OS" ] + [ "$(cat "$M/openwrt/etc/mu300/default-boot")" = linux ] + umount "$M" + fi +else + # Also make the legacy path's success marker mean unmount has finished. + sh "$T/android-mount-mu300root.sh" -u "$M" + trap - EXIT +fi echo MU300-INSTALL-OK # install.sh checks for this line (set -e stops before it on any failure) diff --git a/tools/build-openwrt-tf-magisk.sh b/tools/build-openwrt-tf-magisk.sh index 872c3fd1..f1501beb 100755 --- a/tools/build-openwrt-tf-magisk.sh +++ b/tools/build-openwrt-tf-magisk.sh @@ -38,6 +38,7 @@ for f in wcn_bsp.ko sprd_wlan_combo.ko sprdbt_tty.ko mali_kbase.ko; do [ -s "$IN/out/modules/$f" ] || { echo "missing $IN/out/modules/$f" >&2; exit 1; } done [ -s "$UO/Image" ] || { echo "missing Linux $KERNEL Image in $UO" >&2; exit 1; } +python3 "$TOP/upstream/check-container-support.py" "$UO" rel=$(strings "$UO/Image" | sed -n 's/^Linux version \([^ ]*\) .*/\1/p' | head -n1) case $rel in "$KERNEL".*) ;; *) echo "$UO is kernel '$rel', expected $KERNEL.x" >&2; exit 1 ;; esac for m in $(cat "$TOP/upstream/module-order.txt"); do @@ -73,6 +74,10 @@ for f in ./lib/netifd/proto/mu300cell.sh ./lib/netifd/proto/mu300cell-v6.sh \ ./usr/lib/lua/luci/i18n/mu300.en.lmo ./usr/lib/lua/luci/i18n/mu300.tr.lmo \ ./etc/init.d/unisoc-modem-ui ./etc/rc.d/S95unisoc-modem-ui \ ./www/luci-static/aurora/main.css \ + ./www/luci-static/resources/view/aurora/studio.js \ + ./www/luci-static/resources/view/aurora/marketplace.js \ + ./usr/share/luci/menu.d/luci-app-aurora.json ./usr/share/rpcd/acl.d/luci-app-aurora.json \ + ./usr/lib/lua/luci/i18n/aurora-config.zh-cn.lmo ./usr/lib/lua/luci/i18n/aurora-config.tr.lmo \ ./usr/share/ucode/luci/template/themes/aurora/header.ut; do tar -tzf "$ROOTFS" "$f" >/dev/null || { echo "built rootfs missing required file: $f" >&2; exit 1; } done @@ -94,7 +99,7 @@ python3 "$TOP/boot/build-boot-image.py" \ --kernel "$WRAPPED" --append-ramdisk "$GENERIC" --modules "$IN/out/modules" \ --init "$TOP/boot/init" --busybox "$IN/busybox" --logdw "$IN/tools/logdw/logdw" \ --ueventd-perms "$TOP/android-vendor/ueventd-perms.sh" \ - --android-subset "$IN/android-subset" --out "$BOOT" >/dev/null + --android-subset "$IN/android-subset" --root-target sd --out "$BOOT" >/dev/null STAGE=$(mktemp -d "$TOP/work/tf-magisk-stage.XXXXXX") trap 'rm -rf "$STAGE"' EXIT @@ -102,13 +107,15 @@ cp "$TOP/android/magisk/mu300-openwrt-tf/module.prop" \ "$TOP/android/magisk/mu300-openwrt-tf/customize.sh" \ "$TOP/android/magisk/mu300-openwrt-tf/locale.sh" \ "$TOP/android/magisk/mu300-linux-switch/switch.sh" \ - "$TOP/tools/android-install.sh" "$TOP/tools/mu300-vendor-from-device.sh" "$STAGE/" + "$TOP/tools/android-install.sh" "$TOP/tools/mu300-vendor-from-device.sh" \ + "$TOP/tools/tf-storage.sh" "$TOP/tools/tf-stage.sh" "$TOP/tools/tf-install-worker.sh" "$STAGE/" sed -i "s/Linux 7\.2/Linux $KERNEL/g; s/KERNEL=7\.2/KERNEL=$KERNEL/g" "$STAGE/customize.sh" sed -i "s/7\.2/$KERNEL/g" "$STAGE/module.prop" cp "$IN/busybox" "$STAGE/busybox" cp "$ROOTFS" "$STAGE/mu300-openwrt.tar.gz" cp "$BOOT" "$STAGE/boot-linux.img" (cd "$STAGE" && sha256sum boot-linux.img | cut -d' ' -f1 > boot-linux.sha256) +python3 "$TOP/tools/tf-payload-manifest.py" "$STAGE" chmod 755 "$STAGE"/*.sh "$STAGE/busybox" rm -f "$OUT" python3 - "$STAGE" "$OUT" <<'PY' diff --git a/tools/tf-install-worker.sh b/tools/tf-install-worker.sh new file mode 100644 index 00000000..44fa3482 --- /dev/null +++ b/tools/tf-install-worker.sh @@ -0,0 +1,87 @@ +#!/bin/sh +# Runs under bundled BusyBox ash in Android init's mount namespace, not in +# Magisk's sourced customize.sh shell. Only successful stages permit the next. +set -eu +P=${MU300_PAYLOAD_DIR:?}; T=${MU300_INSTALL_TMP:?}; BB=${MU300_BUSYBOX:?} +# A private applet directory guarantees consistent stat/df/dd/sha256 behavior +# even when Android toybox or Magisk's smaller BusyBox shadows PATH. mke2fs +# remains an absolute Android e2fsprogs path. +if [ -z "${MU300_TF_BIN:-}" ]; then + MU300_TF_BIN=$(mktemp -d "$T/bin.XXXXXX") + "$BB" --install -s "$MU300_TF_BIN" + export MU300_TF_BIN +fi +export PATH="$MU300_TF_BIN:$PATH" +. "$P/tf-storage.sh" +say_i18n() { if [ "${MU300_INSTALL_LANG:-en}" = zh ]; then echo "$1"; else echo "$2"; fi; } +case ${1:-} in + --preflight) + . "$P/mu300-install.env" + cd "$P" + "$BB" sha256sum -c payload.sha256 + [ -s boot-linux.sha256 ] + [ "$(cat boot-linux.sha256)" = "$(sha256sum boot-linux.img | cut -d' ' -f1)" ] + [ -x /system/bin/mke2fs ] || tf_die 'missing Android /system/bin/mke2fs' + /system/bin/mke2fs -V + [ -b "$SD_DEV" ] + [ -b "$MU300_TF_BOOTDEV" ] + read -r required_kib required_inodes < rootfs.requirements + sectors=$(blockdev --getsz "$SD_DEV") + tf_capacity "$sectors" "$required_kib" "$required_inodes" || tf_die 'TF capacity too small / invalid requirements' + boot_sectors=$(blockdev --getsz "$MU300_TF_BOOTDEV") + boot_bytes=$(stat -c %s boot-linux.img) + [ "$boot_bytes" -gt 0 ] && [ $(( (boot_bytes + 4095) / 4096 * 8 )) -le "$boot_sectors" ] || tf_die 'boot image/aligned readback exceeds partition' + [ -b /dev/block/by-name/misc ] && [ "$(blockdev --getsz /dev/block/by-name/misc)" -ge 8 ] || tf_die 'invalid misc partition' + # Staging vendor files avoids discovering absent firmware AFTER format. + free_kib=$(df -Pk "$T" | awk 'END {print $4}') + [ "$free_kib" -ge 131072 ] || tf_die 'need 128 MiB free Android staging space' + exit 0 ;; + --write-boot) + # fdatasync flushes this partition, not every Android filesystem. + exec "$BB" dd if="$P/boot-linux.img" of="$MU300_TF_BOOTDEV" bs=4M conv=fsync ;; + --staging-space) + # Vendor staging has now completed. Its measured size/count must fit + # the reserved budget; leave room for a full boot readback in /data. + vendor_kib=$(du -sk "$MU300_PREPARED_VENDOR" | awk '{print $1}') + vendor_inodes=$(find "$MU300_PREPARED_VENDOR" | wc -l) + [ "$vendor_kib" -le 196608 ] && [ "$vendor_inodes" -le 8192 ] || tf_die 'vendor staging exceeds reserved space/inode budget' + free_kib=$(df -Pk "$T" | awk 'END {print $4}') + boot_bytes=$(stat -c %s "$P/boot-linux.img") + [ "$free_kib" -ge $(( (boot_bytes + 1023) / 1024 + 32768 )) ] || tf_die 'not enough Android space for boot readback' + (cd "$MU300_PREPARED_VENDOR" && find . -type f -exec sha256sum {} +) > "$MU300_TF_STATE/vendor.sha256" + exit 0 ;; + --verify-boot) + bytes=$(stat -c %s "$P/boot-linux.img") + # Read bounded aligned blocks to a file; no pipeline hides an I/O error. + dd if="$MU300_TF_BOOTDEV" of="$T/boot-readback" bs=4096 count=$(( (bytes + 4095) / 4096 )) + [ "$(stat -c %s "$T/boot-readback")" -ge "$bytes" ] + truncate -s "$bytes" "$T/boot-readback" + [ "$(sha256sum "$T/boot-readback" | cut -d' ' -f1)" = "$(cat "$P/boot-linux.sha256")" ] + rm -f "$T/boot-readback" + exit 0 ;; +esac + +# A failed install remains locked until Android reboots. This also prevents +# retries accumulating unkillable requests after a storage-driver failure. +boot_id=$(cat /proc/sys/kernel/random/boot_id) +lock=$T/lock-$boot_id +mkdir "$lock" 2>/dev/null || { + tf_die 'installer already ran/is running in this boot; reboot Android before retrying'; exit 1; +} +MU300_TF_STATE=$(mktemp -d "$T/log.XXXXXX") +export MU300_TF_STATE +say_i18n "TF 安装日志:$MU300_TF_STATE" "TF installation logs: $MU300_TF_STATE" +tf_step preflight 180 "$BB" sh "$0" --preflight +tf_step vendor-preflight 180 "$BB" sh "$P/mu300-vendor-from-device.sh" "$MU300_TF_STATE/vendor" openwrt +MU300_PREPARED_VENDOR=$MU300_TF_STATE/vendor +export MU300_PREPARED_VENDOR +tf_step staging-space 30 "$BB" sh "$0" --staging-space +tf_step rootfs 1200 "$BB" sh "$P/android-install.sh" +tf_step boot-write 60 "$BB" sh "$0" --write-boot +tf_step boot-readback 60 "$BB" sh "$0" --verify-boot +tf_step arm-slot 60 "$BB" sh "$P/switch.sh" --no-reboot +rmdir "$lock" +# Logs remain in Android /data for diagnosis; only the private vendor staging +# directory is disposable. Avoid broad error-path cleanup or global sync. +rm -rf "$MU300_TF_STATE/vendor" +rm -rf "$MU300_TF_BIN" diff --git a/tools/tf-payload-manifest.py b/tools/tf-payload-manifest.py new file mode 100644 index 00000000..0265c6eb --- /dev/null +++ b/tools/tf-payload-manifest.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Validate a TF payload at packaging time; emit size/inode and integrity data.""" +import hashlib +import posixpath +import sys +import tarfile +from pathlib import Path + + +def manifest(stage): + stage = Path(stage) + members = {} + kib = 0 + with tarfile.open(stage / 'mu300-openwrt.tar.gz', 'r:gz') as archive: + for m in archive: + name = posixpath.normpath(m.name) + if name.startswith('/') or name == '..' or name.startswith('../'): + raise ValueError(f'unsafe archive path: {m.name}') + # Do not extract through a parent symlink, whatever archive order. + members[name] = m + kib += ((m.size + 4095) // 4096) * 4 if m.isfile() else 4 + for name in members: + parent = posixpath.dirname(name) + while parent and parent != '.': + if parent in members and members[parent].issym(): + raise ValueError(f'archive entry traverses symlink: {name}') + parent = posixpath.dirname(parent) + # network is generated on first boot; its defaults, not an already + # materialized /etc/config/network, must exist in a fresh rootfs. + for name in ('bin/busybox', 'sbin/procd', 'etc/uci-defaults/90-mu300', 'etc/init.d/mu300-vendor'): + if name not in members or not members[name].isfile() or not members[name].size: + raise ValueError(f'missing boot-critical file: {name}') + if 'sbin/init' not in members: + raise ValueError('missing sbin/init') + # Readback checks cover the boot-critical regular files, unaffected by + # device-specific hotspot/password/fstab edits during installation. + with (stage / 'rootfs-critical.sha256').open('w', newline='\n') as checks: + for name in ('bin/busybox', 'sbin/procd', 'etc/init.d/mu300-vendor'): + digest = hashlib.sha256(archive.extractfile(members[name]).read()).hexdigest() + checks.write(f'{digest} {name}\n') + # Space for vendor runtime, metadata and configuration; inode count is + # explicit at format time, so a small card need not be limited to 1 inode/MiB. + (stage / 'rootfs.requirements').write_text( + f'{kib + max(kib // 4, 262144)} {len(members) + 16384}\n', encoding='ascii') + names = ['mu300-openwrt.tar.gz', 'boot-linux.img', 'rootfs.requirements', 'rootfs-critical.sha256'] + with (stage / 'payload.sha256').open('w', newline='\n') as checks: + for name in names: + with (stage / name).open('rb') as stream: + digest = hashlib.sha256() + for chunk in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(chunk) + checks.write(f'{digest.hexdigest()} {name}\n') + + +if __name__ == '__main__': + manifest(sys.argv[1]) diff --git a/tools/tf-stage.sh b/tools/tf-stage.sh new file mode 100644 index 00000000..9ad15541 --- /dev/null +++ b/tools/tf-stage.sh @@ -0,0 +1,66 @@ +#!/bin/sh +# One bounded installer stage, in its own process group. Never wait for a +# timed-out kernel I/O request, never retry it, and never run sync on failure. +set -u +BB=${MU300_BUSYBOX:?} +if [ "${1:-}" = --worker ]; then + result=$2; shift 2 + "$@" + rc=$? + printf '%s\n' "$rc" > "$result.tmp" + mv "$result.tmp" "$result" + exit "$rc" +fi +name=$1; limit=$2; shift 2 +state=${MU300_TF_STATE:?} +job=$(mktemp -d "$state/$name.XXXXXX") || exit 1 +msg() { if [ "${MU300_INSTALL_LANG:-en}" = zh ]; then echo "$1"; else echo "$2"; fi; } +case $name in + preflight) zh_name=安装包与容量校验 ;; + vendor-preflight) zh_name=设备固件预检与暂存 ;; + staging-space) zh_name=剩余空间检查 ;; + rootfs) zh_name=TF文件系统安装与回读 ;; + boot-write) zh_name=写入启动镜像 ;; + boot-readback) zh_name=启动镜像回读校验 ;; + arm-slot) zh_name=设置启动槽位 ;; + *) zh_name=$name ;; +esac +msg "[TF] 阶段:$zh_name(上限 ${limit} 秒)" "[TF] stage: $name (limit ${limit}s)" +"$BB" setsid "$BB" sh "$0" --worker "$job/result" "$@" > "$job/output.log" 2>&1 & +pid=$! +start=$(cut -d. -f1 /proc/uptime) +last=$start; previous=; shown=0 +stop_worker() { + # Only this stage's session, not Magisk or another installer. + "$BB" kill -TERM -- "-$pid" 2>/dev/null || true + "$BB" kill -KILL -- "-$pid" 2>/dev/null || true +} +trap 'stop_worker; exit 130' INT TERM HUP +while :; do + size=$(wc -c < "$job/output.log") + if [ "$size" -gt "$shown" ]; then + tail -c +$((shown + 1)) "$job/output.log" + shown=$size + fi + if [ -f "$job/result" ]; then + # The worker can finish between the size sample and this check. + tail -c +$((shown + 1)) "$job/output.log" + rc=$(cat "$job/result") + wait "$pid" 2>/dev/null || true + case $rc in 0) exit 0 ;; *) exit 1 ;; esac + fi + now=$(cut -d. -f1 /proc/uptime) + # Block completion counters, not log heartbeats, identify actual I/O + # progress. Total deadline still applies if a broken driver spins/retries. + progress=$(cat /sys/class/block/mmcblk1/stat 2>/dev/null):$size + if [ "$progress" != "$previous" ]; then last=$now; previous=$progress; fi + if [ $((now - start)) -ge "$limit" ] || [ $((now - last)) -ge 120 ]; then + stop_worker + : > "$state/reboot-required" + msg "[TF] $zh_name 超时,已停止后续写入。请重启 Android 后重试;内核阻塞的 I/O 可能无法被终止。日志:$job" \ + "[TF] $name timed out; no further writes. Reboot Android before retrying: kernel-blocked I/O may not be killable. Log: $job" + exit 124 + fi + [ $(( (now - start) % 10 )) -ne 0 ] || msg "[TF] $zh_name:已运行 $((now - start)) 秒" "[TF] $name: $((now - start))s elapsed" + sleep 2 +done diff --git a/tools/tf-storage.sh b/tools/tf-storage.sh new file mode 100644 index 00000000..09b64117 --- /dev/null +++ b/tools/tf-storage.sh @@ -0,0 +1,119 @@ +#!/bin/sh +# TF-only storage primitives. Sourced by android-install.sh and tested with +# fixture sysfs/mountinfo trees; no environment override of production paths. +tf_die() { say_i18n "TF 安装中止:$1" "TF installation stopped: $1"; return 1; } +tf_step() { "$MU300_BUSYBOX" sh "$P/tf-stage.sh" "$@"; } +tf_mounts_for_ids() { + # mountinfo field 3 is major:minor, independent of /dev/block/vold aliases. + awk -v ids="$1" 'BEGIN { n=split(ids,a," "); for(i=1;i<=n;i++) wanted[a[i]]=1 } + wanted[$3] { print $1, $5 }' "$2" +} +tf_namespace_gone() { + # An exited/zombie task can still have a proc directory, but mountinfo + # returns EINVAL after its namespace was released. Never exempt live tasks + # merely because a proc read failed (permissions/SELinux must fail closed). + [ -e "$1/mountinfo" ] || return 0 + tf_process_state=$(awk '/^State:/ {print $2}' "$1/status" 2>/dev/null) || return 1 + case $tf_process_state in + Z|X) if ! readlink "$1/ns/mnt" >/dev/null 2>&1; then return 0; fi ;; + esac + return 1 +} +tf_release() { + [ "$(readlink /proc/self/ns/mnt)" = "$(readlink /proc/1/ns/mnt)" ] || { + tf_die 'run in Android init mount namespace (nsenter -t 1 -m)'; return 1; + } + tf_target=$(readlink -f "$1") || return 1 + case $tf_target in /dev/block/mmcblk1|/dev/block/mmcblk1p[0-9]*) ;; *) tf_die 'unexpected TF device'; return 1 ;; esac + tf_ids= + # Formatting a whole card requires releasing every partition. For a + # partition install do not disturb other partitions or other removable disks. + for tf_sys in /sys/class/block/mmcblk1 /sys/class/block/mmcblk1p*; do + [ -r "$tf_sys/dev" ] || continue + # The raw parent overlaps a selected partition too. An accidental + # whole-card mount must not be overlooked just because p1 was selected. + [ "$tf_target" = /dev/block/mmcblk1 ] || [ "${tf_sys##*/}" = mmcblk1 ] || \ + [ "${tf_sys##*/}" = "${tf_target##*/}" ] || continue + tf_id=$(cat "$tf_sys/dev") || return 1 + for tf_holder in "$tf_sys"/holders/*; do + [ ! -e "$tf_holder" ] || { tf_die "TF has a device-mapper/stacked holder: $tf_holder"; return 1; } + done + tf_ids="$tf_ids $tf_id" + done + [ -n "$tf_ids" ] || { tf_die 'missing TF device identity'; return 1; } + # vold unmount is asynchronous. This is an operation deadline, not a + # boot delay. No forced/lazy unmount and no format until every alias is gone. + # Android reports unsupported/unreadable public filesystems (including + # some existing Linux TF installs) as "unmountable", not "unmounted". + # That is NOT a mounted state; still verify mountinfo below before writes. + tf_n=0 + tf_requested=' ' + while [ "$tf_n" -lt 15 ]; do + tf_busy= + tf_volumes=$(sm list-volumes all) || return 1 + for tf_id in $tf_ids; do + tf_vol=public:$(echo "$tf_id" | tr : ,) + tf_state=$(printf '%s\n' "$tf_volumes" | awk -v v="$tf_vol" '$1==v {print $2}') + case $tf_state in + ''|unmounted|unmountable) ;; + mounted|mounted_ro) + tf_busy=1 + case $tf_requested in + *" $tf_vol "*) ;; + *) + say_i18n "正在释放 $tf_vol ($tf_state)" "releasing $tf_vol ($tf_state)" + sm unmount "$tf_vol" || return 1 + tf_requested="$tf_requested$tf_vol " ;; + esac ;; + checking|ejecting) tf_busy=1 ;; + *) tf_die "unexpected vold state: $tf_vol $tf_state"; return 1 ;; + esac + done + [ -n "$tf_busy" ] || break + tf_n=$((tf_n + 1)); sleep 1 + done + [ -z "$tf_busy" ] || { + printf '%s\n' "$tf_volumes" + tf_die 'vold did not release TF (see volume states above)'; return 1; + } + # In init's mount namespace: remove any remaining direct mounts, children + # first. A mount remaining in another namespace is a hard refusal, not an + # invitation to enter arbitrary app namespaces and detach their storage. + tf_mounts_for_ids "$tf_ids" /proc/self/mountinfo | sort -rn > "$T/tf-mounts" + while read -r tf_mid tf_path; do + [ -n "$tf_mid" ] || continue + tf_path=$(printf '%b' "$tf_path") + umount "$tf_path" || return 1 + done < "$T/tf-mounts" + for tf_info in /proc/[0-9]*/mountinfo; do + [ -r "$tf_info" ] || continue + tf_left=$(tf_mounts_for_ids "$tf_ids" "$tf_info" 2>/dev/null) || { + if tf_namespace_gone "${tf_info%/mountinfo}"; then continue; fi + tf_die "cannot inspect $tf_info"; return 1 + } + [ -z "$tf_left" ] || { tf_die "TF still mounted ($tf_info): $tf_left"; return 1; } + done +} +tf_read_super() { + # Bound BEFORE I/O; check the read itself AND byte count. A short read is + # never a blank disk. Only aligned raw-device reads (no bs=1 raw seeks). + tf_sectors=$(blockdev --getsz "$1") || return 1 + case $tf_sectors in ''|*[!0-9]*) return 1 ;; esac + [ "$tf_sectors" -ge 8 ] || return 1 + dd if="$1" of="$T/tf-super" bs=512 count=8 || return 1 + [ "$(wc -c < "$T/tf-super")" -eq 4096 ] || return 1 +} +tf_capacity() { + # Arguments are sectors, required KiB and required inodes. Sector arithmetic + # avoids Android mksh byte overflow. We run TF workers with 64-bit BusyBox ash. + case $1:$2:$3 in *[!0-9:]*|:*|*::*|*:) return 1 ;; esac + [ "$1" -gt 0 ] && [ "$2" -gt 0 ] && [ "$3" -gt 0 ] || return 1 + [ $(( $1 / 2 )) -ge "$2" ] || return 1 +} + +if [ "${1:-}" = --release ]; then + set -eu + P=${MU300_PAYLOAD_DIR:?}; T=${MU300_INSTALL_TMP:?} + say_i18n() { if [ "${MU300_INSTALL_LANG:-en}" = zh ]; then echo "$1"; else echo "$2"; fi; } + tf_release "$2" +fi diff --git a/upstream/README.md b/upstream/README.md index 1acfa51e..868c0a9c 100644 --- a/upstream/README.md +++ b/upstream/README.md @@ -37,6 +37,38 @@ The build stops on anything that drifts silently: a patch that neither applies n Kconfig does not take (unless listed in `config-ignored.txt`), a port edit whose anchor moved, or a module whose vermagic does not match the kernel. `tools/make-release.sh` packages the same bundle as `mu300-kernel-6.18.tar.gz`. +### KVM and container kernel support + +The shared 6.18/7.2 configuration includes the KVM/container subset of upstream +commits `59e17d5` and `765da29`: built-in KVM, `/proc/config.gz`, namespace, +seccomp and cgroup controllers; on-demand vhost-net/vsock, bridge netfilter, +IPVS, VXLAN/IPvlan, binfmt_misc and FUSE modules. Existing OverlayFS, veth, +bridge and nftables remain built in. Use the nftables/iptables-nft backend, +not iptables-legacy. No Docker/QEMU daemon is installed or enabled by this +kernel change; userspace runtimes are separate and must be installed before use. +Do not expose an unauthenticated Docker TCP socket. + +`build-modules.sh` now installs **in-tree modules as well as vendor modules**, +stripped and flat under `out/modules`. Only `module-order.txt` goes into the +early boot ramdisk; optional container/VM drivers are not loaded at boot. +Partial builds remove previously collected in-tree modules and reject module +name collisions (including `-`/`_` aliases). The unrelated upstream USB/Wi-Fi, +RAID, VPN and network-filesystem additions are deliberately not part of this port. + +The output also carries `kernel.config`, `kernel.sha256`, `modules.in-tree` +and `modules.sha256`. `check-container-support.py` verifies the **built** config, +Image and complete module set before TF/Magisk, generic kernel bundle or +mainline rootfs assembly. Old output directories lacking this evidence need a +fresh `build.sh` followed by `build-modules.sh`; copying a new fragment next to +an old Image is not sufficient. Both commands must use the same `KV`/`OUTDIR`. + +After installing and rebooting into a rebuilt kernel, runtime acceptance still +requires `/dev/kvm`, a successful KVM VM/vCPU run, cgroup controllers mounted +by the host, and a Docker container with working networking and resource limits. +Upstream records successful KVM execution on its F50; config/build checks alone +do not certify the current device or a running Docker service. This feature +cannot be hot-applied to an already running kernel without KVM. + The bring-up path of old (hand-built image, `init-bringup`, `boot/flash-trial.sh`) still works for experiments: ```sh python3 upstream/wrap-image.py upstream/out/Image upstream/out/Image.lk diff --git a/upstream/build-modules.sh b/upstream/build-modules.sh index a00e922f..96927cd4 100644 --- a/upstream/build-modules.sh +++ b/upstream/build-modules.sh @@ -1,5 +1,5 @@ #!/bin/bash -# Build the out-of-tree vendor modules (WCN) against the mainline tree built by build.sh. +# Build vendor modules and collect the kernel's own modules, flat for kmodloader. # Run inside the mu300-mainline-build container: bash /work/build-modules.sh [module-dir...] set -eo pipefail KV=${KV:-6.18.54} @@ -14,6 +14,26 @@ mkdir -p $OUT/modules [ $# -gt 0 ] || rm -f $OUT/modules/*.ko $OUT/modules/*.log # Module.symvers for the built-in exports (pcie-sprd etc.) make -C $K O=$O ARCH=arm64 -j"$(nproc)" modules > $O/modules.log 2>&1 || { tail -20 $O/modules.log; exit 1; } +cmp -s "$O/.config" "$OUT/kernel.config" || { + echo 'kernel configuration changed or Image evidence missing; run build.sh first with the same KV/OUTDIR' >&2 + exit 1 +} +# Based on upstream 59e17d5/765da29: =m was previously compiled but never shipped. +# A private staging directory avoids stale modules from a previous configuration. +STAGE=$(mktemp -d "$O/mod-install.XXXXXX") +trap 'rm -rf "$STAGE"' EXIT +make -C "$K" O="$O" ARCH=arm64 INSTALL_MOD_PATH="$STAGE" INSTALL_MOD_STRIP=1 DEPMOD=true modules_install >> "$O/modules.log" 2>&1 || + { tail -20 "$O/modules.log"; exit 1; } +if [ -f "$OUT/modules.in-tree" ]; then + while IFS= read -r ko; do + case $ko in ''|*/*|*..*) echo "invalid previous module name: $ko" >&2; exit 1 ;; esac + rm -f "$OUT/modules/$ko" + done < "$OUT/modules.in-tree" +fi +find "$STAGE/lib/modules" -name '*.ko' -printf '%f\n' | sort > "$OUT/modules.in-tree" +tr - _ < "$OUT/modules.in-tree" | sort > "$O/modules.in-tree.names" +[ -z "$(uniq -d "$O/modules.in-tree.names")" ] || { echo 'in-tree module name collision' >&2; exit 1; } +find "$STAGE/lib/modules" -name '*.ko' -exec cp {} "$OUT/modules/" \; extra= for m in $mods; do rm -rf /src/mod-build/$m && mkdir -p /src/mod-build && cp -r /work/modules/$m /src/mod-build/$m @@ -31,6 +51,13 @@ for m in $mods; do [ "$m" = mali ] && margs="src=/src/mod-build/mali CONFIG_MALI_MIDGARD=m CONFIG_MALI_PLATFORM_NAME=qogirn6pro CONFIG_MALI_DEVFREQ=y CONFIG_DEVFREQ_THERMAL=y CONFIG_MALI_DEBUG=n CONFIG_MALI_FENCE_DEBUG=n BUILD=no" make -C $O ARCH=arm64 M=/src/mod-build/$m KBUILD_EXTRA_SYMBOLS="$extra" KCFLAGS="$kcflags" $margs -j"$(nproc)" modules 2>&1 | tee $OUT/modules/$m.log [ -f /src/mod-build/$m/Module.symvers ] && extra="$extra /src/mod-build/$m/Module.symvers" - find /src/mod-build/$m -name '*.ko' -exec cp {} $OUT/modules/ \; + while IFS= read -r ko; do + name=$(basename "$ko" | tr - _) + ! grep -Fqx "$name" "$O/modules.in-tree.names" || { echo "vendor/in-tree module collision: $name" >&2; exit 1; } + cp "$ko" "$OUT/modules/" + done < <(find /src/mod-build/$m -name '*.ko') done +# Evidence covers every module (including vendor dependencies), not just a shortlist. +(cd "$OUT" && sha256sum Image kernel.config modules/*.ko > modules.sha256) +python3 /work/check-container-support.py "$OUT" ls -la $OUT/modules/*.ko diff --git a/upstream/build.sh b/upstream/build.sh index e432d433..cc1582de 100644 --- a/upstream/build.sh +++ b/upstream/build.sh @@ -52,4 +52,7 @@ mkdir -p $OUT cp $O/arch/arm64/boot/Image $O/ums9620-mu300.dtb $OUT/ # for depmod on the device: modprobe of a built-in driver fails without them cp $O/modules.builtin $O/modules.builtin.modinfo $OUT/ +# Tie feature checks to the Image actually built, not just the requested fragment. +cp "$O/.config" "$OUT/kernel.config" +(cd "$OUT" && sha256sum Image kernel.config > kernel.sha256) ls -la $OUT diff --git a/upstream/check-container-support.py b/upstream/check-container-support.py new file mode 100644 index 00000000..33bf0659 --- /dev/null +++ b/upstream/check-container-support.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Refuse old Images or incomplete module sets in either TF or kernel bundles.""" +import argparse +import hashlib +import re +import tarfile +from pathlib import Path + + +BUILTIN = '''VIRTUALIZATION KVM IKCONFIG IKCONFIG_PROC CGROUPS MEMCG BLK_CGROUP +CGROUP_SCHED CGROUP_PIDS CPUSETS CGROUP_BPF CFS_BANDWIDTH BLK_DEV_THROTTLING +NAMESPACES UTS_NS IPC_NS USER_NS PID_NS NET_NS SECCOMP SECCOMP_FILTER +POSIX_MQUEUE VETH BRIDGE TUN OVERLAY_FS NF_CONNTRACK NF_NAT NF_TABLES NFT_COMPAT +NETFILTER_XT_MATCH_CONNTRACK NETFILTER_XT_TARGET_MASQUERADE'''.split() +MODULES = { + 'VHOST_NET': 'vhost_net', 'VSOCKETS': 'vsock', 'VHOST_VSOCK': 'vhost_vsock', + 'BRIDGE_NETFILTER': 'br_netfilter', 'NETFILTER_XT_MATCH_ADDRTYPE': 'xt_addrtype', + 'NETFILTER_XT_MATCH_IPVS': 'xt_ipvs', 'NETFILTER_XT_MARK': 'xt_mark', + 'IP_VS': 'ip_vs', 'IP_VS_RR': 'ip_vs_rr', 'IP_VS_WRR': 'ip_vs_wrr', + 'IP_VS_SH': 'ip_vs_sh', 'VXLAN': 'vxlan', 'IPVLAN': 'ipvlan', + 'MACVTAP': 'macvtap', 'BINFMT_MISC': 'binfmt_misc', 'FUSE_FS': 'fuse', +} + + +def config_check(path): + config = dict(line.split('=', 1) for line in path.read_text().splitlines() + if line.startswith('CONFIG_') and '=' in line) + for key in BUILTIN: + if config.get('CONFIG_' + key) != 'y': + raise ValueError(f'CONFIG_{key}=y missing in built kernel.config; rebuild kernel') + for key in MODULES: + if config.get('CONFIG_' + key) not in ('y', 'm'): + raise ValueError(f'CONFIG_{key} missing in built kernel.config; rebuild kernel') + return config + + +def check_hashes(out, manifest): + names = set() + for line in (out / manifest).read_text().splitlines(): + digest, name = line.split(None, 1) + name = name.lstrip('* ') + if Path(name).is_absolute() or '..' in Path(name).parts or name in names: + raise ValueError(f'invalid/duplicate manifest path: {name}') + if hashlib.sha256((out / name).read_bytes()).hexdigest() != digest: + raise ValueError(f'{name} no longer matches {manifest}; rebuild it') + names.add(name) + return names + + +def check(out): + config = config_check(out / 'kernel.config') + for name in ('modules.builtin', 'modules.builtin.modinfo'): + if not (out / name).is_file() or not (out / name).stat().st_size: + raise ValueError(f'{name} missing; built-in module indexes must ship too') + if check_hashes(out, 'kernel.sha256') != {'Image', 'kernel.config'}: + raise ValueError('kernel.sha256 must tie Image to kernel.config') + files = {f'modules/{p.name}' for p in (out / 'modules').glob('*.ko')} + if not files or check_hashes(out, 'modules.sha256') != files | {'Image', 'kernel.config'}: + raise ValueError('module manifest is empty/incomplete or stale; rebuild modules') + version = re.search(rb'Linux version ([^\s\x00]+)', (out / 'Image').read_bytes()) + if not version: + raise ValueError('cannot identify Image kernel release') + for name in files: + vermagic = re.search(rb'vermagic=([^\s\x00]+)', (out / name).read_bytes()) + if not vermagic or vermagic[1] != version[1]: + raise ValueError(f'{name} vermagic does not match Image') + normalized = {name.replace('-', '_') for name in files} + if len(normalized) != len(files): + raise ValueError('module names collide after hyphen/underscore normalization') + for key, name in MODULES.items(): + if config['CONFIG_' + key] == 'm' and f'modules/{name}.ko' not in normalized: + raise ValueError(f'{name}.ko missing; kernel support was configured but not packaged') + for name in (out / 'modules.in-tree').read_text().splitlines(): + if f'modules/{name}' not in files: + raise ValueError(f'in-tree dependency {name} missing') + return version[1].decode('ascii') + + +def check_rootfs(out, archive, release): + prefix = f'lib/modules/{release}/' + expected = {prefix + p.name: hashlib.sha256(p.read_bytes()).hexdigest() + for p in (out / 'modules').glob('*.ko')} + for name in ('modules.builtin', 'modules.builtin.modinfo'): + expected[prefix + name] = hashlib.sha256((out / name).read_bytes()).hexdigest() + # Read as a stream, never unpack a tar into the host filesystem. + seen = set() + with tarfile.open(archive, 'r|gz') as tar: + for member in tar: + name = member.name.removeprefix('./') + if name not in expected: + if name.startswith(prefix) and name.endswith('.ko'): + raise ValueError(f'rootfs contains unexpected module: {name}') + continue + if name in seen or not member.isfile(): + raise ValueError(f'rootfs duplicate/non-file module entry: {name}') + data = tar.extractfile(member) + if hashlib.sha256(data.read()).hexdigest() != expected[name]: + raise ValueError(f'rootfs module/index differs from build: {name}') + seen.add(name) + if seen != set(expected): + raise ValueError('rootfs missing built modules/indexes: ' + ', '.join(sorted(set(expected) - seen))) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('output', type=Path) + parser.add_argument('--config-only', action='store_true') + parser.add_argument('--rootfs', type=Path) + args = parser.parse_args() + try: + if args.config_only: + config_check(args.output) + else: + release = check(args.output) + if args.rootfs: + check_rootfs(args.output, args.rootfs, release) + except (OSError, ValueError) as error: + parser.exit(1, f'KVM/container build check: {error}\n') + print('KVM/container build checks passed (runtime verification still required)') diff --git a/upstream/make-bundle.sh b/upstream/make-bundle.sh index 6f75de6e..16a87dd4 100755 --- a/upstream/make-bundle.sh +++ b/upstream/make-bundle.sh @@ -18,6 +18,7 @@ OUT=${1:?usage: upstream/make-bundle.sh OUT.tar.gz [mu300-kernel.tar.gz]} REF=${2:-$(ls -t "$TOP"/release/*/mu300-kernel.tar.gz 2>/dev/null | head -1)} [ -f "$UO/Image" ] || { echo "no $UO/Image (run build.sh)" >&2; exit 1; } [ -f "$REF" ] || { echo "no 5.4 kernel bundle for busybox/logdw (give one as the second argument)" >&2; exit 1; } +python3 "$U/check-container-support.py" "$UO" krel=$(strings "$UO/Image" | sed -n 's/^Linux version \([^ ]*\) .*/\1/p' | head -1) [ -n "$krel" ] || { echo "cannot read the kernel release from upstream/out/Image" >&2; exit 1; } diff --git a/upstream/mu300-mainline.config b/upstream/mu300-mainline.config index 04e68317..32f7f2d5 100644 --- a/upstream/mu300-mainline.config +++ b/upstream/mu300-mainline.config @@ -388,3 +388,43 @@ CONFIG_SOFTLOCKUP_DETECTOR=y CONFIG_HARDLOCKUP_DETECTOR=y # reported, not fatal: vendor threads sleep uninterruptibly for good (sipa-set-rps, slog, the Wi-Fi TX thread) CONFIG_DETECT_HUNG_TASK=y + +# KVM/container subset of upstream 59e17d5 + 765da29. Shared by 6.18 and 7.2. +# Docker is a container runtime, not a KVM guest; neither daemon starts here. +CONFIG_VIRTUALIZATION=y +CONFIG_KVM=y +CONFIG_VHOST_MENU=y +CONFIG_VHOST_NET=m +CONFIG_VSOCKETS=m +CONFIG_VHOST_VSOCK=m +CONFIG_IKCONFIG=y +CONFIG_IKCONFIG_PROC=y +CONFIG_BINFMT_MISC=m +CONFIG_PSI=y +CONFIG_CGROUP_NET_PRIO=y +CONFIG_CGROUP_NET_CLASSID=y +CONFIG_CGROUP_MISC=y +CONFIG_CFS_BANDWIDTH=y +CONFIG_BLK_DEV_THROTTLING=y +# Docker bridge / swarm, using iptables-nft and the existing nft_compat core. +# Do not enable competing legacy iptables tables or change fw4 defaults. +CONFIG_BRIDGE_NETFILTER=m +CONFIG_NETFILTER_XT_MATCH_ADDRTYPE=m +CONFIG_NETFILTER_XT_MATCH_IPVS=m +CONFIG_NETFILTER_XT_MARK=m +CONFIG_NETFILTER_XT_MATCH_COMMENT=m +CONFIG_NETFILTER_XT_MATCH_MULTIPORT=m +CONFIG_NF_CONNTRACK_MARK=y +CONFIG_NF_CONNTRACK_ZONES=y +CONFIG_IP_VS=m +CONFIG_IP_VS_PROTO_TCP=y +CONFIG_IP_VS_PROTO_UDP=y +CONFIG_IP_VS_RR=m +CONFIG_IP_VS_WRR=m +CONFIG_IP_VS_SH=m +CONFIG_IP_VS_NFCT=y +CONFIG_DUMMY=m +CONFIG_MACVTAP=m +CONFIG_IPVLAN=m +CONFIG_VXLAN=m +CONFIG_FUSE_FS=m