diff --git a/boot/init b/boot/init index 855c0cea..ebb85bef 100644 --- a/boot/init +++ b/boot/init @@ -179,27 +179,26 @@ setup_usb_gadget() { # NCM by default, in a single configuration with the ACM console: Windows 10 2004+/11 bind their inbox # UsbNcm.sys to it, macOS and Linux their own drivers - all measured, none needs an INF. ECM, which Windows has # no driver for, is the fallback. MU300_USBNET (kernel command line) picks the functions. - # "rndis ncm" is for Windows without NCM (7, 8, 10 before 2004): RNDIS gets configuration 1 and NCM moves to - # configuration 2. Windows only ever uses the first, and binds rndis.sys to it through the MS OS descriptors - # below; Linux skips RNDIS configurations on purpose. macOS does not: it takes configuration 1 as well, finds - # no driver for RNDIS and has no network (measured) - which is why RNDIS is not the default. + # RNDIS uses a single configuration with ACM. Windows does not create its + # composite parent for a device with multiple configurations: the old + # RNDIS+NCM arrangement bound the whole device to usbser and exposed no + # network adapter. macOS has no RNDIS driver, so NCM remains the default. rndis= netfunc= for f in ${MU300_USBNET:-ncm ecm}; do case $f in rndis) [ -z "$rndis" ] && mkdir -p "$g/functions/rndis.rn0" 2>/dev/null && rndis=1 ;; - *) [ -z "$netfunc" ] && mkdir -p "$g/functions/$f.usb0" 2>/dev/null && netfunc=$f ;; + *) [ -z "$netfunc$rndis" ] && mkdir -p "$g/functions/$f.usb0" 2>/dev/null && netfunc=$f ;; esac done [ -n "$netfunc$rndis" ] || log "stage=usb-no-net-function (console only)" cdc=c.1 - [ -n "$rndis" ] && cdc=c.2 echo 0x0525 > "$g/idVendor" echo 0xa4a1 > "$g/idProduct" echo 0x0200 > "$g/bcdUSB" - # Windows asks for the MS OS descriptors (below) once per VID/PID/bcdDevice and caches the answer, "none" - # included: the default bcdDevice follows the kernel version and was cached as "none" by every PC that met - # the earlier gadget. A value of our own makes them ask again. Change it whenever the descriptors change. - echo 0x0301 > "$g/bcdDevice" + # Windows caches OS-descriptor support by VID/PID/bcdDevice. Use a new + # revision for the corrected, single-configuration RNDIS descriptor. + if [ -n "$rndis" ]; then echo 0x0302 > "$g/bcdDevice" + else echo 0x0301 > "$g/bcdDevice"; fi # Miscellaneous / IAD: the network and the ACM functions each span two interfaces, and without this device class # Windows' composite driver ignores their association descriptors and hands out the interfaces one by one, so a # class driver never sees its function as a whole @@ -221,8 +220,8 @@ setup_usb_gadget() { ln -s "$g/functions/acm.GS0" "$g/configs/c.1/f2" # MS OS descriptors: Windows asks for them with vendor request 0xcd and binds rndis.sys by compatible ID. # They are what identifies the function: the stock f_rndis' control interface is 02/02/ff, which Windows - # would otherwise hand to usbser (a device with two configurations is never composite on Windows, so the - # first interface names the whole device). + # would otherwise hand to usbser. A single configuration lets Windows + # enumerate RNDIS and ACM as separate interface collections. echo 1 > "$g/os_desc/use" echo 0xcd > "$g/os_desc/b_vendor_code" echo MSFT100 > "$g/os_desc/qw_sign" @@ -256,15 +255,26 @@ setup_usb_gadget() { # Never rebind the gadget from a shell running on its own ACM console: the console dies with the unbind and the # rebind never runs, which leaves the device with no USB at all until it is power-cycled. log "stage=usb-bind-start" - [ -n "$udc" ] && echo "$udc" > "$g/UDC" - log "stage=usb-bind-done rc=$?" + bound=0 + [ -n "$udc" ] && echo "$udc" > "$g/UDC" && bound=1 + log "stage=usb-bind-done bound=$bound" + # Consume a one-shot policy only if its requested function was actually + # created and the gadget bound successfully, never just because a config + # file was readable. + if [ "$bound" = 1 ]; then + case ${MU300_USB_REQUESTED:-} in + ecm|ncm) [ "$netfunc" = "$MU300_USB_REQUESTED" ] && echo "$MU300_USB_REQUESTED" > /run/unisoc-usb-net-applied ;; + rndis) [ -n "$rndis" ] && echo rndis > /run/unisoc-usb-net-applied ;; + esac + fi persist # The functions register their netdevs as they are bound, configuration by configuration, so RNDIS would take # usb0 - the name lan-start and the OpenWrt bridge expect for the CDC link. Name them by function instead. if [ -n "$rndis" ]; then r=$(cat "$g/functions/rndis.rn0/ifname" 2>/dev/null) - c=$(cat "$g/functions/$netfunc.usb0/ifname" 2>/dev/null) + c= + [ -z "$netfunc" ] || c=$(cat "$g/functions/$netfunc.usb0/ifname" 2>/dev/null) case $r in ""|"(unnamed net_device)"|rndis0) ;; *) ip link set "$r" name rndis0 ;; esac case $c in ""|"(unnamed net_device)"|usb0) ;; *) ip link set "$c" name usb0 ;; esac log "stage=usb-ifnames rndis=$r->rndis0 cdc=${c:-none}->usb0" @@ -274,17 +284,23 @@ setup_usb_gadget() { # Bring usb0 up immediately after binding, before the host selects the data interface: # f_ecm (and f_ncm alike) reports the link state in its first CONNECT notification, and macOS' ECM driver does not # pick up a later "connected" notification (v10 left usb0 down until systemd ran -> host "inactive"). - ifconfig usb0 up + early_net=usb0 + early_host_mac=$MAC:02 + if [ -n "$rndis" ] && [ -z "$netfunc" ]; then + early_net=rndis0 + early_host_mac=$MAC:04 + fi + ifconfig "$early_net" up # Windows requests DHCP as soon as NCM enumerates, before OpenWrt starts # dnsmasq. Serve the final LAN address immediately and keep the same host # lease across switch_root. The post-rootfs rebind renews this same lease. - if [ -e /sys/class/net/usb0 ]; then - ifconfig usb0 "$NET.1" netmask 255.255.255.0 up - echo "$MAC:02" > /run/mu300-usb-host-mac + if [ -e "/sys/class/net/$early_net" ]; then + ifconfig "$early_net" "$NET.1" netmask 255.255.255.0 up + echo "$early_host_mac" > /run/mu300-usb-host-mac cat > /run/udhcpd-usb0.conf </dev/null | tr '\n' ',')" +# No additional wait or second mount: the root scan has established the TF +# device, and the root mount lets us read the current (journaled) policy. +mkdir -p /disk +rootloop= +root_mounted=0 +if [ -n "$sd_root" ]; then + rootloop=$sd_root + mount -t ext4 -o noatime "$sd_root" /disk 2>>/run/rootmount.err && root_mounted=1 + log "stage=sd-root dev=$sd_root mounted=$root_mounted" +fi +[ "$root_mounted" = 1 ] && read_usb_boot_policy +setup_usb_gadget if [ -z "$sd_root" ]; then if found=$(find_root_offset); then [ "$found" = "$ROOT_OFFSET" ] || log "stage=root-offset found=$found (default $ROOT_OFFSET)" @@ -369,14 +416,6 @@ pick_root() { [ "$os" = ubuntu ] && [ -x /disk/lib/systemd/systemd ] && { echo /disk; return; } done } -mkdir -p /disk -rootloop= -root_mounted=0 -if [ -n "$sd_root" ]; then - rootloop=$sd_root - mount -t ext4 -o noatime "$sd_root" /disk 2>>/run/rootmount.err && root_mounted=1 - log "stage=sd-root dev=$sd_root mounted=$root_mounted" -fi if [ "$root_mounted" = 0 ]; then rootloop=$(losetup -f 2>/run/rootmount.err) if [ -n "$rootloop" ] && losetup -o $ROOT_OFFSET "$rootloop" /dev/mmcblk0 2>>/run/rootmount.err \ diff --git a/openwrt/build-rootfs.sh b/openwrt/build-rootfs.sh index 41710785..7b55bd7b 100755 --- a/openwrt/build-rootfs.sh +++ b/openwrt/build-rootfs.sh @@ -133,6 +133,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/* 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 diff --git a/openwrt/luci-app-mu300/Makefile b/openwrt/luci-app-mu300/Makefile index fc0c01f1..8c5f3574 100644 --- a/openwrt/luci-app-mu300/Makefile +++ b/openwrt/luci-app-mu300/Makefile @@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk PKG_NAME:=luci-app-mu300 PKG_VERSION:=1.0.1 -PKG_RELEASE:=1 +PKG_RELEASE:=3 PKG_LICENSE:=MIT PKG_MAINTAINER:=MU300 Linux contributors PKGARCH:=all @@ -34,6 +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/* $(INSTALL_DIR) $(1)/usr/lib/lua/luci/i18n $(CP) ./lmo/. $(1)/usr/lib/lua/luci/i18n/ endef @@ -64,6 +65,7 @@ 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 + rm -f /etc/unisoc-modem/usb-boot.conf fi rm -f /tmp/luci-indexcache /tmp/luci-modulecache/* 2>/dev/null /etc/init.d/rpcd restart 2>/dev/null || true diff --git a/openwrt/luci-app-mu300/README.md b/openwrt/luci-app-mu300/README.md index 0d940a03..63651cc9 100644 --- a/openwrt/luci-app-mu300/README.md +++ b/openwrt/luci-app-mu300/README.md @@ -3,6 +3,8 @@ A self-contained LuCI application for Unisoc cellular devices. It provides the dashboard, live radio readings, persistent network/band/cell/EN-DC locks, a guarded AT terminal and an SMS UI. +The Device Management page controls USB role and gadget network policy, and +lists host-side USB network adapters for optional attachment to the LAN bridge. The dashboard follows LuCI's selected language (English, Turkish, or Simplified Chinese) without an extra language package. Its colors follow Aurora's existing @@ -60,6 +62,40 @@ available; a successful marker prevents duplicate application. `early` is deliberately not a user-selectable setting because it is only safe at that exact point in the platform radio sequence. +## USB device management + +USB role defaults to device at every boot. The page can switch it immediately; +checking host auto-apply asks the package's boot worker to reapply host mode +at every boot. On the battery-less F50, the plugin writes the requested role +to sysfs directly: USB management disappears and an attached adapter may need +an externally powered hub. U30 Air uses `mu300-usb` and its charger boost/VBUS +checks. Other hardware can use the sysfs fallback or configure +`unisoc_modem.usb.role_command` with a platform-specific executable that +accepts `host` or `device`. The plugin must not bypass a known platform's +power-safety checks. + +NCM/ECM/RNDIS selection is stored in `/etc/unisoc-modem/usb-boot.conf` only +when "Enable selected protocol" is checked. The optional TF-platform hook in `boot/init` +reads that file from the mounted TF root before gadget enumeration; other OpenWrt builds can +implement the same two-line `mode=...`/`scope=...` contract at their own early +gadget setup point. The plugin itself owns the policy and UI, not the kernel +or gadget. `once` is consumed after a successful boot only if initramfs +recorded that it applied the selection; subsequent boots use the platform's +default NCM. Selecting persistent host mode automatically disables USB +network auto-apply. While the current role is host, network-mode controls are +disabled. The backend validates the same rules regardless of UI state. +The TF boot implementation exposes RNDIS as a single USB configuration with +the ACM console; Windows does not bind a composite RNDIS adapter when the +device offers both RNDIS and NCM configurations. On LAN handoff, the temporary +initramfs IPv4 address is removed from `rndis0` so only `br-lan` owns it. + +USB adapter discovery uses the USB sysfs parent of each network device. On +refresh it attempts to bring discovered devices up. “Add to LAN” adds only a +verified USB adapter to the configured LAN bridge device's UCI port list, +commits `network`, and reloads networking. The selected port is reattached +on USB netdev hotplug and LAN ifup, without a polling daemon or another +network reload. The action is idempotent and only available in host mode. + ## Build Copy this directory alone to `package/luci-app-mu300` in any compatible OpenWrt @@ -70,6 +106,8 @@ runtime. For a source-tree hot install (without an `.ipk`/`.apk`), copy `root/` to `/`, `htdocs/` to `/www/`, and `lmo/` to `/usr/lib/lua/luci/i18n/`; then +make `/etc/init.d/unisoc-modem-ui`, `/usr/libexec/rpcd/mu300dash` and the +`/usr/libexec/unisoc-modem/*` adapters executable; then enable/start `unisoc-modem-ui` and restart `rpcd`. Copying only `root/` leaves the LuCI menu visible but makes `/luci-static/resources/view/mu300/*.js` return HTTP 404. Normal package 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 98f3b844..b73d4cbe 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,11 +25,92 @@ 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 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: { '': {} } }); +var callUsbNetAdd = rpc.declare({ object: 'mu300dash', method: 'usb_net_add', params: [ 'iface' ], expect: { '': {} } }); /* Dashboard translations deliberately ship as a tiny runtime catalog: a * standalone package works in any OpenWrt buildroot without po2lmo or extra * language packages. Chinese remains the source/fallback language. */ var DASH_I18N = { + '设备管理': ['Device management', 'Cihaz yönetimi'], + 'USB 角色': ['USB role', 'USB rolü'], + '当前角色': ['Current role', 'Geçerli rol'], + '切换 USB 角色': ['Switch USB role', 'USB rolünü değiştir'], + '设备模式': ['Device mode', 'Cihaz modu'], + '主机模式': ['Host mode', 'Ana makine modu'], + '开机自动启用主机模式': ['Enable host mode at boot', 'Açılışta ana makine modunu etkinleştir'], + '应用角色': ['Apply role', 'Rolü uygula'], + '主机模式会断开本端口的 USB 网络与串口。F50 没有电池;切换后可能失去管理连接,外接 USB 网卡通常需要自供电 Hub。': ['Host mode disconnects USB networking and serial on this port. F50 has no battery; management may be lost and a USB adapter usually needs a powered hub.', 'Ana makine modu bu bağlantı noktasındaki USB ağını ve seri bağlantıyı keser. F50 bataryasızdır; yönetim bağlantısı kaybolabilir ve USB bağdaştırıcısı genellikle harici güçlü bir hub gerektirir.'], + 'USB 网络模式': ['USB network mode', 'USB ağ modu'], + '网络协议': ['Network protocol', 'Ağ protokolü'], + '生效期限': ['Apply duration', 'Uygulama süresi'], + '仅下次重启': ['Next reboot only', 'Yalnızca sonraki yeniden başlatma'], + '永久生效': ['Permanent', 'Kalıcı'], + '启用所选协议': ['Enable selected protocol', 'Seçilen protokolü etkinleştir'], + '保存,重启后生效': ['Save; apply after reboot', 'Kaydet; yeniden başlatınca uygula'], + 'NCM 为默认模式。Windows 不原生支持 ECM;RNDIS 会改变枚举方式。关闭“启用所选协议”时仅保存选择;选择“仅下次重启”则成功应用一次后恢复默认 NCM。': ['NCM is the default. Windows does not natively support ECM; RNDIS changes enumeration. With Enable selected protocol off, only your choice is saved. Next reboot only applies once, then returns to NCM.', 'NCM varsayılandır. Windows ECM’yi yerel olarak desteklemez; RNDIS aygıt tanımayı değiştirir. Seçilen protokolü etkinleştir kapalıysa yalnızca seçim kaydedilir. Yalnızca sonraki yeniden başlatma bir kez uygulanır, ardından NCM’ye dönülür.'], + '主机模式下不可选择 USB 网络模式;主机开机自启会自动关闭 USB 网络开机自启。': ['USB network mode is unavailable in host mode; host auto-start also disables USB network auto-start.', 'Ana makine modunda USB ağ modu kullanılamaz; ana makine otomatik başlatma USB ağının otomatik başlatmasını da kapatır.'], + 'USB 网卡': ['USB network adapters', 'USB ağ bağdaştırıcıları'], + '仅主机模式可用。刷新时会尝试启用发现的 USB 网卡;添加到 LAN 后将保存到网桥并重新加载网络。': ['Available only in host mode. Refresh brings discovered USB adapters up; adding to LAN saves the bridge and reloads networking.', 'Yalnızca ana makine modunda kullanılabilir. Yenileme bulunan USB bağdaştırıcılarını açar; LAN’a ekleme köprüyü kaydeder ve ağı yeniden yükler.'], + '切换到主机模式后显示 USB 网卡。': ['Switch to host mode to see USB adapters.', 'USB bağdaştırıcılarını görmek için ana makine moduna geçin.'], + '正在扫描 USB 网卡…': ['Scanning USB adapters…', 'USB bağdaştırıcıları taranıyor…'], + '没有发现 USB 网卡。': ['No USB adapters found.', 'USB bağdaştırıcısı bulunamadı.'], + '链路已连接': ['Link connected', 'Bağlantı kuruldu'], + '链路未连接,已尝试启用': ['No link; enable attempted', 'Bağlantı yok; etkinleştirme denendi'], + '已加入 LAN': ['Added to LAN', 'LAN’a eklendi'], + '添加到 LAN': ['Add to LAN', 'LAN’a ekle'], + '确认切换 USB 角色?': ['Switch USB role?', 'USB rolü değiştirilsin mi?'], + '切换主机模式会立即断开 USB 管理连接。F50 没有电池,外设可能需要自供电;请确认有其他管理途径。': ['Host mode immediately disconnects USB management. F50 has no battery and peripherals may need external power; make sure another management path exists.', 'Ana makine modu USB yönetimini hemen keser. F50 bataryasızdır ve çevre birimleri harici güç gerektirebilir; başka bir yönetim yolu olduğundan emin olun.'], + '切回设备模式后 USB 网络和串口会重新枚举。': ['USB networking and serial will re-enumerate in device mode.', 'Cihaz modunda USB ağı ve seri bağlantı yeniden tanınır.'], + '正在切换 USB 角色…': ['Switching USB role…', 'USB rolü değiştiriliyor…'], + '切换请求已接收,USB 连接可能短暂中断。': ['Switch request accepted; the USB connection may briefly disconnect.', 'Geçiş isteği alındı; USB bağlantısı kısa süreli kesilebilir.'], + '管理连接已中断;请重新连接后确认 USB 角色。': ['Management connection lost; reconnect to confirm the USB role.', 'Yönetim bağlantısı kesildi; USB rolünü doğrulamak için yeniden bağlanın.'], + '暂时无法确认角色;请重新连接后刷新页面。': ['Unable to confirm the role yet; reconnect and refresh the page.', 'Rol henüz doğrulanamadı; yeniden bağlanıp sayfayı yenileyin.'], + 'USB 角色已应用': ['USB role applied', 'USB rolü uygulandı'], + '保存 USB 网络模式?': ['Save USB network mode?', 'USB ağ modu kaydedilsin mi?'], + '网络模式将在下次重启时生效,USB 管理连接可能需要重新识别。': ['The network mode applies on the next reboot; USB management may need to reconnect.', 'Ağ modu sonraki yeniden başlatmada uygulanır; USB yönetimi yeniden bağlanabilir.'], + '只保存选择;未启用所选协议,下次重启仍使用默认 NCM。': ['Save the selection only; with the selected protocol disabled, the next boot still uses default NCM.', 'Yalnızca seçim kaydedilir; seçilen protokol etkin değilse sonraki açılışta varsayılan NCM kullanılır.'], + '正在保存 USB 网络设置…': ['Saving USB network settings…', 'USB ağ ayarları kaydediliyor…'], + '设置已保存': ['Settings saved', 'Ayarlar kaydedildi'], + '添加 USB 网卡到 LAN?': ['Add USB adapter to LAN?', 'USB bağdaştırıcısı LAN’a eklensin mi?'], + '这会保存网桥配置并重新加载网络,现有连接可能短暂中断。': ['This saves the bridge configuration and reloads networking; existing connections may briefly drop.', 'Bu işlem köprü yapılandırmasını kaydedip ağı yeniden yükler; mevcut bağlantılar kısa süreli kesilebilir.'], + '正在添加 USB 网卡…': ['Adding USB adapter…', 'USB bağdaştırıcısı ekleniyor…'], + '添加失败:': ['Add failed: ', 'Ekleme başarısız: '], + '切换失败:': ['Switch failed: ', 'Değiştirme başarısız: '], + '保存失败:': ['Save failed: ', 'Kaydetme başarısız: '], + '不可用': ['Unavailable', 'Kullanılamıyor'], + '保存': ['Save', 'Kaydet'], + '添加': ['Add', 'Ekle'], + 'USB role adapter is not executable': ['USB role adapter is not executable', 'USB rol bağdaştırıcısı çalıştırılabilir değil'], + 'USB role adapter failed': ['USB role adapter failed', 'USB rol bağdaştırıcısı başarısız'], + 'Device is the boot default; host auto-apply is the only persistent role': ['Device is the boot default; host auto-apply is the only persistent role', 'Cihaz modu açılış varsayılanıdır; yalnızca ana makine otomatik uygulaması kalıcıdır'], + 'Cannot save USB role policy': ['Cannot save USB role policy', 'USB rol ilkesi kaydedilemiyor'], + 'Cannot disable USB network boot policy': ['Cannot disable USB network boot policy', 'USB ağı açılış ilkesi kapatılamıyor'], + 'Cannot commit USB role policy': ['Cannot commit USB role policy', 'USB rol ilkesi uygulanamıyor'], + 'Cannot save USB network policy': ['Cannot save USB network policy', 'USB ağ ilkesi kaydedilemiyor'], + 'Cannot commit USB network policy': ['Cannot commit USB network policy', 'USB ağ ilkesi uygulanamıyor'], + 'Cannot create USB boot settings directory': ['Cannot create USB boot settings directory', 'USB açılış ayarları dizini oluşturulamıyor'], + 'Cannot write USB boot settings': ['Cannot write USB boot settings', 'USB açılış ayarları yazılamıyor'], + 'Cannot save USB boot settings': ['Cannot save USB boot settings', 'USB açılış ayarları kaydedilemiyor'], + 'Invalid USB role': ['Invalid USB role', 'Geçersiz USB rolü'], + 'Invalid USB network mode': ['Invalid USB network mode', 'Geçersiz USB ağ modu'], + 'Invalid USB network scope': ['Invalid USB network scope', 'Geçersiz USB ağ süresi'], + 'Invalid boot-auto value': ['Invalid boot-auto value', 'Geçersiz otomatik başlatma değeri'], + 'USB role switch is unavailable': ['USB role switch is unavailable', 'USB rol anahtarı kullanılamıyor'], + 'USB role readback did not match': ['USB role readback did not match', 'USB rolü geri okuması eşleşmedi'], + 'USB role switch was refused by platform safety checks': ['USB role switch was refused by platform safety checks', 'USB rol değişimi platform güvenlik denetimi tarafından reddedildi'], + 'USB network mode is unavailable in host role': ['USB network mode is unavailable in host role', 'Ana makine rolünde USB ağ modu kullanılamaz'], + 'Disable host boot-auto before configuring USB network': ['Disable host boot-auto before configuring USB network', 'USB ağını yapılandırmadan önce ana makine otomatik başlatmasını kapatın'], + 'USB host mode is required': ['USB host mode is required', 'USB ana makine modu gerekli'], + 'Not a USB network interface': ['Not a USB network interface', 'USB ağ arayüzü değil'], + 'LAN bridge device section was not found': ['LAN bridge device section was not found', 'LAN köprü aygıtı bölümü bulunamadı'], + 'Cannot bring USB network interface up': ['Cannot bring USB network interface up', 'USB ağ arayüzü etkinleştirilemiyor'], + 'Cannot add interface to LAN bridge': ['Cannot add interface to LAN bridge', 'Arayüz LAN köprüsüne eklenemiyor'], + 'Cannot save LAN bridge': ['Cannot save LAN bridge', 'LAN köprüsü kaydedilemiyor'], + 'Cannot attach USB interface to LAN bridge': ['Cannot attach USB interface to LAN bridge', 'USB arayüzü LAN köprüsüne bağlanamıyor'], + 'Network reload failed': ['Network reload failed', 'Ağ yeniden yüklenemedi'], '链路与流量': ['Link & traffic', 'Bağlantı ve trafik'], '下行速率': ['Download rate', 'İndirme hızı'], '上行速率': ['Upload rate', 'Yükleme hızı'], @@ -903,6 +984,8 @@ return baseclass.extend({ callLockGet: callLockGet, callLockFresh: callLockFresh, callLockSet: callLockSet, callSmsList: callSmsList, callSmsShow: callSmsShow, callSmsSend: callSmsSend, callSmsDel: callSmsDel, callSmsSync: callSmsSync, + 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, uiLanguage: uiLanguage, translate: translate, localize: localize, localizeMenu: localizeMenu, diff --git a/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/device.js b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/device.js new file mode 100644 index 00000000..095e72c9 --- /dev/null +++ b/openwrt/luci-app-mu300/htdocs/luci-static/resources/view/mu300/device.js @@ -0,0 +1,202 @@ +'use strict'; +'require view'; +'require mu300.common as M'; + +return view.extend({ + load: function() { return L.resolveDefault(M.callUsbGet(), {}); }, + render: function(state) { + M.injectCss(); + M.localizeMenu(); + var root = document.createElement('div'); + root.className = 'mud'; + root.innerHTML = ` + +
+
+

USB 角色

+
当前角色--
+
+
+ +
+
主机模式会断开本端口的 USB 网络与串口。F50 没有电池;切换后可能失去管理连接,外接 USB 网卡通常需要自供电 Hub。
+
+
+

USB 网络模式

+
+
+
+
+ +
+
NCM 为默认模式。Windows 不原生支持 ECM;RNDIS 会改变枚举方式。关闭“启用所选协议”时仅保存选择;选择“仅下次重启”则成功应用一次后恢复默认 NCM。
+
+
+
+

USB 网卡

+
仅主机模式可用。刷新时会尝试启用发现的 USB 网卡;添加到 LAN 后将保存到网桥并重新加载网络。
+
+
`; + M.localize(root); + this.root = root; + this.state = state || {}; + this.wire(); + this.paint(); + return root; + }, + q: function(id) { return this.root.querySelector('#mud-usb-' + id); }, + paint: function() { + var s = this.state || {}; + this.q('role-now').textContent = s.role === 'host' ? M.translate('主机模式') : s.role === 'device' ? M.translate('设备模式') : M.translate('不可用'); + this.q('role').querySelector('option[value="host"]').disabled = s.host_supported === 0; + this.q('role').value = s.role === 'host' || s.role_auto ? 'host' : 'device'; + this.q('role-auto').checked = !!s.role_auto; + this.q('net-mode').value = s.net_mode || 'ncm'; + this.q('net-scope').value = s.net_scope || 'permanent'; + this.q('net-auto').checked = !!s.net_auto; + this.updateDisabled(); + this.refreshAdapters(); + }, + updateDisabled: function() { + var host = this.state.role === 'host', hostAuto = this.q('role-auto').checked && this.q('role').value === 'host'; + this.q('role-auto').disabled = this.q('role').value !== 'host'; + if (this.q('role').value !== 'host') this.q('role-auto').checked = false; + var locked = host || !!this.state.role_auto || hostAuto; + [ 'net-mode', 'net-scope', 'net-auto', 'net-apply' ].forEach(function(id) { this.q(id).disabled = locked; }, this); + if (locked) this.q('net-auto').checked = false; + this.q('net-note').textContent = M.translate(locked ? '主机模式下不可选择 USB 网络模式;主机开机自启会自动关闭 USB 网络开机自启。' : 'NCM 为默认模式。Windows 不原生支持 ECM;RNDIS 会改变枚举方式。关闭“启用所选协议”时仅保存选择;选择“仅下次重启”则成功应用一次后恢复默认 NCM。'); + this.q('refresh').disabled = !host; + }, + wire: function() { + var self = this; + this.q('role').addEventListener('change', function() { self.updateDisabled(); }); + this.q('role-auto').addEventListener('change', function() { self.updateDisabled(); }); + this.q('net-mode').addEventListener('change', function() { self.q('net-auto').checked = true; }); + this.q('net-scope').addEventListener('change', function() { self.q('net-auto').checked = true; }); + this.q('role-apply').addEventListener('click', function() { + var role = self.q('role').value, auto = self.q('role-auto').checked ? '1' : '0'; + var warning = role === 'host' ? '切换主机模式会立即断开 USB 管理连接。F50 没有电池,外设可能需要自供电;请确认有其他管理途径。' : '切回设备模式后 USB 网络和串口会重新枚举。'; + M.confirmBox('确认切换 USB 角色?', warning, { danger: role === 'host', okText: '应用' }).then(function(yes) { + if (!yes) return; + var btn = self.q('role-apply'); M.busy(btn, true); + var msg = M.toast('正在切换 USB 角色…', { type: 'busy', timeout: 0 }); + M.callUsbSet('role', role, '', auto).then(function(r) { + M.busy(btn, false); + if (!r || r.ok !== 1) { + msg.update(r && r.ok === 0 ? '切换失败:' + (r.error || '未知错误') : '管理连接已中断;请重新连接后确认 USB 角色。', r && r.ok === 0 ? 'error' : 'info'); + setTimeout(function() { msg.close(); }, 6000); + return; + } + if (r.pending) { + msg.update('切换请求已接收,USB 连接可能短暂中断。', 'info'); + self.watchRole(role, msg, 0); + } else { + msg.update('USB 角色已应用', 'success'); setTimeout(function() { msg.close(); }, 2500); + self.reloadState(); + } + }, function() { + M.busy(btn, false); + msg.update('管理连接已中断;请重新连接后确认 USB 角色。', 'info'); + setTimeout(function() { msg.close(); }, 6000); + }); + }); + }); + this.q('net-apply').addEventListener('click', function() { + var mode = self.q('net-mode').value, scope = self.q('net-scope').value, auto = self.q('net-auto').checked ? '1' : '0'; + M.confirmBox('保存 USB 网络模式?', auto === '1' ? '网络模式将在下次重启时生效,USB 管理连接可能需要重新识别。' : '只保存选择;未启用所选协议,下次重启仍使用默认 NCM。', { okText: '保存' }).then(function(yes) { + if (!yes) return; + var btn = self.q('net-apply'); M.busy(btn, true); + var msg = M.toast('正在保存 USB 网络设置…', { type: 'busy', timeout: 0 }); + L.resolveDefault(M.callUsbSet('net', mode, scope, auto), {}).then(function(r) { + M.busy(btn, false); msg.update(r.ok ? '设置已保存' : '保存失败:' + (r.error || '未知错误'), r.ok ? 'success' : 'error'); + setTimeout(function() { msg.close(); }, 3500); + if (r.ok) self.reloadState(); + }); + }); + }); + this.q('refresh').addEventListener('click', function() { self.refreshAdapters(0); }); + }, + reloadState: function() { + var self = this; + L.resolveDefault(M.callUsbGet(), {}).then(function(s) { if (s.ok) { self.state = s; self.paint(); } }); + }, + watchRole: function(role, msg, attempt) { + var self = this; + setTimeout(function() { + M.callUsbGet().then(function(s) { + if (s && s.ok && s.role === role) { + msg.update('USB 角色已应用', 'success'); + setTimeout(function() { msg.close(); }, 2500); + self.state = s; self.paint(); + return; + } + self.finishRoleWatch(role, msg, attempt); + }, function() { self.finishRoleWatch(role, msg, attempt); }); + }, attempt ? 1000 : 350); + }, + finishRoleWatch: function(role, msg, attempt) { + if (attempt < 4) { this.watchRole(role, msg, attempt + 1); return; } + msg.update('暂时无法确认角色;请重新连接后刷新页面。', 'info'); + setTimeout(function() { msg.close(); }, 5000); + }, + refreshAdapters: function(attempt) { + attempt = attempt || 0; + var self = this, list = this.q('adapters'); + list.replaceChildren(); + if (this.state.role !== 'host') { + list.textContent = M.translate('切换到主机模式后显示 USB 网卡。'); return; + } + var wait = document.createElement('div'); wait.className = 'mud-note mud-booting'; + wait.textContent = M.translate('正在扫描 USB 网卡…'); list.appendChild(wait); + M.busy(this.q('refresh'), true); + L.resolveDefault(M.callUsbNetList(), {}).then(function(r) { + M.busy(self.q('refresh'), false); + list.replaceChildren(); + if (!r.ok || !r.devices || !r.devices.length) { + list.textContent = M.translate('没有发现 USB 网卡。'); + if (self.state.role === 'host' && attempt < 2) + setTimeout(function() { if (self.state.role === 'host') self.refreshAdapters(attempt + 1); }, 1600); + return; + } + r.devices.forEach(function(d) { + var row = document.createElement('div'); row.className = 'mud-device-item'; + var main = document.createElement('div'); main.className = 'mud-device-item-main'; + var dot = document.createElement('i'); dot.className = 'mud-device-dot' + (d.carrier ? ' up' : ''); main.appendChild(dot); + var info = document.createElement('div'); + var name = document.createElement('div'); name.className = 'mud-device-item-name'; name.textContent = d.name; + var sub = document.createElement('div'); sub.className = 'mud-device-item-sub'; sub.textContent = M.translate(d.carrier ? '链路已连接' : '链路未连接,已尝试启用'); + info.appendChild(name); info.appendChild(sub); main.appendChild(info); row.appendChild(main); + var btn = document.createElement('button'); btn.className = 'mud-btn'; btn.textContent = M.translate(d.in_lan ? '已加入 LAN' : '添加到 LAN'); btn.disabled = !!d.in_lan; + btn.addEventListener('click', function() { + M.confirmBox('添加 USB 网卡到 LAN?', '这会保存网桥配置并重新加载网络,现有连接可能短暂中断。', { okText: '添加' }).then(function(yes) { + if (!yes) return; + M.busy(btn, true); var msg = M.toast('正在添加 USB 网卡…', { type: 'busy', timeout: 0 }); + L.resolveDefault(M.callUsbNetAdd(d.name), {}).then(function(a) { + M.busy(btn, false); msg.update(a.ok ? '已添加到 LAN' : '添加失败:' + (a.error || '未知错误'), a.ok ? 'success' : 'error'); + setTimeout(function() { msg.close(); }, 3500); self.refreshAdapters(); + }); + }); + }); + row.appendChild(btn); list.appendChild(row); + }); + }); + } +}); diff --git a/openwrt/luci-app-mu300/lmo/mu300.en.lmo b/openwrt/luci-app-mu300/lmo/mu300.en.lmo index 7ca404b4..263151c7 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 1522000e..d35b23a0 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 ffb05044..5f8b8095 100644 --- a/openwrt/luci-app-mu300/po/en/mu300.po +++ b/openwrt/luci-app-mu300/po/en/mu300.po @@ -20,3 +20,6 @@ msgstr "AT terminal" msgid "适配设置" msgstr "Adapter settings" + +msgid "设备管理" +msgstr "Device management" diff --git a/openwrt/luci-app-mu300/po/tr/mu300.po b/openwrt/luci-app-mu300/po/tr/mu300.po index 76ae86a1..6e9b4d3f 100644 --- a/openwrt/luci-app-mu300/po/tr/mu300.po +++ b/openwrt/luci-app-mu300/po/tr/mu300.po @@ -20,3 +20,6 @@ msgstr "AT terminali" msgid "适配设置" msgstr "Bağdaştırıcı ayarları" + +msgid "设备管理" +msgstr "Cihaz yönetimi" diff --git a/openwrt/luci-app-mu300/root/etc/config/unisoc_modem b/openwrt/luci-app-mu300/root/etc/config/unisoc_modem index bc10b668..03869acd 100644 --- a/openwrt/luci-app-mu300/root/etc/config/unisoc_modem +++ b/openwrt/luci-app-mu300/root/etc/config/unisoc_modem @@ -12,3 +12,10 @@ config core 'main' option usb_device 'usb0' option replay_timeout '90' option state_dir '/etc/unisoc-modem/lock-state.d' + +config device 'usb' + option role_auto '0' + option net_mode 'ncm' + option net_scope 'permanent' + option net_auto '0' + option role_command '' diff --git a/openwrt/luci-app-mu300/root/etc/hotplug.d/iface/90-unisoc-usb-host b/openwrt/luci-app-mu300/root/etc/hotplug.d/iface/90-unisoc-usb-host new file mode 100644 index 00000000..c0de971e --- /dev/null +++ b/openwrt/luci-app-mu300/root/etc/hotplug.d/iface/90-unisoc-usb-host @@ -0,0 +1,5 @@ +#!/bin/sh +# A LAN reload can recreate br-lan after the NIC has already enumerated. +[ "$ACTION" = ifup ] && [ "$INTERFACE" = lan ] || exit 0 +[ -x /usr/libexec/unisoc-modem/device-usb ] || exit 0 +/usr/libexec/unisoc-modem/device-usb net-sync >/dev/null 2>&1 diff --git a/openwrt/luci-app-mu300/root/etc/hotplug.d/net/90-unisoc-usb-host b/openwrt/luci-app-mu300/root/etc/hotplug.d/net/90-unisoc-usb-host new file mode 100644 index 00000000..4eb57d82 --- /dev/null +++ b/openwrt/luci-app-mu300/root/etc/hotplug.d/net/90-unisoc-usb-host @@ -0,0 +1,6 @@ +#!/bin/sh +# A selected host-side USB NIC can enumerate after netifd creates br-lan. +# Reattach on the kernel netdev event, without polling or reloading the LAN. +[ "$ACTION" = add ] || exit 0 +[ -x /usr/libexec/unisoc-modem/device-usb ] || exit 0 +/usr/libexec/unisoc-modem/device-usb net-sync >/dev/null 2>&1 diff --git a/openwrt/luci-app-mu300/root/etc/init.d/unisoc-modem-ui b/openwrt/luci-app-mu300/root/etc/init.d/unisoc-modem-ui index 055cb15e..1ca57e90 100644 --- a/openwrt/luci-app-mu300/root/etc/init.d/unisoc-modem-ui +++ b/openwrt/luci-app-mu300/root/etc/init.d/unisoc-modem-ui @@ -4,6 +4,10 @@ START=95 USE_PROCD=1 start_service() { + # Complete this short policy step before S99 mu300-post decides whether the + # device-mode gadget needs its one boot-time rebind. The normal device path + # performs only local UCI reads; host mode may use a platform power helper. + /usr/libexec/unisoc-modem/device-usb boot 2>&1 | logger -t unisoc-usb procd_open_instance boot-lock-replay procd_set_param command /usr/libexec/unisoc-modem/boot-replay procd_set_param stdout 1 diff --git a/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash b/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash index 7fb75ea0..6f61ed00 100644 --- a/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash +++ b/openwrt/luci-app-mu300/root/usr/libexec/rpcd/mu300dash @@ -325,7 +325,11 @@ do_list() { "sms_show": { "id": "String" }, "sms_send": { "num": "String", "text": "String" }, "sms_delete": { "id": "String", "sim": "String" }, - "sms_sync": { } + "sms_sync": { }, + "usb_get": { }, + "usb_set": { "kind": "String", "value": "String", "scope": "String", "auto": "String" }, + "usb_net_list": { }, + "usb_net_add": { "iface": "String" } } EOF } @@ -371,6 +375,16 @@ 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' ;; + usb_get) run_m usb_get '"$DASH/device-usb" get' ;; + usb_set) + kind=$(inp '@.kind'); value=$(inp '@.value'); scope=$(inp '@.scope'); auto=$(inp '@.auto') + case $kind in + role) run_m usb_set:role '"$DASH/device-usb" set-role "$value" "$auto"' ;; + net) run_m usb_set:net '"$DASH/device-usb" set-net "$value" "$scope" "$auto"' ;; + *) printf '{"ok":0,"error":"unknown USB setting"}\n' ;; + esac ;; + usb_net_list) run_m usb_net_list '"$DASH/device-usb" net-list' ;; + usb_net_add) iface=$(inp '@.iface'); run_m usb_net_add '"$DASH/device-usb" net-add "$iface"' ;; *) printf '{"ok":0,"error":"no such method"}\n' ;; esac ;; diff --git a/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/device-usb b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/device-usb new file mode 100644 index 00000000..8147bb75 --- /dev/null +++ b/openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/device-usb @@ -0,0 +1,256 @@ +#!/bin/sh +# Portable USB-role adapter and persistent gadget-mode policy. +# A platform may provide MU300_USB_ROLE_COMMAND (or UCI usb.role_command) with +# the contract: COMMAND host|device. F50 uses the requested raw role switch; +# other known platforms retain their power-sequencing helper. +set -u +export PATH="$PATH:/opt/mu300/bin:/usr/sbin:/sbin" + +CFG=unisoc_modem.usb +ROLE_FILE=${MU300_USB_ROLE_FILE:-/sys/class/usb_role/25100000.dwc3-role-switch/role} +BOOT_FILE=${MU300_USB_BOOT_FILE:-/etc/unisoc-modem/usb-boot.conf} +NET_CLASS=${MU300_USB_NET_CLASS:-/sys/class/net} +USB_BUS=${MU300_USB_BUS:-/sys/bus/usb/devices} +RESCAN_MARKER=${MU300_USB_RESCAN_MARKER:-/run/unisoc-usb-host-rescan-done} +NETWORK_SERVICE=${MU300_USB_NETWORK_SERVICE:-/etc/init.d/network} +IP=${MU300_USB_IP_BIN:-ip} +get() { uci -q get "$CFG.$1" 2>/dev/null || true; } +put() { uci -q set "$CFG.$1=$2"; } +error() { printf '{"ok":0,"error":"%s"}\n' "$1"; exit 1; } +role_now() { cat "$ROLE_FILE" 2>/dev/null || echo unavailable; } +device_name() { + if [ -n "${MU300_USB_DEVICE:-}" ]; then echo "$MU300_USB_DEVICE" + elif command -v mu300-device >/dev/null 2>&1; then mu300-device + else echo generic; fi +} +role_command() { + cmd=${MU300_USB_ROLE_COMMAND:-$(get role_command)} + if [ -n "$cmd" ]; then + [ -x "$cmd" ] || error 'USB role adapter is not executable' + "$cmd" "$1" || error 'USB role adapter failed' + elif [ "$(device_name)" = f50 ]; then + [ -w "$ROLE_FILE" ] || error 'USB role switch is unavailable' + printf '%s\n' "$1" > "$ROLE_FILE" || error 'USB role switch failed' + elif command -v mu300-usb >/dev/null 2>&1; then + mu300-usb "$1" || error 'USB role switch was refused by platform safety checks' + else + [ -w "$ROLE_FILE" ] || error 'USB role switch is unavailable' + printf '%s\n' "$1" > "$ROLE_FILE" || error 'USB role switch failed' + fi +} +ensure_section() { + uci -q get "$CFG" >/dev/null 2>&1 || uci -q set "$CFG=device" +} +sync_boot_file() { + mode=$(get net_mode); scope=$(get net_scope); auto=$(get net_auto) + [ "$auto" = 1 ] || { rm -f "$BOOT_FILE"; return; } + case $mode in ecm|ncm|rndis) ;; *) error 'Invalid USB network mode' ;; esac + case $scope in once|permanent) ;; *) error 'Invalid USB network scope' ;; esac + mkdir -p "${BOOT_FILE%/*}" || error 'Cannot create USB boot settings directory' + tmp="$BOOT_FILE.$$" + printf 'mode=%s\nscope=%s\n' "$mode" "$scope" > "$tmp" || error 'Cannot write USB boot settings' + chmod 600 "$tmp" + mv "$tmp" "$BOOT_FILE" || error 'Cannot save USB boot settings' +} +usb_net() { + name=$1 + case $name in ''|*[!a-zA-Z0-9_.:-]*) return 1 ;; esac + [ -d "$NET_CLASS/$name" ] || return 1 + sub=$(readlink -f "$NET_CLASS/$name/device/subsystem" 2>/dev/null) + # Configfs gadget interfaces (usb0/rndis0) are not host-side USB NICs. + # Their parent belongs to the gadget bus, even if their names contain usb. + case $sub in */bus/gadget) return 1 ;; esac + case $sub in */bus/usb) return 0 ;; esac + path=$(readlink -f "$NET_CLASS/$name/device" 2>/dev/null) + case $path in */usb[0-9]*/*) return 0 ;; esac + return 1 +} +bridge_section() { + bridge=$(uci -q get unisoc_modem.main.lan_device 2>/dev/null) + [ -n "$bridge" ] || bridge=br-lan + uci -q show network | sed -n "s/^\(network\.[^.]*\)\.name='$bridge'$/\1/p" | head -n1 +} +bridge_has() { + section=$1; name=$2 + ports=$(uci -q get "$section.ports" 2>/dev/null) + case " $ports " in *" $name "*) return 0 ;; esac + return 1 +} +sync_host_nic() { + name=$1 + usb_net "$name" || return 0 + section=$(bridge_section) + [ -n "$section" ] && bridge_has "$section" "$name" || return 0 + bridge=$(uci -q get unisoc_modem.main.lan_device 2>/dev/null) + [ -n "$bridge" ] || bridge=br-lan + "$IP" link set dev "$name" up >/dev/null 2>&1 || return 1 + "$IP" link set dev "$name" master "$bridge" >/dev/null 2>&1 +} +host_nic_present() { + for dir in "$NET_CLASS"/*; do + [ -d "$dir" ] && usb_net "${dir##*/}" && return 0 + done + return 1 +} +start_host_rescan() { + # The first hub may enumerate before its downstream Ethernet dongle has + # power. Run one non-blocking rescan; never hold up boot or poll forever. + ( "$0" host-rescan /dev/null 2>&1 ) & +} +case ${1:-} in + get) + role=$(role_now); role_auto=$(get role_auto); net_auto=$(get net_auto) + mode=$(get net_mode); scope=$(get net_scope) + case $role_auto in 1) ;; *) role_auto=0 ;; esac + case $net_auto in 1) ;; *) net_auto=0 ;; esac + case $mode in ecm|ncm|rndis) ;; *) mode=ncm ;; esac + case $scope in once|permanent) ;; *) scope=permanent ;; esac + [ "$role_auto" = 0 ] || net_auto=0 + [ "$role" != host ] || net_auto=0 + available=1 + if [ "$role" = host ] || [ "$role_auto" = 1 ]; then available=0; fi + host_supported=1 + [ -e "$ROLE_FILE" ] || host_supported=0 + printf '{"ok":1,"role":"%s","role_auto":%s,"host_supported":%s,"net_mode":"%s","net_scope":"%s","net_auto":%s,"net_available":%s}\n' \ + "$role" "$role_auto" "$host_supported" "$mode" "$scope" "$net_auto" "$available" + ;; + set-role) + role=${2:-}; auto=${3:-} + case $role in host|device) ;; *) error 'Invalid USB role' ;; esac + case $auto in 0|1) ;; *) error 'Invalid boot-auto value' ;; esac + [ "$role" = host ] || [ "$auto" = 0 ] || error 'Device is the boot default; host auto-apply is the only persistent role' + [ -e "$ROLE_FILE" ] || error 'USB role switch is unavailable' + # Persist and acknowledge before dropping the USB management link. + # A synchronous role write can tear down the very RPC carrying its + # response, leading the browser to report failure after success. + ensure_section + put role_auto "$auto" || error 'Cannot save USB role policy' + if [ "$role" = host ] && [ "$auto" = 1 ]; then + put net_auto 0 || error 'Cannot disable USB network boot policy' + rm -f "$BOOT_FILE" + fi + uci commit unisoc_modem || error 'Cannot commit USB role policy' + pending=0 + if [ "$(role_now)" != "$role" ]; then + pending=1 + # Give rpcd/uhttpd a brief chance to flush the acknowledgement + # before the USB gadget carrying that response disappears. + ( sleep 0.25; "$0" apply-role "$role" /dev/null 2>&1 ) & + fi + printf '{"ok":1,"pending":%s}\n' "$pending" + ;; + apply-role) + role=${2:-} + case $role in host|device) ;; *) exit 2 ;; esac + [ "$(role_now)" = "$role" ] || role_command "$role" || { + logger -t unisoc-usb "role switch to $role failed" + exit 1 + } + if [ "$role" = host ]; then + start_host_rescan + else + rmdir "$RESCAN_MARKER" 2>/dev/null || true + fi + ;; + set-net) + mode=${2:-}; scope=${3:-}; auto=${4:-} + case $mode in ecm|ncm|rndis) ;; *) error 'Invalid USB network mode' ;; esac + case $scope in once|permanent) ;; *) error 'Invalid USB network scope' ;; esac + case $auto in 0|1) ;; *) error 'Invalid boot-auto value' ;; esac + [ "$(role_now)" != host ] || error 'USB network mode is unavailable in host role' + [ "$(get role_auto)" != 1 ] || error 'Disable host boot-auto before configuring USB network' + ensure_section + put net_mode "$mode" && put net_scope "$scope" && put net_auto "$auto" || error 'Cannot save USB network policy' + sync_boot_file + uci commit unisoc_modem || error 'Cannot commit USB network policy' + printf '{"ok":1}\n' + ;; + boot) + # initramfs applies the selected gadget mode before enumeration. A + # one-shot mode is consumed only after userspace has actually booted. + if [ "$(get role_auto)" = 1 ] && [ "$(get net_auto)" = 1 ]; then + ensure_section + put net_auto 0 && uci commit unisoc_modem + rm -f "$BOOT_FILE" + fi + if [ "$(get net_auto)" = 1 ] && [ "$(get net_scope)" = once ] && + [ -f "${MU300_USB_APPLIED_FILE:-/run/unisoc-usb-net-applied}" ]; then + ensure_section + put net_auto 0 && uci commit unisoc_modem + rm -f "$BOOT_FILE" + fi + if [ "$(get role_auto)" = 1 ]; then + [ "$(role_now)" = host ] || role_command host + start_host_rescan + fi + "$0" net-sync || true + ;; + host-rescan) + sleep "${MU300_USB_RESCAN_DELAY:-2}" + [ "$(role_now)" = host ] || exit 0 + host_nic_present && exit 0 + mkdir "$RESCAN_MARKER" 2>/dev/null || exit 0 + # Reset only the first external hub, once. Re-authorizing its USB + # device causes a fresh downstream port scan without touching the + # DWC3 role or rebooting the device. + for hub in "$USB_BUS"/[0-9]*-[0-9]*; do + [ -f "$hub/bDeviceClass" ] || continue + [ "$(cat "$hub/bDeviceClass" 2>/dev/null)" = 09 ] || continue + [ -w "$hub/authorized" ] || continue + case ${hub##*/} in *.*|*:*) continue ;; esac + printf '0\n' > "$hub/authorized" || exit 1 + printf '1\n' > "$hub/authorized" || exit 1 + logger -t unisoc-usb "rescanned host hub ${hub##*/} after missing USB NIC" + break + done + ;; + net-sync) + # The role readback can lag behind host netdev events. Only physical + # USB NICs explicitly saved as LAN ports are eligible, so attaching + # them does not require waiting for the role sysfs state to settle. + for dir in "$NET_CLASS"/*; do + [ -d "$dir" ] || continue + sync_host_nic "${dir##*/}" || true + done + ;; + net-list) + [ "$(role_now)" = host ] || { printf '{"ok":1,"devices":[],"host_only":1}\n'; exit 0; } + section=$(bridge_section) + printf '{"ok":1,"devices":[' + first=1 + for dir in "$NET_CLASS"/*; do + [ -d "$dir" ] || continue + name=${dir##*/} + usb_net "$name" || continue + "$IP" link set dev "$name" up >/dev/null 2>&1 || true + [ "$first" = 1 ] || printf ',' + first=0 + joined=0 + if [ -n "$section" ] && bridge_has "$section" "$name"; then + joined=1 + sync_host_nic "$name" || true + fi + carrier=$(cat "$dir/carrier" 2>/dev/null); case $carrier in 1) ;; *) carrier=0 ;; esac + printf '{"name":"%s","carrier":%s,"in_lan":%s}' "$name" "$carrier" "$joined" + done + printf ']}\n' + ;; + net-add) + name=${2:-} + [ "$(role_now)" = host ] || error 'USB host mode is required' + usb_net "$name" || error 'Not a USB network interface' + section=$(bridge_section) + [ -n "$section" ] || error 'LAN bridge device section was not found' + "$IP" link set dev "$name" up || error 'Cannot bring USB network interface up' + if ! bridge_has "$section" "$name"; then + uci -q add_list "$section.ports=$name" || error 'Cannot add interface to LAN bridge' + uci commit network || error 'Cannot save LAN bridge' + "$NETWORK_SERVICE" reload >/dev/null 2>&1 || error 'Network reload failed' + fi + bridge=$(uci -q get unisoc_modem.main.lan_device 2>/dev/null) + [ -n "$bridge" ] || bridge=br-lan + "$IP" link set dev "$name" master "$bridge" >/dev/null 2>&1 || error 'Cannot attach USB interface to LAN bridge' + printf '{"ok":1}\n' + ;; + *) echo "usage: $0 {get|set-role ROLE AUTO|apply-role ROLE|set-net MODE SCOPE AUTO|boot|host-rescan|net-sync|net-list|net-add IFACE}" >&2; exit 2 ;; +esac 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 93eb4576..4fd9f783 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 @@ -60,7 +60,7 @@ "admin/modem/settings": { "title": "适配设置", - "order": 4, + "order": 5, "action": { "type": "view", "path": "mu300/settings" @@ -68,5 +68,11 @@ "depends": { "acl": [ "luci-app-mu300" ] } + }, + "admin/modem/device": { + "title": "设备管理", + "order": 4, + "action": { "type": "view", "path": "mu300/device" }, + "depends": { "acl": [ "luci-app-mu300" ] } } } diff --git a/openwrt/overlay/etc/hotplug.d/iface/10-mu300-usb b/openwrt/overlay/etc/hotplug.d/iface/10-mu300-usb index ccd863f8..d5aa82f0 100755 --- a/openwrt/overlay/etc/hotplug.d/iface/10-mu300-usb +++ b/openwrt/overlay/etc/hotplug.d/iface/10-mu300-usb @@ -7,6 +7,29 @@ rm -f /run/mu300-early-udhcpd.pid # netifd has transferred usb0 to br-lan without changing the management IP or # DHCP lease. +# With the RNDIS-only gadget, initramfs gives rndis0 the LAN address to serve +# early DHCP. netifd can retain that address after enslaving rndis0, creating +# two equal 192.168.77.0/24 routes; replies then leave through the wrong +# device and the Windows host cannot even ping br-lan. Keep the IP on br-lan +# only, after netifd has installed it. This also handles an NCM handoff if +# that driver ever retains its early address. +bridge_ip=$(ip -4 -o addr show dev br-lan 2>/dev/null | awk 'NR == 1 { print $4 }') +if [ -n "$bridge_ip" ]; then + for nic in usb0 rndis0; do + ip -o link show dev "$nic" 2>/dev/null | grep -q 'master br-lan' || continue + ip -4 -o addr show dev "$nic" 2>/dev/null | grep -Fq "inet $bridge_ip " || continue + ip addr del "$bridge_ip" dev "$nic" 2>/dev/null || true + done +fi + +# On an already-installed rootfs, firstboot's bridge UCI section predates a +# later switch to RNDIS. Reattach its gadget netdev after every LAN ifup, not +# only the first boot; this also covers a network reload from Device Management. +if [ -e /sys/class/net/rndis0 ]; then + ip link set rndis0 master br-lan 2>/dev/null + ip link set rndis0 up 2>/dev/null +fi + # The final NCM endpoint health check/rebind is a procd one-shot in mu300-post. # A detached child launched by hotplug can be reaped with the hotplug process; # keep this hook limited to the deterministic DHCP handoff above. diff --git a/openwrt/overlay/etc/init.d/mu300-post b/openwrt/overlay/etc/init.d/mu300-post index 7ecf1a07..761121e0 100755 --- a/openwrt/overlay/etc/init.d/mu300-post +++ b/openwrt/overlay/etc/init.d/mu300-post @@ -20,12 +20,18 @@ start_service() { # counts grow and dnsmasq logs DHCPOFFER, but Windows receives nothing. # One tracked 100 ms rebind after br-lan/dnsmasq are ready restores TX and # makes Windows renew the same reserved lease without a physical replug. - procd_open_instance usb-ready - procd_set_param command /opt/mu300/bin/mu300-usb-reset --fast-run - procd_set_param oneshot 1 - procd_set_param stdout 1 - procd_set_param stderr 1 - procd_close_instance + if [ "$(cat /sys/class/usb_role/25100000.dwc3-role-switch/role 2>/dev/null)" != host ]; then + # netifd may have emitted lan/ifup before the gadget's early address + # became visible to hotplug. Repeat the idempotent LAN handoff here; + # do not wait or poll for readiness. + ACTION=ifup INTERFACE=lan /etc/hotplug.d/iface/10-mu300-usb + procd_open_instance usb-ready + procd_set_param command /opt/mu300/bin/mu300-usb-reset --fast-run + procd_set_param oneshot 1 + procd_set_param stdout 1 + procd_set_param stderr 1 + procd_close_instance + fi # U30 Air exposes a second function on some kernels. Keep it in the LAN; # PDP and IPv4/IPv6 lease changes themselves never re-enumerate the gadget. diff --git a/openwrt/overlay/etc/uci-defaults/90-mu300 b/openwrt/overlay/etc/uci-defaults/90-mu300 index 8dafba52..7b305f5e 100755 --- a/openwrt/overlay/etc/uci-defaults/90-mu300 +++ b/openwrt/overlay/etc/uci-defaults/90-mu300 @@ -83,6 +83,9 @@ dev=$(uci -q show network | sed -n "s/^network\.\(@device\[[0-9]*\]\)\.name='br- if [ -n "$dev" ]; then uci -q delete network.$dev.ports uci add_list network.$dev.ports='usb0' + # RNDIS is a second USB configuration on Windows. It appears only when + # selected in the initramfs; without it in br-lan, Windows has no LAN. + [ -e /sys/class/net/rndis0 ] && uci add_list network.$dev.ports='rndis0' # Do not wait for the wireless bridge member before creating the wired LAN. uci set network.$dev.bridge_empty='1' fi diff --git a/rootfs/overlay/opt/mu300/bin/mu300-usb-reset b/rootfs/overlay/opt/mu300/bin/mu300-usb-reset index cd94213b..805c68b2 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-usb-reset +++ b/rootfs/overlay/opt/mu300/bin/mu300-usb-reset @@ -9,6 +9,10 @@ set -u export PATH="$PATH:/opt/mu300/busybox-bin:/usr/sbin:/sbin" G=${MU300_GADGET:-/sys/kernel/config/usb_gadget/linux} +# A gadget rebind is meaningless in host role and could race a deliberate +# boot-time role switch. Leave the host controller and its attached NICs alone. +[ "$(cat /sys/class/usb_role/25100000.dwc3-role-switch/role 2>/dev/null)" = host ] && exit 0 + if [ "${1:-}" = --ready ]; then setsid "$0" --fast-run /dev/null 2>&1 & exit 0 @@ -44,8 +48,15 @@ if [ "${1:-}" = --fast-run ]; then echo "$udc" > "$G/UDC" 2>/dev/null && [ "$(cat "$G/UDC" 2>/dev/null)" = "$udc" ] && break n=$((n + 1)); /opt/mu300/bin/busybox usleep 20000 2>/dev/null || sleep 1 done - ip link set usb0 master br-lan 2>/dev/null || true - ip link set usb0 up 2>/dev/null || ifconfig usb0 up 2>/dev/null + for nic in usb0 rndis0; do + [ -e "/sys/class/net/$nic" ] || continue + ip link set "$nic" master br-lan 2>/dev/null || true + ip link set "$nic" up 2>/dev/null || ifconfig "$nic" up 2>/dev/null + done + # The second enumeration can happen after lan/ifup. Complete the same + # handoff once more so the initramfs IP is not left on a bridge port. + ACTION=ifup INTERFACE=lan /etc/hotplug.d/iface/10-mu300-usb + cut -d ' ' -f 1 /proc/uptime > /run/mu300-usb-rebind-done logger -t mu300-usb "fast gadget rebind completed on $udc" exit 0 fi diff --git a/tests/test_mu300_i18n.py b/tests/test_mu300_i18n.py index 3889fb49..d19daae1 100644 --- a/tests/test_mu300_i18n.py +++ b/tests/test_mu300_i18n.py @@ -24,7 +24,7 @@ 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'): + for name in ('home', 'at', 'locks', 'sms', 'settings', 'device'): self.assertTrue((PACKAGE / f'htdocs/luci-static/resources/view/mu300/{name}.js').is_file()) def test_global_menu_catalogs_are_complete(self): diff --git a/tests/test_usb_management.py b/tests/test_usb_management.py new file mode 100644 index 00000000..8a8d2729 --- /dev/null +++ b/tests/test_usb_management.py @@ -0,0 +1,260 @@ +"""USB device-management policy and host-only LAN attachment.""" +import json +import time +import unittest +from helpers import ShellTest, TOP + + +USB = TOP / 'openwrt/luci-app-mu300/root/usr/libexec/unisoc-modem/device-usb' + + +class USBManagement(ShellTest): + def setUp(self): + super().setUp() + self.role = self.tmp / 'role' + self.role.write_text('device\n') + self.boot_file = self.tmp / 'usb-boot.conf' + self.applied = self.tmp / 'applied' + self.net_class = self.tmp / 'net' + self.net_class.mkdir() + self.usb_bus = self.tmp / 'usb-bus' + self.usb_bus.mkdir() + self.rescan_marker = self.tmp / 'rescan-done' + self.stub('uci', ''' +cmd=$1; [ "$cmd" = -q ] && { shift; cmd=$1; }; shift +case "$cmd" in + get) + case "$1" in + unisoc_modem.usb) echo device ;; + unisoc_modem.usb.*) key=${1##*.}; [ -f "$STUBLOG/uci.$key" ] && cat "$STUBLOG/uci.$key" ;; + unisoc_modem.main.lan_device) echo br-lan ;; + network.*.ports) [ -f "$STUBLOG/ports" ] && cat "$STUBLOG/ports" ;; + esac ;; + set) + key=${1%%=*}; val=${1#*=}; printf '%s' "$val" > "$STUBLOG/uci.${key##*.}" ;; + show) [ "$1" = network ] && echo "network.@device[0].name='br-lan'" ;; + add_list) printf '%s' "${1##*=}" > "$STUBLOG/ports" ;; + commit) echo "$1" >> "$STUBLOG/commits" ;; +esac +''') + helper = self.tmp / 'safe-role' + helper.write_text('#!/bin/sh\nprintf "%s\\n" "$1" > "$MU300_USB_ROLE_FILE"\n') + helper.chmod(0o755) + self.helper = helper + reload_script = self.tmp / 'network' + reload_script.write_text('#!/bin/sh\nprintf "%s\\n" "$1" >> "$STUBLOG/reloads"\n') + reload_script.chmod(0o755) + self.reload_script = reload_script + self.stub('ip', 'printf "%s\\n" "$*" >> "$STUBLOG/ip-calls"') + + def call_usb(self, shell, *args): + return self.script(shell, USB, *args, + MU300_USB_ROLE_FILE=self.role, + MU300_USB_BOOT_FILE=self.boot_file, + MU300_USB_APPLIED_FILE=self.applied, + MU300_USB_NET_CLASS=self.net_class, + MU300_USB_BUS=self.usb_bus, + MU300_USB_RESCAN_MARKER=self.rescan_marker, + MU300_USB_RESCAN_DELAY='0', + MU300_USB_ROLE_COMMAND=self.helper, + MU300_USB_NETWORK_SERVICE=self.reload_script, + MU300_USB_IP_BIN=self.stubs / 'ip') + + def wait_text(self, path, value): + for _ in range(30): + if path.exists() and path.read_text().strip() == value: + return + time.sleep(0.02) + self.assertEqual(path.read_text().strip() if path.exists() else None, value) + + def test_host_auto_disables_usb_network_auto_and_blocks_changes(self): + for shell in self.each_shell(): + self.role.write_text('device\n') + (self.tmp / 'uci.role_auto').write_text('0') + self.call_usb(shell, 'set-net', 'ecm', 'permanent', '1') + self.assertTrue(self.boot_file.exists()) + response = self.call_usb(shell, 'set-role', 'host', '1') + self.assertEqual(json.loads(response.stdout)['ok'], 1, response.stderr) + self.wait_text(self.role, 'host') + self.assertEqual((self.tmp / 'uci.net_auto').read_text(), '0') + self.assertFalse(self.boot_file.exists()) + denied = self.call_usb(shell, 'set-net', 'rndis', 'once', '1') + self.assertEqual(json.loads(denied.stdout)['ok'], 0) + + def test_once_consumed_only_after_boot_marker(self): + for shell in self.each_shell(): + self.role.write_text('device\n') + (self.tmp / 'uci.role_auto').write_text('0') + self.applied.unlink(missing_ok=True) + self.call_usb(shell, 'set-net', 'rndis', 'once', '1') + self.assertIn('mode=rndis', self.boot_file.read_text()) + self.call_usb(shell, 'boot') + self.assertTrue(self.boot_file.exists()) + self.applied.touch() + self.call_usb(shell, 'boot') + self.assertFalse(self.boot_file.exists()) + self.assertEqual((self.tmp / 'uci.net_auto').read_text(), '0') + + def test_f50_host_uses_explicit_role_adapter(self): + for shell in self.each_shell(): + self.role.write_text('device\n') + result = self.script(shell, USB, 'set-role', 'host', '1', + MU300_USB_ROLE_FILE=self.role, + MU300_USB_DEVICE='f50', + MU300_USB_ROLE_COMMAND=self.helper, + MU300_USB_BOOT_FILE=self.boot_file, + MU300_USB_NET_CLASS=self.net_class, + MU300_USB_BUS=self.usb_bus, + MU300_USB_RESCAN_MARKER=self.rescan_marker, + MU300_USB_RESCAN_DELAY='0') + self.assertEqual(json.loads(result.stdout)['ok'], 1) + self.wait_text(self.role, 'host') + status = self.script(shell, USB, 'get', MU300_USB_ROLE_FILE=self.role, + MU300_USB_DEVICE='f50', MU300_USB_BOOT_FILE=self.boot_file) + self.assertEqual(json.loads(status.stdout)['host_supported'], 1) + self.role.write_text('device\n') + raw = self.script(shell, USB, 'set-role', 'host', '0', + MU300_USB_ROLE_FILE=self.role, + MU300_USB_DEVICE='f50', MU300_USB_BOOT_FILE=self.boot_file) + self.assertEqual(json.loads(raw.stdout)['ok'], 1) + self.wait_text(self.role, 'host') + + def test_async_role_readback_is_pending_not_a_false_failure(self): + slow = self.tmp / 'slow-role' + slow.write_text('#!/bin/sh\nprintf "%s\\n" "$1" > "$STUBLOG/role-request"\n') + slow.chmod(0o755) + for shell in self.each_shell(): + self.role.write_text('device\n') + result = self.script(shell, USB, 'set-role', 'host', '1', + MU300_USB_ROLE_FILE=self.role, + MU300_USB_ROLE_COMMAND=slow, + MU300_USB_BOOT_FILE=self.boot_file, + MU300_USB_NET_CLASS=self.net_class, + MU300_USB_BUS=self.usb_bus, + MU300_USB_RESCAN_MARKER=self.rescan_marker, + MU300_USB_RESCAN_DELAY='0') + self.assertEqual(json.loads(result.stdout), {'ok': 1, 'pending': 1}) + self.assertEqual((self.tmp / 'uci.role_auto').read_text(), '1') + self.wait_text(self.tmp / 'role-request', 'host') + + def test_host_only_usb_adapter_list_and_idempotent_bridge_add(self): + usbdev = self.tmp / 'usb1' / '1-1' + usbdev.mkdir(parents=True) + nic = self.net_class / 'eth0' + nic.mkdir() + (nic / 'device').symlink_to(usbdev, target_is_directory=True) + (nic / 'carrier').write_text('1\n') + other = self.net_class / 'sipa_eth0' + other.mkdir() + (other / 'carrier').write_text('1\n') + gadget = self.net_class / 'rndis0' + gadget.mkdir() + gadget_parent = self.tmp / 'gadget.0' + gadget_parent.mkdir() + (gadget / 'device').symlink_to(gadget_parent, target_is_directory=True) + gadget_bus = self.tmp / 'bus' / 'gadget' + gadget_bus.mkdir(parents=True) + (gadget_parent / 'subsystem').symlink_to(gadget_bus, target_is_directory=True) + for shell in self.each_shell(): + (self.tmp / 'ports').unlink(missing_ok=True) + (self.tmp / 'reloads').unlink(missing_ok=True) + self.role.write_text('device\n') + denied = self.call_usb(shell, 'net-add', 'eth0') + self.assertEqual(json.loads(denied.stdout)['ok'], 0) + self.role.write_text('host\n') + listed = json.loads(self.call_usb(shell, 'net-list').stdout) + self.assertEqual([d['name'] for d in listed['devices']], ['eth0']) + self.assertEqual(listed['devices'][0]['carrier'], 1) + added = self.call_usb(shell, 'net-add', 'eth0') + self.assertEqual(json.loads(added.stdout)['ok'], 1, + added.stdout + added.stderr + (self.tmp / 'ip-calls').read_text()) + self.assertEqual(json.loads(self.call_usb(shell, 'net-add', 'eth0').stdout)['ok'], 1) + self.assertEqual((self.tmp / 'reloads').read_text().splitlines(), ['reload']) + self.assertEqual(json.loads(self.call_usb(shell, 'net-add', 'sipa_eth0').stdout)['ok'], 0) + self.assertEqual(json.loads(self.call_usb(shell, 'net-add', 'rndis0').stdout)['ok'], 0) + + def test_selected_usb_nic_reattaches_without_network_reload(self): + usbdev = self.tmp / 'usb1' / '1-1' + usbdev.mkdir(parents=True) + nic = self.net_class / 'eth0' + nic.mkdir() + (nic / 'device').symlink_to(usbdev, target_is_directory=True) + (self.tmp / 'ports').write_text('usb0 eth0') + for shell in self.each_shell(): + (self.tmp / 'ip-calls').unlink(missing_ok=True) + (self.tmp / 'reloads').unlink(missing_ok=True) + self.role.write_text('host\n') + self.call_usb(shell, 'net-sync') + calls = (self.tmp / 'ip-calls').read_text() + self.assertIn('link set dev eth0 up', calls) + self.assertIn('link set dev eth0 master br-lan', calls) + self.assertFalse((self.tmp / 'reloads').exists()) + + def test_missing_host_nic_triggers_one_hub_rescan(self): + hub = self.usb_bus / '1-1' + hub.mkdir() + (hub / 'bDeviceClass').write_text('09\n') + (hub / 'authorized').write_text('1\n') + for shell in self.each_shell(): + self.role.write_text('host\n') + self.rescan_marker.rmdir() if self.rescan_marker.exists() else None + self.call_usb(shell, 'host-rescan') + self.assertEqual((hub / 'authorized').read_text(), '1\n') + self.assertTrue(self.rescan_marker.exists()) + (hub / 'authorized').write_text('sentinel\n') + self.call_usb(shell, 'host-rescan') + self.assertEqual((hub / 'authorized').read_text(), 'sentinel\n') + + +class USBIntegration(unittest.TestCase): + def test_tf_early_policy_precedes_gadget_enumeration(self): + init = (TOP / 'boot/init').read_text() + self.assertLess(init.index('stage=sd-scan dev='), + init.index('[ "$root_mounted" = 1 ] && read_usb_boot_policy\nsetup_usb_gadget')) + 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')) + self.assertIn('/disk/openwrt/etc/unisoc-modem/usb-boot.conf', init) + self.assertIn('/run/unisoc-usb-net-applied', init) + + def test_rndis_is_single_configuration_with_own_revision_and_early_dhcp(self): + init = (TOP / 'boot/init').read_text() + self.assertIn('[ -z "$netfunc$rndis" ] && mkdir -p "$g/functions/$f.usb0"', init) + self.assertNotIn('cdc=c.2', init) + self.assertIn('echo 0x0302 > "$g/bcdDevice"', init) + self.assertIn('early_net=rndis0', init) + self.assertIn('interface $early_net', init) + reset = (TOP / 'rootfs/overlay/opt/mu300/bin/mu300-usb-reset').read_text() + self.assertIn('for nic in usb0 rndis0', reset) + self.assertIn('ACTION=ifup INTERFACE=lan /etc/hotplug.d/iface/10-mu300-usb', reset) + self.assertIn('/run/mu300-usb-rebind-done', reset) + + def test_rndis_enters_lan_on_firstboot_and_reload(self): + first = (TOP / 'openwrt/overlay/etc/uci-defaults/90-mu300').read_text() + hotplug = (TOP / 'openwrt/overlay/etc/hotplug.d/iface/10-mu300-usb').read_text() + self.assertIn("uci add_list network.$dev.ports='rndis0'", first) + self.assertIn('ip link set rndis0 master br-lan', hotplug) + + def test_host_boot_cannot_be_undone_by_gadget_rebind(self): + ui = (TOP / 'openwrt/luci-app-mu300/root/etc/init.d/unisoc-modem-ui').read_text() + post = (TOP / 'openwrt/overlay/etc/init.d/mu300-post').read_text() + reset = (TOP / 'rootfs/overlay/opt/mu300/bin/mu300-usb-reset').read_text() + self.assertIn('/usr/libexec/unisoc-modem/device-usb boot', ui) + self.assertIn('!= host', post) + self.assertIn('= host ] && exit 0', reset) + + def test_host_nic_hotplug_and_build_inventory(self): + pkg = TOP / 'openwrt/luci-app-mu300/root/etc/hotplug.d' + net = (pkg / 'net/90-unisoc-usb-host').read_text() + iface = (pkg / 'iface/90-unisoc-usb-host').read_text() + self.assertIn('device-usb net-sync', net) + self.assertIn('device-usb net-sync', iface) + for script in ('openwrt/build-rootfs.sh', 'tools/build-openwrt-tf-magisk.sh', 'tools/make-release.sh'): + content = (TOP / script).read_text() + self.assertIn('90-unisoc-usb-host', content) + + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/tools/build-openwrt-tf-magisk.sh b/tools/build-openwrt-tf-magisk.sh index 66ed51e6..f7c3677b 100755 --- a/tools/build-openwrt-tf-magisk.sh +++ b/tools/build-openwrt-tf-magisk.sh @@ -66,6 +66,10 @@ for f in ./lib/netifd/proto/mu300cell.sh ./lib/netifd/proto/mu300cell-v6.sh \ ./etc/init.d/mu300-smsd ./etc/sysctl.d/99-mu300-console.conf \ ./usr/share/luci/menu.d/luci-app-mu300.json \ ./www/luci-static/resources/view/mu300/home.js \ + ./www/luci-static/resources/view/mu300/device.js \ + ./usr/libexec/unisoc-modem/device-usb \ + ./etc/hotplug.d/net/90-unisoc-usb-host \ + ./etc/hotplug.d/iface/90-unisoc-usb-host \ ./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 \ diff --git a/tools/make-release.sh b/tools/make-release.sh index f42b47db..50051d1f 100755 --- a/tools/make-release.sh +++ b/tools/make-release.sh @@ -81,6 +81,8 @@ MU300_INPUTS="$IN" MU300_LUCI_PLUGIN_SRC="$TOP/openwrt/luci-app-mu300" MU300_VER sh "$TOP/openwrt/build-rootfs.sh" mu300-openwrt-release.tar.gz >/dev/null mv "$TOP/openwrt/mu300-openwrt-release.tar.gz" "$D/mu300-openwrt-rootfs.tar.gz" for f in ./usr/share/luci/menu.d/luci-app-mu300.json ./www/luci-static/resources/view/mu300/home.js \ + ./www/luci-static/resources/view/mu300/device.js ./usr/libexec/unisoc-modem/device-usb \ + ./etc/hotplug.d/net/90-unisoc-usb-host ./etc/hotplug.d/iface/90-unisoc-usb-host \ ./etc/init.d/unisoc-modem-ui ./usr/lib/lua/luci/i18n/mu300.en.lmo ./usr/lib/lua/luci/i18n/mu300.tr.lmo; do tar -tzf "$D/mu300-openwrt-rootfs.tar.gz" "$f" >/dev/null || { echo "release OpenWrt rootfs missing $f" >&2; exit 1;