Add IMS/VoLTE/VoWiFi stack and fix Dual-SIM cellular mobile data

- Add Qualcomm MCFG .mbn parser and profile store (bananarchy-imsctl), QMI_PDC/QMI_IMSDCM VoLTE daemon (bananarchy-imsd), and SWu IKEv2/EAP-AKA/ESP/SIP/AMR VoWiFi engine (bananarchy-vowifi) with disabled-by-default (auto) 4G-only activation and xmodem/xfiles/xcallscreen UI support.

- Add libmm-wds-bind.so QMI_SERVICE_WDS PRIMARY subscription binding (including serialized post-mux/data-port binding), msm-modem-uim-selection DSDS PS-domain handoff, cs-only dial pause/restore (10-bananarchy-dpm.sh), cold-boot mmcli -K recovery, and networks.so connection.autoconnect no race fix.

- Add offline test suites (test-ims-mbn.py, test-imsd-volte.py, test-vowifi-swu-ims.py, test-lte-mobile-data.py), update docs (CHANGELOG.md Unreleased, README.md, MANUAL.md, AGENTS.md), and pin rebuilt 4-target image SHA-256 hashes in scripts/check-rebuild.sh.
This commit is contained in:
Luxferre committed 2026-11-20 19:18:58 +02:00
1 parent 03bc80f267
commit c40ec932de
65 files changed
+11904 -117

No files matched your search

+8 -1
View File
@@ -89,10 +89,17 @@ Keep this file short. Full details live in `README.md`, `MANUAL.md`, `SDK.md`, `
`scripts/test-dns-resolution.py`. GPS resolves through `bananarchy-gps-modem.sh`, never `mmcli -m any`. `scripts/test-dns-resolution.py`. GPS resolves through `bananarchy-gps-modem.sh`, never `mmcli -m any`.
- Keep idle and autostart daemons as compiled C ARM ELF binaries (`bananarchy-lid`, `bananarchy-cover-idle`, - Keep idle and autostart daemons as compiled C ARM ELF binaries (`bananarchy-lid`, `bananarchy-cover-idle`,
`bananarchy-volume-keys`, `bananarchy-dsds`, `bananarchy-modemmonitor`, `bananarchy-soundmonitor`, `bananarchy-volume-keys`, `bananarchy-dsds`, `bananarchy-modemmonitor`, `bananarchy-soundmonitor`,
`bananarchy-notifmonitor`, `bananarchy-run-aligned`, `bananarchy-session-loop`), not Python or `/bin/sh` loops. `bananarchy-notifmonitor`, `bananarchy-run-aligned`, `bananarchy-session-loop`, `bananarchy-imsctl`,
`bananarchy-imsd`) alongside `bananarchy-vowifi`, not Python or `/bin/sh` loops.
Preserve `/run/bananarchy/lid-state`, the cover socket protocol, `FBIOBLANK`, cover diagnostics, Preserve `/run/bananarchy/lid-state`, the cover socket protocol, `FBIOBLANK`, cover diagnostics,
`should_skip_while_dark()`, `bananarchy-dsds --sig-hysteresis`, `scripts/test-cover-idle.py`, `should_skip_while_dark()`, `bananarchy-dsds --sig-hysteresis`, `scripts/test-cover-idle.py`,
`scripts/test-dsds-daemon.py`, and `scripts/test-standby-power-policy.py`. `scripts/test-dsds-daemon.py`, and `scripts/test-standby-power-policy.py`.
- Keep IMS, VoLTE, VoWiFi, and mobile data (`wwan0`) invariants: `/etc/bananarchy/ims.conf` must ship with `volte_mode=auto` and
`vowifi_mode=auto` (disabled at 0% idle CPU unless connected to a strictly **4G-only** network or explicitly
enabled by the user), `QMI_IMSDCM` (`0x0302`) must stay closed at idle (`close_imsdcm()` / `ensure_imsdcm()`) alongside dedicated QRTR socket isolation + `g_pdc_loaded_id` deduplication in
`bananarchy-imsd`, `bananarchy-ims-bearer.sh` must remain isolated from `wwan0`, `QMI_UIM` APDU lock serialization in `bananarchy-vowifi`, emergency calls (`112`/`911`) prioritizing
cellular CS/VoLTE before VoWiFi fallback, Duress Mode gating in `bananarchy-imsctl`/`modem.so`/`files.so`, `/etc/init.d/modemmanager` and `msm-modem-uim-selection` preloading `libmm-wds-bind.so` (`PRIMARY` `QMI_WDS` binding without calling `QMI_DSD 0x004E`), `mobile-data-prep` / `10-bananarchy-dpm.sh` `restore-dsds` handling sticky `cs-only` Dual-SIM pausing, and
`scripts/test-{lte-mobile-data,ims-mbn,imsd-volte,vowifi-swu-ims}.py` passing under `scripts/check-rebuild.sh`.
- Keep standby battery invariants from `0012-msm8909-standby-wifi-wcd-panel-ldo-bms.patch` and - Keep standby battery invariants from `0012-msm8909-standby-wifi-wcd-panel-ldo-bms.patch` and
`bananarchy-power-policy.conf`: `CPU_RPM_SLEEP=0`, `CPU_L2_SLEEP=0`, `MODEM_DRX_MODE=0`, `WIFI_LISTEN_INTERVAL=8`, `bananarchy-power-policy.conf`: `CPU_RPM_SLEEP=0`, `CPU_L2_SLEEP=0`, `MODEM_DRX_MODE=0`, `WIFI_LISTEN_INTERVAL=8`,
`WIFI_STANDBY_RAT=gsm`, `msm8916-wcd-analog` `s2` gating, `pm8916_bms_vm` `screen_off` S3 OCV mode, `sdhci-msm` `WIFI_STANDBY_RAT=gsm`, `msm8916-wcd-analog` `s2` gating, `pm8916_bms_vm` `screen_off` S3 OCV mode, `sdhci-msm`
+26
View File
@@ -12,6 +12,32 @@ Release versions follow the `<year-letter><MM><DD>` format (where `2026` is `a`,
--- ---
## Unreleased
### Cellular PS attach, Dual-SIM QMI WDS subscription binding (`libmm-wds-bind.so`), and mobile data (`wwan0`) fixes across all targets
- **QMI `WDS` subscription binding (`src/bananarchy-daemons/mm-wds-bind.c`, `libmm-wds-bind.so`, `/etc/init.d/modemmanager`)**: added a lightweight C `LD_PRELOAD` library preloaded by `ModemManager` and `msm-modem-uim-selection` (`run_wds_qmicli`) that hooks `qmi_device_allocate_client_finish()`, `qmi_client_wds_bind_mux_data_port()`, and `qmi_client_wds_bind_data_port()` to serialize `QMI_SUBSCRIPTION_TYPE_PRIMARY` (`1`, overrideable via `BANANARCHY_WDS_SUBSCRIPTION`) binding on every `QMI_SERVICE_WDS` (`1`) client both at allocation and after `Bind Mux Data Port` (`0x00A2`) / `Bind Data Port` (`0x0089`), preventing sticky KaiOS `SECONDARY` EFS `DDS` state (`QMI_DSD 0x004F == 2`) from resetting or routing `WDS Start Network` or `3gpp` profile lookups to the unprovisioned secondary subscription.
- **DSDS PS-domain handoff, APN sync, autoconnect race fix, cold-boot MM recovery, and safe `cs-only` dial pause/restore (`msm-modem-uim-selection`, `10-bananarchy-dpm.sh`, `networks_plugin.cpp`)**: updated `ensure_dsds_nas_registration()` (`QrtrTransport` `NAS` + `DSD`) to lock `Secondary GW` (`sub=1`) to GSM/`cs-only`, promote `Primary GW` (`sub=0`) to `cs-ps` + `gsm,umts,lte` (unless `rat_parked`) and `PS attach`, and bind `QMI_DSD` to `PRIMARY` (`data_enabled=1`) without triggering `QMI_DSD 0x004E`; updated `sync_wds_apn()` to populate empty `Profile [1]` alongside `attach_pdn`/`def_prof` directly via `QMI_WDS` while skipping `ims`/`sos` and removing `mmcli --3gpp-set-initial-eps-bearer-settings` calls (which triggered asynchronous 3GPP detaches before dial); added ANSI-safe `mmcli -K` cold-boot `failed` (`sim-missing`) auto-recovery and `nmcli` `gsm:` readiness gating in `mobile-data-prep` alongside `22 s` waits + `spawn_enable_and_register` in `boot`; switched cellular GSM profiles in `networks.so` and `mobile-data-prep` to `connection.autoconnect no` and ran `nmcli connection modify` before `mobile-data-prep` (and cleared any in-flight `qrtr0` `connecting` state) so background autoconnect never collides with `nmcli --wait 30 connection up` (`QMI OutOfCall (15)`); added `mobile-data-prep` / `restore-dsds` (`dsds_paused_for_data`) pause/reactivation via `10-bananarchy-dpm.sh` and `networks.so` when carrier EFS still holds `sub=0` in `cs-only`; and added `pre-up.d/10-bananarchy-dpm.sh` so `wwan0` BAM-DMUX opens before NetworkManager dial.
- **Idle `QMI_IMSDCM` (`0x0302`) isolation & bearer separation (`bananarchy-imsd.c`, `bananarchy-ims-bearer.sh`)**: gated QRTR `QMI_IMSDCM` (`0x0302`) server registration behind active VoLTE (`ensure_imsdcm()` / `close_imsdcm()`) and emitted `IMS_QMI_FLAG_IND` on `PDP_ACTIVATE`/`PDP_DEACTIVATE` so `MPSS.JO.3.1` `IMSAgent` cannot stall `DDSState = Pending` (`CM 2007`) at idle, while keeping IMS bearers isolated to `wwan1`/`rmnet_data1` away from `wwan0`.
- **Offline regression suite (`scripts/test-lte-mobile-data.py`, `scripts/check-rebuild.sh`)**: added offline host tests covering Dual-SIM/Single-SIM `ensure-ps-domain` over mock QRTR (`NAS` + `DSD`), `rat_parked` preservation, `cs-only` Dual-SIM pause and dispatcher `restore-dsds`, `Profile [1/4/5]` APN sync + initial-bearer skip, host `gcc` + `ctypes` validation of `mm-wds-bind.c`, and `bananarchy-ims-bearer.sh` `wwan0` isolation, wired into `scripts/check-rebuild.sh`.
### IMS profile (`.mbn`) management, VoLTE, and VoWiFi (`bananarchy-imsctl`, `bananarchy-imsd`, `bananarchy-vowifi`) across all targets
- **Disabled-by-default (`auto`) IMS policy with 4G-only auto-activation (`/etc/bananarchy/ims.conf`, `bananarchy-imsd`, `bananarchy-ims-bearer.sh`, `40-bananarchy-ims.sh`)**: shipped `volte_mode=auto` and `vowifi_mode=auto` (`volte_backend=auto`, `vowifi_roaming=0`, `wfc_preference=cellular_preferred`), keeping IMS daemons, bearer allocation, and `bananarchy-vowifi` completely idle at 0% CPU when CS/3G/2G fallback is available (`LTE+UMTS`, `UMTS`, `GSM`, or no registration) and activating VoLTE / VoWiFi automatically only when the connected cellular network is strictly **4G-only** (`LTE` with no 2G/3G CS fallback or modem `4G Only` preference) or when explicitly enabled by the user.
- **Qualcomm MCFG `.mbn` ELF32 parser, profile store, and `QMI_PDC` loader (`src/bananarchy-daemons/ims_mbn.h`, `ims_qrtr.h`, `bananarchy-imsctl.c`, `bananarchy-imsd.c`)**: implemented pure-C Qualcomm MCFG `.mbn` ELF32 LE validation (enforcing `config_type == 1` software configs, parsing `MCFG_TRL` carrier/MCC-MNC/version trailers, scanning `NV 67218` / EFS IMS flags, and computing pure-C SHA-1 `ba_<16hex>` IDs without external tools), persistent storage under `/var/lib/bananarchy/ims/profiles/`, `QMI_PDC` chunked `.mbn` loading/activation over `AF_QIPCRTR` (deduplicated via `g_pdc_loaded_id` / `pdc_select_only`), `QMI_DSD` `"ims"` APN tagging, dedicated-socket `QMI_IMSDCM` (`0x0302`) bearer activate/deactivate server, `QMI_IMS`/`QMI_IMSA` baseband VoLTE control with userspace fallback (`userspace`), and full Duress Mode mutation/exposure guards (`kDuressModeFlagPath`).
- **VoWiFi (`SWu` IKEv2 + `EAP-AKA`/`EAP-AKA'` + UDP/4500 ESP + 3GPP SIP + `SMS-over-IP`) and AMR-WB/AMR-NB codec support (`src/dwm-plugins/bananarchy_vowifi.cpp`, `vowifi_ikev2.h`, `vowifi_aka.h`, `amr_rtp.h`, `sip_plugin.cpp`)**: added an event-driven C++20 `SWu`/`IMS` userland engine implementing RFC 7296 IKEv2 (`COOKIE`, OpenSSL 3 `BN_get_rfc3526_prime_2048()` DH Group 14 with Group 2 fallback, `CFG_REQUEST` `P_CSCF_IP4/6`), RFC 4187/5448 `EAP-AKA` / `EAP-AKA'` via locked `QMI_UIM` `ISIM`/`USIM` `OPEN_LOGICAL_CHANNEL` + `SEND_APDU` (plus offline Milenage support), RFC 3948 UDP/4500 ESP over `tun_ims`, 3GPP SIP `REGISTER` (`AKAv1-MD5` with `AUTS` resync & instant `REFRESH` triggers), `INVITE` / `183 Session Progress` / `PRACK` / `UPDATE` / RTP / DTMF / `BYE`, `SMS-over-IP` (`RP-DATA` GSM-7/UCS-2 logging cleanly without `[SIM n]` tags), anti-spam `block.tsv` filtering, runtime-`dlopen`ed `AMR-WB` (`16 kHz`) / `AMR-NB` (`8 kHz`) octet-aligned and bandwidth-efficient RFC 4867 codecs (shared with `xsip` / `sip.so`), and cellular-first `112`/`911` emergency call routing (`sxmo_modemdial.sh`, `sxmo_modemcall.sh`, `sxmo_modemsendsms.sh`).
- **NeoUI control, CallScreen, power policy, and offline verification (`modem_plugin.cpp`, `files_plugin.cpp`, `callscreen_plugin.cpp`, `bananarchy-power-policy.sh`, `scripts/test-{ims-mbn,imsd-volte,vowifi-swu-ims,standby-power-policy}.py`)**: expanded `xmodem` to 5 tabs (`1:SIM 2:Rad 3:IMS 4:AT 5:Log`) with interactive `.mbn` install/select/remove and ePDG modals, added `.mbn` inspect/install actions to `xfiles`, wired `[SIM n VoWiFi]` / `[SIM n VoLTE]` badges and 425 Hz ringback into `xcallscreen`, updated `sxmo_hook_statusbar.sh`, `sxmo_hook_modem.sh`, `bananarchy-cover-status.sh`, `bananarchy-power-policy.sh` (preventing GSM parking during active cellular-preferred VoLTE and preserving IPv6 RA when `VOWIFI_IPV6_EPDG=1`), and added offline mock-QRTR / mock-TUN / Milenage host test suites (`test-ims-mbn.py`, `test-imsd-volte.py`, `test-vowifi-swu-ims.py`, and case 6 in `test-standby-power-policy.py`) wired into `scripts/check-rebuild.sh`.
- **Rebuilt local image SHA-256 checksums (`--mkinitfs`, no release `.zip` archives built yet)**:
- `images/bananarchy-nokia-argon.img`: `22014270bb62ebc825afe5ef60fe8aefa65776eb9efc511b92e834a61b59fb0e`
- `images/bananarchy-nokia-beatles.img`: `dce127a00efcf1e19aeaa8b21e4f28b33cdd5dd0044dcea0051a2e880c021ef7`
- `images/boot-bananarchy-nokia-beatles.img`: `480d6988f57028006ce0227092de077dffe5d6a51dadeedb0ef1f16a9a35a3e0`
- `images/bananarchy-nokia-coconut.img`: `1d5f20a0f6677748c25eedd044b23bb168ddaee0e4ae71c47ceefc0b0878c86f`
- `images/boot-bananarchy-nokia-coconut.img`: `7f56459f258857ed0252d0cd81e8fe496e55af2cff48e3cf6defe39a341dfc4a`
- `images/bananarchy-nokia-sparkler.img`: `99d54d6bc001e97f41dc314bbf012ef266251a70b6663a82260f32b1ffeff9e5`
- `images/boot-bananarchy-nokia-sparkler.img`: `a57973505f56754be74fdea9536e656af82a93d3d3722dcb61b3c6b6e9f6782b`
---
## Build `a1120` — codename `cocojamboo` (2026-11-20) ## Build `a1120` — codename `cocojamboo` (2026-11-20)
This build expands public release coverage to all four hardware-verified targets — **Nokia 8110 4G (`nokia-argon`)**, **Nokia 2720 Flip (`nokia-beatles`)**, **Nokia 800 Tough (`nokia-coconut`)**, and **Nokia 8000 4G (`nokia-sparkler`)** — shipping 4-core SMP/`cpufreq`, calibrated 157 Hz speaker-LRA haptic audio, dual-LED torch/camera support, versionless `lk2nd` screens, 72-hour DSDS/Wi-Fi standby optimizations (`0012`), Bluetooth 5.x/6.x headset audio and Android SSP pairing/OBEX file transfer, the Quagr encrypted pager (`xquagr`) with 2720 Flip cover alerts, permissionless keypad timers, microSD detection fixes, and DNS resolution/VPN leak fixes. This build expands public release coverage to all four hardware-verified targets — **Nokia 8110 4G (`nokia-argon`)**, **Nokia 2720 Flip (`nokia-beatles`)**, **Nokia 800 Tough (`nokia-coconut`)**, and **Nokia 8000 4G (`nokia-sparkler`)** — shipping 4-core SMP/`cpufreq`, calibrated 157 Hz speaker-LRA haptic audio, dual-LED torch/camera support, versionless `lk2nd` screens, 72-hour DSDS/Wi-Fi standby optimizations (`0012`), Bluetooth 5.x/6.x headset audio and Android SSP pairing/OBEX file transfer, the Quagr encrypted pager (`xquagr`) with 2720 Flip cover alerts, permissionless keypad timers, microSD detection fixes, and DNS resolution/VPN leak fixes.
+24 -7
View File
@@ -196,7 +196,7 @@ All twenty-five phone applications are compiled as shared-object plugins (`/usr/
- **Image preview and wallpaper installation**: pressing `Return` on any image file (`.jpg`, `.png`, `.bmp`, `.gif`, `.webp`, `.ppm`, `.tif`, `.ico`, `.svg`) opens the built-in image viewer (`*` toggles full-screen preview; **Left softkey (`Set Wall`)** installs the image into `~/Pictures/Wallpapers/`, applies it via `feh`, and refreshes the desktop overlay). You can also select **Preview Image** or **Set as Wallpaper** directly from the **Left softkey (`Actions`)** menu. - **Image preview and wallpaper installation**: pressing `Return` on any image file (`.jpg`, `.png`, `.bmp`, `.gif`, `.webp`, `.ppm`, `.tif`, `.ico`, `.svg`) opens the built-in image viewer (`*` toggles full-screen preview; **Left softkey (`Set Wall`)** installs the image into `~/Pictures/Wallpapers/`, applies it via `feh`, and refreshes the desktop overlay). You can also select **Preview Image** or **Set as Wallpaper** directly from the **Left softkey (`Actions`)** menu.
- **Monophonic ringtone viewer (`.nrt`, `.rtttl`, `.rtx`, `.emy`, `.imy`), audio playback, and ringtone/notification installation**: pressing `Return` on any Nokia RTTTL (`.nrt`, `.rtttl`, `.rtx`), Ericsson eMelody (`.emy`), or IrDA iMelody (`.imy`) file opens the built-in **Ringtone Viewer** (`RingtoneView`), displaying the melody title, format tag, BPM, note count, duration, graphical piano-roll pitch contour, and scrollable note sequence (`Up`/`Down`), with instant playback preview (`*` or `Center OK`), `Left`/`Right` to step through ringtones in the current folder, **Left softkey (`Set Ring`)** to set as the active call ringtone, **`#`** to set as the active notification/SMS sound, and `1` to edit the melody text. Pressing `Return` on standard audio or tracker module files opens **Music (`xmusic`)**. From the **Left softkey (`Actions`)** menu on any monophonic melody, audio, or tracker file, select **Preview Ringtone**, **Set as Ringtone**, **Set as Notif / SMS Sound**, **Open in Ringtones App**, or **Play in Music Player**. - **Monophonic ringtone viewer (`.nrt`, `.rtttl`, `.rtx`, `.emy`, `.imy`), audio playback, and ringtone/notification installation**: pressing `Return` on any Nokia RTTTL (`.nrt`, `.rtttl`, `.rtx`), Ericsson eMelody (`.emy`), or IrDA iMelody (`.imy`) file opens the built-in **Ringtone Viewer** (`RingtoneView`), displaying the melody title, format tag, BPM, note count, duration, graphical piano-roll pitch contour, and scrollable note sequence (`Up`/`Down`), with instant playback preview (`*` or `Center OK`), `Left`/`Right` to step through ringtones in the current folder, **Left softkey (`Set Ring`)** to set as the active call ringtone, **`#`** to set as the active notification/SMS sound, and `1` to edit the melody text. Pressing `Return` on standard audio or tracker module files opens **Music (`xmusic`)**. From the **Left softkey (`Actions`)** menu on any monophonic melody, audio, or tracker file, select **Preview Ringtone**, **Set as Ringtone**, **Set as Notif / SMS Sound**, **Open in Ringtones App**, or **Play in Music Player**.
- **MicroSD card (`/media/sdcard`) integration**: the external microSD slot (`sdhci@7864000`) uses `non-removable` boot-time detection with zero card-detect polling (when empty or idle, `7864900.sdhci` enters `runtime_status = suspended` and drops `l11`/`l12` to `0 mA`). If a microSD card (`/dev/mmcblk1`) is present at boot, `udev` and `/usr/bin/sxmo_sdcard.sh` automatically mount it at `/media/sdcard`; if a card is inserted or swapped while powered on (such as on side-tray phones), run `sxmo_sdcard.sh rescan` or pick **Rescan SD Card Slot** from **System menu -> SD Card**. From the **Left softkey (`Actions`)** menu inside `xfiles` (or **System menu -> SD Card**), select **Open SD Card (/media/sdcard)** to jump straight to the card (mounting it on demand if needed) or **Mount / Unmount SD Card** (`sxmo_sdcard.sh unmount`) to safely flush buffers and unbind `7864900.sdhci` before card removal. - **MicroSD card (`/media/sdcard`) integration**: the external microSD slot (`sdhci@7864000`) uses `non-removable` boot-time detection with zero card-detect polling (when empty or idle, `7864900.sdhci` enters `runtime_status = suspended` and drops `l11`/`l12` to `0 mA`). If a microSD card (`/dev/mmcblk1`) is present at boot, `udev` and `/usr/bin/sxmo_sdcard.sh` automatically mount it at `/media/sdcard`; if a card is inserted or swapped while powered on (such as on side-tray phones), run `sxmo_sdcard.sh rescan` or pick **Rescan SD Card Slot** from **System menu -> SD Card**. From the **Left softkey (`Actions`)** menu inside `xfiles` (or **System menu -> SD Card**), select **Open SD Card (/media/sdcard)** to jump straight to the card (mounting it on demand if needed) or **Mount / Unmount SD Card** (`sxmo_sdcard.sh unmount`) to safely flush buffers and unbind `7864900.sdhci` before card removal.
- **Bluetooth file transfer (`Send via Bluetooth`)**: select **Send via Bluetooth** from the **Left softkey (`Actions`)** menu on any file to choose a paired or nearby Bluetooth device (`*` rescans) and transmit the file over Bluetooth OBEX Object Push (`/usr/bin/bananarchy-bt-obex`). - **Bluetooth file transfer (`Send via Bluetooth`) and IMS `.mbn` profiles**: select **Send via Bluetooth** from the **Left softkey (`Actions`)** menu on any file to choose a paired or nearby Bluetooth device (`*` rescans) and transmit the file over Bluetooth OBEX Object Push (`/usr/bin/bananarchy-bt-obex`). On Qualcomm MCFG `.mbn` files, **Install IMS Profile** and **Inspect MBN Profile** parse ELF32 `MCFG_SW` metadata and install/activate the profile via `/usr/bin/bananarchy-imsctl` (blocked in Duress Mode).
- **File management actions**: the **Left softkey (`Actions`)** menu also provides **Edit in Text Editor**, **View Text**, **Edit in nano**, **New Folder**, **New File**, **Rename**, **Copy**, **Cut / Move**, **Paste Here**, **Properties**, **Open Terminal Here**, and **Delete**. - **File management actions**: the **Left softkey (`Actions`)** menu also provides **Edit in Text Editor**, **View Text**, **Edit in nano**, **New Folder**, **New File**, **Rename**, **Copy**, **Cut / Move**, **Paste Here**, **Properties**, **Open Terminal Here**, and **Delete**.
9. **Camera (`camera.so` / `xcamera`)**: 9. **Camera (`camera.so` / `xcamera`)**:
@@ -207,19 +207,20 @@ All twenty-five phone applications are compiled as shared-object plugins (`/usr/
- **Open**: select **Themes** from the System, Apps, or Config menu, or run `xthemes`. - **Open**: select **Themes** from the System, Apps, or Config menu, or run `xthemes`.
- **Live theme switching and customizer**: browse 21 preinstalled `.xth` schemes (`~/.xthemes/*.xth`) with live color swatches and press **Center `OK`** or **Call (green)** to apply across `dwm`, `dmenu`, `st`, `dunst` (`bananarchy-sync-dunst-theme`), and all plugins with zero restart. Press **`*`** or **Left softkey** to customize individual colors and font sizes, save a custom theme (`#`), or edit the `.xth` file in Nano. - **Live theme switching and customizer**: browse 21 preinstalled `.xth` schemes (`~/.xthemes/*.xth`) with live color swatches and press **Center `OK`** or **Call (green)** to apply across `dwm`, `dmenu`, `st`, `dunst` (`bananarchy-sync-dunst-theme`), and all plugins with zero restart. Press **`*`** or **Left softkey** to customize individual colors and font sizes, save a custom theme (`#`), or edit the `.xth` file in Nano.
11. **Modem, Dual-SIM, and PIN/PUK manager (`modem.so` / `xmodem`)**: 11. **Modem, Dual-SIM, IMS / VoLTE / VoWiFi, and PIN/PUK manager (`modem.so` / `xmodem`)**:
- **Open**: select **Modem** from the System menu, or run `xmodem`. Also opens automatically when a SIM card requires PIN or PUK unlock. - **Open**: select **Modem** from the System menu, or run `xmodem`. Also opens automatically when a SIM card requires PIN or PUK unlock.
- **Four control tabs (`Left`/`Right` or `1`–`4`)**: - **Five control tabs (`Left`/`Right` or `1`–`5`)**:
- **`1:SIMs`**: inspects both physical SIM slots via QMI UIM (`PRESENT`/`EMPTY`, `[PRI 4G / DEFAULT]`, `[PRI 4G / DSDS]`, `[SEC 2G / DEFAULT]`, `[SEC 2G / DSDS]`, `READY`/`PIN-LOCK`/`PUK-LOCK`, remaining retries, operator, RAT, and phone number). Press `Return` on a slot (or use the bottom quick-action rows) to **Set as Default SIM (Calls/SMS)** (instant switch without dropping network registration), **Make Primary GW (4G/Data Swap)** (`msm-modem-uim-selection switch <slot> --swap-gw` to move 4G/LTE/3G + Mobile Data to that slot and 2G DSDS standby to the other), **Unlock SIM PIN**, **Unblock SIM with PUK**, **Enable / Disable PIN Lock**, or **Change SIM PIN** (with automatic `ModemManager` reprobe after unlock). - **`1:SIMs`**: inspects both physical SIM slots via QMI UIM (`PRESENT`/`EMPTY`, `[PRI 4G / DEFAULT]`, `[PRI 4G / DSDS]`, `[SEC 2G / DEFAULT]`, `[SEC 2G / DSDS]`, `READY`/`PIN-LOCK`/`PUK-LOCK`, remaining retries, operator, RAT, and phone number). Press `Return` on a slot (or use the bottom quick-action rows) to **Set as Default SIM (Calls/SMS)** (instant switch without dropping network registration), **Make Primary GW (4G/Data Swap)** (`msm-modem-uim-selection switch <slot> --swap-gw` to move 4G/LTE/3G + Mobile Data to that slot and 2G DSDS standby to the other), **Unlock SIM PIN**, **Unblock SIM with PUK**, **Enable / Disable PIN Lock**, or **Change SIM PIN** (with automatic `ModemManager` reprobe after unlock).
- **`2:Radio`**: shows signal bar, registration status, access technology (`LTE`/`UMTS`/`GSM`), operator, both IMEIs, and phone number, with actions to switch **Network Mode** (`4G/3G/2G`, `3G/2G`, `4G Only`, `3G Only`, `2G Only`), **Send USSD Code**, toggle **Modem Power**, or **Restart ModemManager**. - **`2:Radio`**: shows signal bar, registration status, access technology (`LTE`/`UMTS`/`GSM`), operator, both IMEIs, and phone number, with actions to switch **Network Mode** (`4G/3G/2G`, `3G/2G`, `4G Only`, `3G Only`, `2G Only`), **Send USSD Code**, toggle **Modem Power**, or **Restart ModemManager**.
- **`3:AT`**: interactive AT command console with presets (`AT`, `ATI`, `AT+CPIN?`, `AT+CSQ`, `AT+COPS?`, etc.) and custom keypad entry. - **`3:IMS`**: displays live VoLTE and VoWiFi registration status, active carrier MBN profile, `QMI_PDC` / `QMI_IMSDCM` bearer state, and ISIM/USIM `EAP-AKA` readiness. Configure **VoLTE Mode** (`auto` / `on` / `off`), **VoWiFi Mode** (`auto` / `on` / `off`), **VoLTE Backend** (`auto` / `baseband` / `userspace`), **WFC Preference** (`Cellular Pref.` / `Wi-Fi Pref.`), **VoWiFi Roaming**, **Active IMS SIM Slot**, **Manage `.mbn` Profiles** (install, activate, auto-match MCC/MNC, remove, or reset to modem default), and **ePDG & SIP Settings** (`/etc/bananarchy/ims.conf`). Both VoLTE and VoWiFi default to `auto` (disabled unless connected to a strictly **4G-only** network).
- **`4:Log`**: scrollable history of calls, SMS events, and USSD responses. - **`4:AT`**: interactive AT command console with presets (`AT`, `ATI`, `AT+CPIN?`, `AT+CSQ`, `AT+COPS?`, etc.) and custom keypad entry.
- **`5:Log`**: scrollable history of calls, SMS events, and USSD responses.
12. **Networks and Bluetooth manager (`networks.so` / `xnetworks` / `xbluetooth`)**: 12. **Networks and Bluetooth manager (`networks.so` / `xnetworks` / `xbluetooth`)**:
- **Open**: select **Networks** or **Bluetooth** from the System menu, or run `xnetworks` / `xbluetooth`. - **Open**: select **Networks** or **Bluetooth** from the System menu, or run `xnetworks` / `xbluetooth`.
- **Three connectivity tabs (`Left`/`Right` or `1`–`3`)**: - **Three connectivity tabs (`Left`/`Right` or `1`–`3`)**:
- **`1:Wi-Fi`**: toggle Wi-Fi radio, rescan (`*`), toggle **Wi-Fi Hotspot**, and connect to WPA2/open networks with a multi-tap password dialog (`*` toggles password visibility). - **`1:Wi-Fi`**: toggle Wi-Fi radio, rescan (`*`), toggle **Wi-Fi Hotspot**, and connect to WPA2/open networks with a multi-tap password dialog (`*` toggles password visibility).
- **`2:Cell/APN`**: toggle **Mobile Data** (configuring the QMI `bam-dmux` `wwan0` static IPv4 bearer, default route, and DNS via NetworkManager `rc-manager=file` + local `dnsmasq` caching, with automatic `1.1.1.1`/`9.9.9.9` fallback when a carrier omits DNS), inspect `wwan0` IPv4 status, edit **APN Configuration**, and toggle **USB Tethering** (forwarding tethered `172.16.42.1:53` queries to local `dnsmasq`). - **`2:Cell/APN`**: toggle **Mobile Data** (running `msm-modem-uim-selection mobile-data-prep` to open QMI `bam-dmux` `wwan0`, synchronize WDS `Profile [1]`/`attach_pdn`/`def_prof`, bind `QMI_WDS` via `libmm-wds-bind.so`, and temporarily pause/restore Dual-SIM `Secondary GW` if required by carrier EFS, then configuring `wwan0` IPv4, default route, and DNS via NetworkManager `rc-manager=file` + local `dnsmasq` caching with automatic `1.1.1.1`/`9.9.9.9` fallback when a carrier omits DNS), inspect `wwan0` IPv4 status, edit **APN Configuration**, and toggle **USB Tethering** (forwarding tethered `172.16.42.1:53` queries to local `dnsmasq`).
- **`3:Bluetooth`**: toggle **Bluetooth Power** (showing a live `ON (N Active)` badge and starting `/usr/bin/bananarchy-bt-obex`), toggle **Discoverable** (`OFF (Hidden)` by default to avoid continuous Inquiry Scan standby draw, or `ON (Visible for 60s)`, persisted in `~/.config/sxmo/bt_discoverable`), edit the **Bluetooth Device Name** (`Name: <Alias> [Edit]`, persisted in `~/.config/sxmo/bt_name` and applied via `bluetoothctl system-alias` independently of the system hostname), configure the **OBEX File Receiver** (`OBEX Dir: <folder> [Set]`, opening actions to **Set Target Directory...** via an interactive folder picker including `/media/sdcard`, **Open Folder in Files**, or **Reset to ~/Downloads**, persisted in `~/.config/sxmo/bt_obex_dir`; `#` quick-opens the folder in `xfiles`), scan nearby devices (`*` or `Scan`, 15-second discovery scan), and manage paired/discovered devices. Pairing runs via a persistent `KeyboardDisplay` `Agent1` in `/usr/bin/bananarchy-bt-obex` (with `ssp on`, `bondable on`, `linksec on`, `advertising off`, Smartphone class `2 3`, and `PairableTimeout = 0`), popping up an interactive pairing dialog in `xnetworks` for 6-digit passkey confirmation (`Accept & Pair` / `Reject Pairing`), keypad PIN/passkey entry, or outgoing keyboard pairing codes (while auto-confirming screenless Classic Audio headsets). Incoming OBEX file pushes (over both L2CAP `SOCK_SEQPACKET` and RFCOMM, with Smartphone Class of Device `0x5a020c` and no `a2dp_source` role so paired Android phones recognize OPP rather than a headset) pop up an interactive confirmation dialog showing sender, filename, size, **Accept & Save File**, **Dir: ... [Set]** to pick a different destination folder on the spot, and **Reject Transfer**. The scan now drives one interactive `bluetoothctl` client through `script(1)` (`/usr/local/bin/bluetoothctl` -> `/usr/bin/bananarchy-bt-scan.sh`), sets auto transport and duplicate-data, asks the same client for `devices` three times while discovery is active, parses both `[NEW] Device ...` / `[CHG] Device ...` and `Device <MAC> <Name>` lines, and stops discovery cleanly before the client exits; the controller is also powered on automatically if `bluetoothctl show` reports `Powered: no`. A narrow `doas` helper runs `btmgmt -i hci0 le on` alongside BR/EDR SSP/bondable flags before discovery because this WCNSS controller otherwise starts with LE and pairing flags unconfigured. BlueZ keeps `ControllerMode = dual`: `bredr` mode rejects the LE-only HOGP profile, so BLE HID devices would connect at the GATT level but never create a keyboard or mouse input node. **Connect Device** and **Pair & Trust Device** run non-blockingly (`--async-ui`), power the adapter on, enable LE/SSP, select the `le` bearer for HID-over-GATT devices, prefer public BR/EDR entries and the `bredr` bearer (`ConnectProfile` A2DP/HFP fallback) for Classic Audio / dual-mode Bluetooth 5.x/6.x headsets or `OBEX/PAN` phones, and automatically pair unpaired peripherals. Active connections are pinned to the top of the device list with a green border and live profile/battery badges (`[ACTIVE: A2DP]`, `[ACTIVE: HSP/HFP]`, `[ACTIVE: HID Gamepad]`, `[ACTIVE: HID Keyboard]`, `[ACTIVE: HID Mouse]`), and the device actions menu (`Center OK`) provides **Connect Device**, **Disconnect Device**, **Pair & Trust Device**, **Switch Audio (A2DP / HSP-HFP)**, and **Forget / Remove Device**. Supports Bluetooth **A2DP** (`sbc`, `sbc_xq`, `aac`, `ldac` ABR `auto`, `aptx`, `aptx_hd`) with AVRCP hardware volume and Play/Pause/Next/Prev headset button control of `xmusic`, and **HSP/HFP** (`CVSD` 8 kHz over QDSP6 `INTERNAL_BT_SCO`, with `mSBC`/`LC3-A127`/`LC3` and unsupported LE Audio BAP roles disabled, plus headset `ATA` call answer/A2DP restore synchronization), **HID keyboards** (automatically switching `fcitx5-t9` and NeoUI/plugin inputs to `[KBD]` direct QWERTY mode so `0-9`, `*`, `#`, `Shift+0-9`, and letters bypass T9 multi-tap and preedit popups), **HID mice** (automatically showing the X11 mouse cursor whenever a mouse is connected and hiding it when disconnected), and **HID gamepads** (automatically bridged to the phone's D-Pad, softkeys, and action keys via `/dev/uinput`). - **`3:Bluetooth`**: toggle **Bluetooth Power** (showing a live `ON (N Active)` badge and starting `/usr/bin/bananarchy-bt-obex`), toggle **Discoverable** (`OFF (Hidden)` by default to avoid continuous Inquiry Scan standby draw, or `ON (Visible for 60s)`, persisted in `~/.config/sxmo/bt_discoverable`), edit the **Bluetooth Device Name** (`Name: <Alias> [Edit]`, persisted in `~/.config/sxmo/bt_name` and applied via `bluetoothctl system-alias` independently of the system hostname), configure the **OBEX File Receiver** (`OBEX Dir: <folder> [Set]`, opening actions to **Set Target Directory...** via an interactive folder picker including `/media/sdcard`, **Open Folder in Files**, or **Reset to ~/Downloads**, persisted in `~/.config/sxmo/bt_obex_dir`; `#` quick-opens the folder in `xfiles`), scan nearby devices (`*` or `Scan`, 15-second discovery scan), and manage paired/discovered devices. Pairing runs via a persistent `KeyboardDisplay` `Agent1` in `/usr/bin/bananarchy-bt-obex` (with `ssp on`, `bondable on`, `linksec on`, `advertising off`, Smartphone class `2 3`, and `PairableTimeout = 0`), popping up an interactive pairing dialog in `xnetworks` for 6-digit passkey confirmation (`Accept & Pair` / `Reject Pairing`), keypad PIN/passkey entry, or outgoing keyboard pairing codes (while auto-confirming screenless Classic Audio headsets). Incoming OBEX file pushes (over both L2CAP `SOCK_SEQPACKET` and RFCOMM, with Smartphone Class of Device `0x5a020c` and no `a2dp_source` role so paired Android phones recognize OPP rather than a headset) pop up an interactive confirmation dialog showing sender, filename, size, **Accept & Save File**, **Dir: ... [Set]** to pick a different destination folder on the spot, and **Reject Transfer**. The scan now drives one interactive `bluetoothctl` client through `script(1)` (`/usr/local/bin/bluetoothctl` -> `/usr/bin/bananarchy-bt-scan.sh`), sets auto transport and duplicate-data, asks the same client for `devices` three times while discovery is active, parses both `[NEW] Device ...` / `[CHG] Device ...` and `Device <MAC> <Name>` lines, and stops discovery cleanly before the client exits; the controller is also powered on automatically if `bluetoothctl show` reports `Powered: no`. A narrow `doas` helper runs `btmgmt -i hci0 le on` alongside BR/EDR SSP/bondable flags before discovery because this WCNSS controller otherwise starts with LE and pairing flags unconfigured. BlueZ keeps `ControllerMode = dual`: `bredr` mode rejects the LE-only HOGP profile, so BLE HID devices would connect at the GATT level but never create a keyboard or mouse input node. **Connect Device** and **Pair & Trust Device** run non-blockingly (`--async-ui`), power the adapter on, enable LE/SSP, select the `le` bearer for HID-over-GATT devices, prefer public BR/EDR entries and the `bredr` bearer (`ConnectProfile` A2DP/HFP fallback) for Classic Audio / dual-mode Bluetooth 5.x/6.x headsets or `OBEX/PAN` phones, and automatically pair unpaired peripherals. Active connections are pinned to the top of the device list with a green border and live profile/battery badges (`[ACTIVE: A2DP]`, `[ACTIVE: HSP/HFP]`, `[ACTIVE: HID Gamepad]`, `[ACTIVE: HID Keyboard]`, `[ACTIVE: HID Mouse]`), and the device actions menu (`Center OK`) provides **Connect Device**, **Disconnect Device**, **Pair & Trust Device**, **Switch Audio (A2DP / HSP-HFP)**, and **Forget / Remove Device**. Supports Bluetooth **A2DP** (`sbc`, `sbc_xq`, `aac`, `ldac` ABR `auto`, `aptx`, `aptx_hd`) with AVRCP hardware volume and Play/Pause/Next/Prev headset button control of `xmusic`, and **HSP/HFP** (`CVSD` 8 kHz over QDSP6 `INTERNAL_BT_SCO`, with `mSBC`/`LC3-A127`/`LC3` and unsupported LE Audio BAP roles disabled, plus headset `ATA` call answer/A2DP restore synchronization), **HID keyboards** (automatically switching `fcitx5-t9` and NeoUI/plugin inputs to `[KBD]` direct QWERTY mode so `0-9`, `*`, `#`, `Shift+0-9`, and letters bypass T9 multi-tap and preedit popups), **HID mice** (automatically showing the X11 mouse cursor whenever a mouse is connected and hiding it when disconnected), and **HID gamepads** (automatically bridged to the phone's D-Pad, softkeys, and action keys via `/dev/uinput`).
13. **Ringtones, notification/SMS sounds, and ringer manager (`ringtones.so` / `xringtones`)**: 13. **Ringtones, notification/SMS sounds, and ringer manager (`ringtones.so` / `xringtones`)**:
@@ -248,7 +249,7 @@ All twenty-five phone applications are compiled as shared-object plugins (`/usr/
- **`1:Dialer`**: enter a SIP URI (`user@host[:port]` or `sip:user@host[:port]`) or account extension (`1001`) using multi-tap alphanumeric input (`*` or `#` cycles `[abc]` / `[ABC]` / `[123]` / `[Sym]` / `[Abc]`) or select a recent peer with `Up`/`Down`, and press **Call (green)** or **Center `OK`** to place an outgoing SIP call. Outbound calls work both with a registered SIP account and directly without any configured account (`Direct URI` mode, selectable via `Menu -> Switch Account` when accounts are also present). - **`1:Dialer`**: enter a SIP URI (`user@host[:port]` or `sip:user@host[:port]`) or account extension (`1001`) using multi-tap alphanumeric input (`*` or `#` cycles `[abc]` / `[ABC]` / `[123]` / `[Sym]` / `[Abc]`) or select a recent peer with `Up`/`Down`, and press **Call (green)** or **Center `OK`** to place an outgoing SIP call. Outbound calls work both with a registered SIP account and directly without any configured account (`Direct URI` mode, selectable via `Menu -> Switch Account` when accounts are also present).
- **`2:Accounts`**: add or edit SIP accounts (`~/.config/sxmo/sip_accounts.tsv`: Label, alphanumeric Username, Password, Domain, Port, UDP/TCP/TLS transport, ZRTP toggle, Preferred Codec, Enabled). Enabled accounts maintain RFC 3261 `REGISTER` keepalives with Digest MD5 authentication in the background even when `xsip` is closed. - **`2:Accounts`**: add or edit SIP accounts (`~/.config/sxmo/sip_accounts.tsv`: Label, alphanumeric Username, Password, Domain, Port, UDP/TCP/TLS transport, ZRTP toggle, Preferred Codec, Enabled). Enabled accounts maintain RFC 3261 `REGISTER` keepalives with Digest MD5 authentication in the background even when `xsip` is closed.
- **`3:History`**: browse incoming, outgoing, and missed SIP calls (`~/.local/share/sxmo/sip_history.tsv`) and press **Call (green)** or **Center `OK`** to redial. - **`3:History`**: browse incoming, outgoing, and missed SIP calls (`~/.local/share/sxmo/sip_history.tsv`) and press **Call (green)** or **Center `OK`** to redial.
- **Audio codecs (`AUTO`, `PCMU`, `PCMA`, `GSM`, `OPUS`, `G722`, `G726-32`, `DVI4`, `L16`)**: supports full SDP `m=audio` / `a=rtpmap` / `a=fmtp` negotiation across 10 narrowband (`8 kHz`) and wideband (`16 kHz`) RTP/SRTP audio profiles, prioritizing **ITU-T G.711** `PCMU` (`PT 0`) and `PCMA` (`PT 8`, 8 kHz 64 kbps) first in `AUTO` mode, followed by **GSM 06.10 Full Rate** (`GSM/8000`, `PT 3`, 8 kHz 13 kbps RPE-LTP), **Opus** (`opus/48000/2`, RFC 7587, 16 kHz wideband VoIP with in-band FEC), **ITU-T G.722** (`G722/8000`, 16 kHz wideband 64 kbps SB-ADPCM), **ITU-T G.726-32** (`G726-32/8000`, 8 kHz 32 kbps ADPCM), **IMA ADPCM** (`DVI4/8000` `PT 5` and `DVI4/16000` `PT 6`), and **uncompressed 16-bit PCM** (`L16/8000` and `L16/16000`), plus **RFC 2833 / RFC 4733 `telephone-event/8000`** DTMF. Preferred codec priority is configurable per account (`Codec` field in the Account Editor) or for direct accountless calls (`Menu -> Cycle Direct Codec`). - **Audio codecs (`AUTO`, `PCMU`, `PCMA`, `GSM`, `OPUS`, `G722`, `AMR-WB`, `AMR-NB`, `G726-32`, `DVI4`, `L16`)**: supports full SDP `m=audio` / `a=rtpmap` / `a=fmtp` negotiation across narrowband (`8 kHz`) and wideband (`16 kHz`) RTP/SRTP audio profiles, prioritizing **ITU-T G.711** `PCMU` (`PT 0`) and `PCMA` (`PT 8`, 8 kHz 64 kbps) first in `AUTO` mode, followed by **GSM 06.10 Full Rate** (`GSM/8000`, `PT 3`, 8 kHz 13 kbps RPE-LTP), **Opus** (`opus/48000/2`, RFC 7587, 16 kHz wideband VoIP with in-band FEC), **ITU-T G.722** (`G722/8000`, 16 kHz wideband 64 kbps SB-ADPCM), **AMR-WB** (`AMR-WB/16000`) and **AMR-NB** (`AMR/8000`, RFC 4867 octet-aligned and bandwidth-efficient modes), **ITU-T G.726-32** (`G726-32/8000`, 8 kHz 32 kbps ADPCM), **IMA ADPCM** (`DVI4/8000` `PT 5` and `DVI4/16000` `PT 6`), and **uncompressed 16-bit PCM** (`L16/8000` and `L16/16000`), plus **RFC 2833 / RFC 4733 `telephone-event/8000`** DTMF. Preferred codec priority is configurable per account (`Codec` field in the Account Editor) or for direct accountless calls (`Menu -> Cycle Direct Codec`).
- **ZRTP / SRTP encryption and CallScreen (`xcallscreen`) integration**: supports RFC 6189 **ZRTP** (`DH3k` 3072-bit / `DH2k` 2048-bit Diffie-Hellman key agreement with `a=zrtp-hash` SDP signaling and persistent 96-bit `ZID`) and RFC 3711 **SRTP** (`AES-128-CM` + `HMAC-SHA1-80`/`32`) encrypted voice media (`ON` by default per account and for direct accountless calls via `Menu -> Toggle Direct ZRTP`). Incoming `INVITE` requests wake the phone, trigger the ringtone/vibrator, and open `xcallscreen` with a `[SIP/<codec>]` badge; once ZRTP completes its handshake, the active codec and 4-character Short Authentication String (`SAS`) are displayed in both `xsip` (`<codec> | ZRTP SAS:<sas>`) and `xcallscreen` (`[SIP/<codec>:<sas>]`). - **ZRTP / SRTP encryption and CallScreen (`xcallscreen`) integration**: supports RFC 6189 **ZRTP** (`DH3k` 3072-bit / `DH2k` 2048-bit Diffie-Hellman key agreement with `a=zrtp-hash` SDP signaling and persistent 96-bit `ZID`) and RFC 3711 **SRTP** (`AES-128-CM` + `HMAC-SHA1-80`/`32`) encrypted voice media (`ON` by default per account and for direct accountless calls via `Menu -> Toggle Direct ZRTP`). Incoming `INVITE` requests wake the phone, trigger the ringtone/vibrator, and open `xcallscreen` with a `[SIP/<codec>]` badge; once ZRTP completes its handshake, the active codec and 4-character Short Authentication String (`SAS`) are displayed in both `xsip` (`<codec> | ZRTP SAS:<sas>`) and `xcallscreen` (`[SIP/<codec>:<sas>]`).
17. **Email client (`email.so` / `xemail` / `xmail`)**: 17. **Email client (`email.so` / `xemail` / `xmail`)**:
@@ -586,10 +587,26 @@ Both the rear loudspeaker (`Speaker`, with boosted `RX3 Digital Volume` for loud
```bash ```bash
doas /usr/libexec/msm-modem-uim-selection ussd initiate --sim 2 "*111#" doas /usr/libexec/msm-modem-uim-selection ussd initiate --sim 2 "*111#"
``` ```
- **Prepare cellular PS attach / WDS APN profiles and restore Dual-SIM standby cleanly**:
```bash
doas /usr/libexec/msm-modem-uim-selection mobile-data-prep internet
nmcli connection up internet
nmcli connection down internet
doas /usr/libexec/msm-modem-uim-selection restore-dsds
```
- **Inspect ModemManager registration, operator, and signal quality**: - **Inspect ModemManager registration, operator, and signal quality**:
```bash ```bash
mmcli -m any mmcli -m any
``` ```
- **Inspect or configure IMS `.mbn` profiles, VoLTE, and VoWiFi (`/etc/bananarchy/ims.conf`)**:
```bash
bananarchy-imsctl status
bananarchy-imsctl probe --json
doas bananarchy-imsctl profile inspect /path/to/mcfg_sw.mbn
doas bananarchy-imsctl profile install /path/to/mcfg_sw.mbn --activate
doas bananarchy-imsctl set volte_mode on|auto|off vowifi_mode on|auto|off
doas bananarchy-imsctl auto-match
```
### 5.5 Adreno 304 GPU hardware acceleration and OpenGL / OpenGL ES demos ### 5.5 Adreno 304 GPU hardware acceleration and OpenGL / OpenGL ES demos
+5 -5
View File
@@ -40,13 +40,13 @@ Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs
- **WireGuard (`5:WG`)**: start/stop a kernel WireGuard tunnel (`wg0`), generate keypairs (`wg genkey` / `wg pubkey`) or import `.conf` profiles, edit custom `PrivateKey`, peer `PublicKey`, optional `PresharedKey`, `Endpoint`, `Address`, and `DNS`, and route native and/or Wi-Fi/USB-tethered traffic through it. - **WireGuard (`5:WG`)**: start/stop a kernel WireGuard tunnel (`wg0`), generate keypairs (`wg genkey` / `wg pubkey`) or import `.conf` profiles, edit custom `PrivateKey`, peer `PublicKey`, optional `PresharedKey`, `Endpoint`, `Address`, and `DNS`, and route native and/or Wi-Fi/USB-tethered traffic through it.
- **Zero-log privacy default and Extended Logging toggle (`xengmenu` / `dmenu config` / `bananarchy-engmenu-ctl logging`)**: extended system and session logging is **disabled by default** (`OFF`) across `sxmo_log`, `superd` and its managed services, `Xorg` (`-logfile /dev/null -logverbose 0`), `dwm`, `fcitx5` (`--verbose="*=0"`), `tinydm`, `NetworkManager` (`level=OFF`), `ModemManager` (`--log-level=ERR --log-file=/dev/null`), and kernel `printk`, ensuring zero eMMC log writes and zero idle logging activity. Extended RAM-only logging in `/tmp` (`/tmp/sxmo.log`, `/tmp/superd.log`, `/tmp/superd_state/superd/logs/*.log`) can be toggled at any time in the **Engineering Menu (`*#0001#` / `xengmenu` -> `8: Extended Logging`)**, **`Config -> Extended Logging`**, or via `bananarchy-engmenu-ctl logging [on|off|toggle|status]`. - **Zero-log privacy default and Extended Logging toggle (`xengmenu` / `dmenu config` / `bananarchy-engmenu-ctl logging`)**: extended system and session logging is **disabled by default** (`OFF`) across `sxmo_log`, `superd` and its managed services, `Xorg` (`-logfile /dev/null -logverbose 0`), `dwm`, `fcitx5` (`--verbose="*=0"`), `tinydm`, `NetworkManager` (`level=OFF`), `ModemManager` (`--log-level=ERR --log-file=/dev/null`), and kernel `printk`, ensuring zero eMMC log writes and zero idle logging activity. Extended RAM-only logging in `/tmp` (`/tmp/sxmo.log`, `/tmp/superd.log`, `/tmp/superd_state/superd/logs/*.log`) can be toggled at any time in the **Engineering Menu (`*#0001#` / `xengmenu` -> `8: Extended Logging`)**, **`Config -> Extended Logging`**, or via `bananarchy-engmenu-ctl logging [on|off|toggle|status]`.
- **Global controls drawer (`xdrawer`) and `*` + `#` screenshot combo**: press **both softkeys together** from anywhere to adjust linear (`1%`–`100%`) speaker, earpiece, and ringtone volume, audio output routing (`Speaker`, `Earpiece`, `Headphones` with automatic 3.5mm jack plug/unplug routing), ringer mode (`Ring+Vib` / `Vibrate` / `Silent` / `DND`), 3-level vibration intensity (`Light` / `Medium` / `Strong`), flashlight, sound and microphone mute, screen brightness, and keypad backlight; press **`*` and `#` together** from anywhere to capture a `240x320` PNG screenshot (`scrot` via `bananarchy-screenshot`) to `~/Pictures/screenshot-YYYYMMDD-HHMMSS.png`. - **Global controls drawer (`xdrawer`) and `*` + `#` screenshot combo**: press **both softkeys together** from anywhere to adjust linear (`1%`–`100%`) speaker, earpiece, and ringtone volume, audio output routing (`Speaker`, `Earpiece`, `Headphones` with automatic 3.5mm jack plug/unplug routing), ringer mode (`Ring+Vib` / `Vibrate` / `Silent` / `DND`), 3-level vibration intensity (`Light` / `Medium` / `Strong`), flashlight, sound and microphone mute, screen brightness, and keypad backlight; press **`*` and `#` together** from anywhere to capture a `240x320` PNG screenshot (`scrot` via `bananarchy-screenshot`) to `~/Pictures/screenshot-YYYYMMDD-HHMMSS.png`.
- **Phone dialer (`xdialer`), call log (`xcalllog`), and call screen (`xcallscreen`)**: press any digit on the home screen to start dialing with live T9 contact matching, run interactive carrier USSD codes (`*100#`, etc.), or type `*#06#` to inspect both IMEIs. When two SIM cards are active in Dual-SIM Dual Standby (DSDS), placing a call or running a USSD code prompts to choose between `SIM 1` and `SIM 2`. Incoming and active calls on either SIM (as well as incoming/active VoIP calls from `xsip` and `xtox`) open a dedicated call screen with an active `[SIM 1]`/`[SIM 2]`/`[SIP]`/`[TOX]` badge, earpiece/speaker switching, microphone mute, DTMF keypad, and one-key normalized WAV call recording (`~/Recordings/rec_HHMMSS_<caller>.wav`). The call log includes a 5-tab view (`All`, `Miss`, `In`, `Out`, `Spam`) with integrated anti-spam number blocking (`~/.config/sxmo/block.tsv`) that automatically hangs up blocked callers and logs them to the `Spam` tab without triggering missed-call notifications. - **Phone dialer (`xdialer`), call log (`xcalllog`), and call screen (`xcallscreen`)**: press any digit on the home screen to start dialing with live T9 contact matching, run interactive carrier USSD codes (`*100#`, etc.), or type `*#06#` to inspect both IMEIs. When two SIM cards are active in Dual-SIM Dual Standby (DSDS), placing a call or running a USSD code prompts to choose between `SIM 1` and `SIM 2`. Emergency numbers (`112`/`911`) prioritize cellular CS/VoLTE before falling back to VoWiFi. Incoming and active calls on either SIM (including `[SIM n VoLTE]`/`[SIM n VoWiFi]` IMS calls as well as incoming/active VoIP calls from `xsip` and `xtox`) open a dedicated call screen with an active `[SIM 1]`/`[SIM 2]`/`[SIM 1 VoLTE]`/`[SIM 1 VoWiFi]`/`[SIP]`/`[TOX]` badge, earpiece/speaker switching, microphone mute, DTMF keypad, and one-key normalized WAV call recording (`~/Recordings/rec_HHMMSS_<caller>.wav`). The call log includes a 5-tab view (`All`, `Miss`, `In`, `Out`, `Spam`) with integrated anti-spam number blocking (`~/.config/sxmo/block.tsv`) that automatically hangs up blocked callers and logs them to the `Spam` tab without triggering missed-call notifications.
- **Contacts (`xcontacts`) and SMS manager (`xsms`)**: full phonebook editor with direct Qualcomm QMI SIM card contact import and export across SIM 1 and SIM 2, paired with a threaded SMS conversation view that renders and scrolls full-length concatenated/Unicode (`UCS-2`) messages line by line, a multi-tap message composer with an encoding-aware GSM-7/UCS-2 segment counter and outgoing `SIM 1` / `SIM 2` selection when two SIMs are active, and built-in anti-spam blocklist / spam folder (`~/.local/share/sxmo/block`) with one-key thread blocking and restoration. - **Contacts (`xcontacts`) and SMS manager (`xsms`)**: full phonebook editor with direct Qualcomm QMI SIM card contact import and export across SIM 1 and SIM 2, paired with a threaded SMS conversation view that renders and scrolls full-length concatenated/Unicode (`UCS-2`) messages line by line, a multi-tap message composer with an encoding-aware GSM-7/UCS-2 segment counter, outgoing `SIM 1` / `SIM 2` selection when two SIMs are active, optional IMS `SMS-over-IP` (`RP-DATA`) transport when VoWiFi or userspace VoLTE is active, and built-in anti-spam blocklist / spam folder (`~/.local/share/sxmo/block`) with one-key thread blocking and restoration.
- **Modem and Dual-SIM manager (`xmodem`)**: 4-tab cellular control center (`SIMs`, `Radio`, `AT`, `Log`) supporting Dual-SIM Dual Standby (DSDS) with simultaneous network registration on both SIM slots, instant default SIM switching (`Set as Default SIM (Calls/SMS)`), full Primary/Secondary GW (`4G/Data`) slot swapping (`Make Primary GW (4G/Data Swap)`), SIM PIN unlock and PUK unblock wizards, 2G/3G/4G radio mode selection, interactive USSD sessions, and a live AT command console. - **Modem, Dual-SIM, Mobile Data (`wwan0`), and IMS / VoLTE / VoWiFi manager (`xmodem`, `bananarchy-imsd`, `bananarchy-vowifi`, `bananarchy-imsctl`)**: 5-tab cellular control center (`1:SIM`, `2:Rad`, `3:IMS`, `4:AT`, `5:Log`) supporting Dual-SIM Dual Standby (DSDS) with simultaneous network registration on both SIM slots, instant default SIM switching (`Set as Default SIM (Calls/SMS)`), full Primary/Secondary GW (`4G/Data`) slot swapping (`Make Primary GW (4G/Data Swap)`), event-driven `QMI_WDS` `PRIMARY` subscription binding (`libmm-wds-bind.so`), `Profile [1]`/`attach_pdn` APN synchronization, and automatic Dual-SIM `cs-only` pause/restore (`mobile-data-prep` / `restore-dsds`), SIM PIN unlock and PUK unblock wizards, 2G/3G/4G radio mode selection, Qualcomm MCFG `.mbn` IMS profile management (`install`, `select`, `remove`, MCC/MNC `auto-match`, `QMI_PDC`, and idle-isolated `QMI_IMSDCM`), VoLTE and VoWiFi (`SWu` IKEv2 + `EAP-AKA`/`EAP-AKA'` + UDP/4500 ESP + 3GPP SIP + `SMS-over-IP` with `AMR-WB`/`AMR-NB`), interactive USSD sessions, and a live AT command console. Both VoLTE and VoWiFi ship in `auto` mode (disabled at 0% idle CPU unless the active network is strictly **4G-only** or manually enabled).
- **Networks and Bluetooth manager (`xnetworks`) with OBEX file transfer (`bananarchy-bt-obex`)**: 3-tab connectivity manager for Wi-Fi networks, WPA2 password entry, Wi-Fi hotspot, USB tethering, 4G/LTE mobile data (`wwan0`) and APN editing, and Bluetooth pairing, with built-in Bluetooth OBEX Object Push reception (advertising Smartphone CoD `0x5a020c` without `a2dp_source` headset spoofing, supporting both L2CAP `SOCK_SEQPACKET` GOEP 2.0 and RFCOMM, presenting an incoming Accept/Reject and folder-selection modal in `xnetworks` alongside configurable persistent target folder in `~/.config/sxmo/bt_obex_dir`) and **Send via Bluetooth** in `xfiles`. Bluetooth discovery runs through `/usr/local/bin/bluetoothctl` and `bananarchy-bt-scan.sh`, which keeps one interactive `bluetoothctl` PTY client alive, sets auto transport and duplicate-data, queries `devices` during active discovery, and stops discovery cleanly so unpaired peripherals are not dropped when the scan command exits. A narrow `doas` helper runs `btmgmt -i hci0 le on` along with `bredr on`, `ssp on`, `linksec on`, `bondable on`, `advertising off`, and Smartphone controller class `2 3` so WCNSS pairs with Android phones and LE/Classic peripherals reliably (`PairableTimeout = 0`, while `DiscoverableTimeout = 60` stays off by default). BlueZ runs in `dual` controller mode because `bredr` mode rejects the LE-only HOGP profile, and `bananarchy-bt-obex` registers a persistent `KeyboardDisplay` `Agent1` that pops up interactive NeoUI pairing passkey confirmation, PIN/passkey keypad entry, and keyboard display codes inside `xnetworks` (while auto-confirming screenless Classic Audio headsets). Pair/connect actions run asynchronously (`--async-ui`), power the adapter on, enable LE/SSP, force the LE bearer for HID-over-GATT devices, prefer public BR/EDR bearers and A2DP/HFP `ConnectProfile` fallback for Classic Audio / dual-mode Bluetooth 5.x/6.x headsets, keep controller visibility hidden by default with a 60 s discoverable timeout to save standby battery, and pair unbonded peripherals before connecting. WirePlumber restricts headset roles to `a2dp_sink hsp_hs hfp_hf`, locks HFP to 8 kHz `cvsd` (disabling `msbc` and `lc3-a127`/`lc3` to match QDSP6 `INTERNAL_BT_SCO`), enables LDAC ABR (`quality = "auto"`) and `dummy-avrcp-player` for hardware volume, and forwards headset AVRCP media keys through `bananarchy-bt-obex` to `xmusic`. - **Networks and Bluetooth manager (`xnetworks`) with OBEX file transfer (`bananarchy-bt-obex`)**: 3-tab connectivity manager for Wi-Fi networks, WPA2 password entry, Wi-Fi hotspot, USB tethering, 4G/LTE mobile data (`wwan0`) and APN editing, and Bluetooth pairing, with built-in Bluetooth OBEX Object Push reception (advertising Smartphone CoD `0x5a020c` without `a2dp_source` headset spoofing, supporting both L2CAP `SOCK_SEQPACKET` GOEP 2.0 and RFCOMM, presenting an incoming Accept/Reject and folder-selection modal in `xnetworks` alongside configurable persistent target folder in `~/.config/sxmo/bt_obex_dir`) and **Send via Bluetooth** in `xfiles`. Bluetooth discovery runs through `/usr/local/bin/bluetoothctl` and `bananarchy-bt-scan.sh`, which keeps one interactive `bluetoothctl` PTY client alive, sets auto transport and duplicate-data, queries `devices` during active discovery, and stops discovery cleanly so unpaired peripherals are not dropped when the scan command exits. A narrow `doas` helper runs `btmgmt -i hci0 le on` along with `bredr on`, `ssp on`, `linksec on`, `bondable on`, `advertising off`, and Smartphone controller class `2 3` so WCNSS pairs with Android phones and LE/Classic peripherals reliably (`PairableTimeout = 0`, while `DiscoverableTimeout = 60` stays off by default). BlueZ runs in `dual` controller mode because `bredr` mode rejects the LE-only HOGP profile, and `bananarchy-bt-obex` registers a persistent `KeyboardDisplay` `Agent1` that pops up interactive NeoUI pairing passkey confirmation, PIN/passkey keypad entry, and keyboard display codes inside `xnetworks` (while auto-confirming screenless Classic Audio headsets). Pair/connect actions run asynchronously (`--async-ui`), power the adapter on, enable LE/SSP, force the LE bearer for HID-over-GATT devices, prefer public BR/EDR bearers and A2DP/HFP `ConnectProfile` fallback for Classic Audio / dual-mode Bluetooth 5.x/6.x headsets, keep controller visibility hidden by default with a 60 s discoverable timeout to save standby battery, and pair unbonded peripherals before connecting. WirePlumber restricts headset roles to `a2dp_sink hsp_hs hfp_hf`, locks HFP to 8 kHz `cvsd` (disabling `msbc` and `lc3-a127`/`lc3` to match QDSP6 `INTERNAL_BT_SCO`), enables LDAC ABR (`quality = "auto"`) and `dummy-avrcp-player` for hardware volume, and forwards headset AVRCP media keys through `bananarchy-bt-obex` to `xmusic`.
- **File manager (`xfiles`) with microSD automount (`sxmo_sdcard.sh`), Bluetooth file sharing, music and tracker player (`xmusic`), and camera (`xcamera`)**: keypad directory browser with automatic microSD card (`/dev/mmcblk1`) detection and `/media/sdcard` mounting/unmounting, **Send via Bluetooth** OBEX file push to paired/discovered devices, built-in text viewer, integrated GUI multi-tap text editor (`Edit in Text Editor`, available as an action on any file), image viewer, and dedicated monophonic ringtone viewer (`RingtoneView` for Nokia RTTTL `.nrt`/`.rtttl`/`.rtx`, Ericsson eMelody `.emy`, and IrDA iMelody `.imy` with graphical piano-roll pitch contour, note sequence viewer, live audio preview, and one-key assignment as call ringtone or notification/SMS sound — plus one-click actions to launch `.jar`/`.jad` MIDlets in the **ReMEdy (`remedy`)** J2ME emulator, launch `.gb`/`.gbc` ROMs in the Game Boy emulator, run `.yab` scripts in Yabasic inside the terminal, play audio, preview images, set any image as wallpaper, or install any audio, tracker, or monophonic melody file as call ringtone or notification/SMS sound), a 3-tab music and chiptune tracker module player (`WAV`, `MP3`, `OGG`, `FLAC`, `Opus`, `MOD`, `XM`, `IT`, `S3M`, `NRT`, `RTTTL`, `RTX`, `EMY`, `IMY`, and more), and a live V4L2 camera viewfinder with digital zoom, flash/torch control, self-timer, and photo gallery. - **File manager (`xfiles`) with microSD automount (`sxmo_sdcard.sh`), Bluetooth file sharing, `.mbn` IMS profile installation, music and tracker player (`xmusic`), and camera (`xcamera`)**: keypad directory browser with automatic microSD card (`/dev/mmcblk1`) detection and `/media/sdcard` mounting/unmounting, **Send via Bluetooth** OBEX file push to paired/discovered devices, Qualcomm MCFG `.mbn` metadata inspection and **Install IMS Profile** actions, built-in text viewer, integrated GUI multi-tap text editor (`Edit in Text Editor`, available as an action on any file), image viewer, and dedicated monophonic ringtone viewer (`RingtoneView` for Nokia RTTTL `.nrt`/`.rtttl`/`.rtx`, Ericsson eMelody `.emy`, and IrDA iMelody `.imy` with graphical piano-roll pitch contour, note sequence viewer, live audio preview, and one-key assignment as call ringtone or notification/SMS sound — plus one-click actions to launch `.jar`/`.jad` MIDlets in the **ReMEdy (`remedy`)** J2ME emulator, launch `.gb`/`.gbc` ROMs in the Game Boy emulator, run `.yab` scripts in Yabasic inside the terminal, play audio, preview images, set any image as wallpaper, or install any audio, tracker, or monophonic melody file as call ringtone or notification/SMS sound), a 3-tab music and chiptune tracker module player (`WAV`, `MP3`, `OGG`, `FLAC`, `Opus`, `MOD`, `XM`, `IT`, `S3M`, `NRT`, `RTTTL`, `RTX`, `EMY`, `IMY`, and more), and a live V4L2 camera viewfinder with digital zoom, flash/torch control, self-timer, and photo gallery.
- **Native NeoUI communication and internet suite (`xsip`, `xemail`, `xirc`, `xtox`, `xquagr`, `xkopher`, `webarchy`)**: - **Native NeoUI communication and internet suite (`xsip`, `xemail`, `xirc`, `xtox`, `xquagr`, `xkopher`, `webarchy`)**:
- **SIP VoIP client (`xsip` / `sip.so`)**: RFC 3261 SIP softphone (`Dialer`, `Accounts`, `History`) supporting both account-registered calling (with Digest MD5 authentication and standby `REGISTER` keepalive) and direct accountless P2P SIP URI calling (`user@host[:port]` or `sip:user@host[:port]`), RFC 3263 DNS `SRV` (`_sip._udp.<domain>`) proxy discovery and dialog routing, RFC 6189 **ZRTP** media-path Diffie-Hellman (`DH3k`/`DH2k`) key agreement and RFC 3711 **SRTP** (`AES-128-CM` + `HMAC-SHA1-80`) voice encryption with a 4-character `SAS` verification code, incoming `INVITE` ringing and call handling integrated with `xcallscreen` (`[SIP/<codec>]` / `[SIP/<codec>:<sas>]`), multi-codec wideband and narrowband RTP/SRTP audio (`Opus` 16 kHz / 48 kHz RTP clock with in-band FEC, `ITU-T G.722` 16 kHz wideband SB-ADPCM, `G.711 PCMU`/`PCMA` 8 kHz, `GSM 06.10` Full Rate 8 kHz, `ITU-T G.726-32` 8 kHz ADPCM, `IMA ADPCM DVI4` 8/16 kHz, and `L16` uncompressed 16-bit PCM 8/16 kHz) with per-account and direct-mode codec preference selection, and RFC 2833 / RFC 4733 DTMF. - **SIP VoIP client (`xsip` / `sip.so`)**: RFC 3261 SIP softphone (`Dialer`, `Accounts`, `History`) supporting both account-registered calling (with Digest MD5 authentication and standby `REGISTER` keepalive) and direct accountless P2P SIP URI calling (`user@host[:port]` or `sip:user@host[:port]`), RFC 3263 DNS `SRV` (`_sip._udp.<domain>`) proxy discovery and dialog routing, RFC 6189 **ZRTP** media-path Diffie-Hellman (`DH3k`/`DH2k`) key agreement and RFC 3711 **SRTP** (`AES-128-CM` + `HMAC-SHA1-80`) voice encryption with a 4-character `SAS` verification code, incoming `INVITE` ringing and call handling integrated with `xcallscreen` (`[SIP/<codec>]` / `[SIP/<codec>:<sas>]`), multi-codec wideband and narrowband RTP/SRTP audio (`Opus` 16 kHz / 48 kHz RTP clock with in-band FEC, `ITU-T G.722` 16 kHz wideband SB-ADPCM, `AMR-WB` 16 kHz, `AMR-NB` 8 kHz, `G.711 PCMU`/`PCMA` 8 kHz, `GSM 06.10` Full Rate 8 kHz, `ITU-T G.726-32` 8 kHz ADPCM, `IMA ADPCM DVI4` 8/16 kHz, and `L16` uncompressed 16-bit PCM 8/16 kHz) with per-account and direct-mode codec preference selection, and RFC 2833 / RFC 4733 DTMF.
- **Email client (`xemail` / `xmail` / `email.so`)**: multi-account `IMAP4rev1`, `POP3`, and `SMTP` client (`Inbox`, `Compose`, `Accounts`) supporting implicit TLS, `STARTTLS`, and plain TCP, SASL `PLAIN`/`LOGIN`, MIME RFC 2047/Base64/Quoted-Printable decoding, offline inbox cache, full-screen message reader, and composer. - **Email client (`xemail` / `xmail` / `email.so`)**: multi-account `IMAP4rev1`, `POP3`, and `SMTP` client (`Inbox`, `Compose`, `Accounts`) supporting implicit TLS, `STARTTLS`, and plain TCP, SASL `PLAIN`/`LOGIN`, MIME RFC 2047/Base64/Quoted-Printable decoding, offline inbox cache, full-screen message reader, and composer.
- **IRCv3 client (`xirc` / `irc.so`)**: multi-server IRC client (`Buffers`, `Chat`, `Servers`) with OpenSSL TLS, IRCv3 capability negotiation (`CAP LS 302`: `sasl`, `server-time`, `message-tags`, `multi-prefix`, `away-notify`, `account-notify`, `chghost`, `cap-notify`), `SASL PLAIN` authentication, slash commands, and resident background mode with highlight vibration alerts; the default network is Abjects (`irc.abjects.net`, TLS port `6697`) auto-joining `#bananarchy`. - **IRCv3 client (`xirc` / `irc.so`)**: multi-server IRC client (`Buffers`, `Chat`, `Servers`) with OpenSSL TLS, IRCv3 capability negotiation (`CAP LS 302`: `sasl`, `server-time`, `message-tags`, `multi-prefix`, `away-notify`, `account-notify`, `chghost`, `cap-notify`), `SASL PLAIN` authentication, slash commands, and resident background mode with highlight vibration alerts; the default network is Abjects (`irc.abjects.net`, TLS port `6697`) auto-joining `#bananarchy`.
- **Tox / Trifa P2P messenger and audio call client (`xtox` / `tox.so`)**: encrypted P2P messenger (`Friends`, `Chat`, `My Tox ID`) built on `c-toxcore` (`libtoxcore.so.2`) with DHT + TCP relay bootstrap, friend requests, persistent message history, and `ToxAV` 48 kHz Opus voice calls integrated with `xcallscreen`. - **Tox / Trifa P2P messenger and audio call client (`xtox` / `tox.so`)**: encrypted P2P messenger (`Friends`, `Chat`, `My Tox ID`) built on `c-toxcore` (`libtoxcore.so.2`) with DHT + TCP relay bootstrap, friend requests, persistent message history, and `ToxAV` 48 kHz Opus voice calls integrated with `xcallscreen`.
@@ -10,8 +10,14 @@ if [ "$1" = "wlan0" ]; then
esac esac
exit 0 exit 0
fi fi
[ "$1" = "qrtr0" ] || [ "$1" = "wwan0" ] || exit 0 [ "$1" = "qrtr0" ] || [ "$1" = "wwan0" ] || [ "$1" = "rmnet_data0" ] || exit 0
case "$2" in case "$2" in
up|vpn-up) /usr/bin/bananarchy-dpm.sh open ;; pre-up|up|vpn-up) /usr/bin/bananarchy-dpm.sh open ;;
down|post-down)
_pause_file="${BANANARCHY_RUNDIR:-/run/bananarchy}/dsds_paused_for_data"
if [ -f "$_pause_file" ]; then
"${BANANARCHY_UIM_SEL:-/usr/libexec/msm-modem-uim-selection}" restore-dsds >/dev/null 2>&1 || true
fi
;;
esac esac
exit 0 exit 0
@@ -0,0 +1,15 @@
#!/bin/sh
# Notify bananarchy-imsd on interface up/down/connectivity changes without blocking NM.
IFACE="${1:-any}"
EVENT="${2:-change}"
case "$EVENT" in
up|down|connectivity-change|dhcp4-change|dhcp6-change)
case "$IFACE" in
wlan*|wwan*|rmnet*|tun_ims)
/usr/bin/bananarchy-imsctl notify "$IFACE" "$EVENT" >/dev/null 2>&1 &
;;
esac
;;
esac
exit 0
@@ -0,0 +1,9 @@
#!/bin/sh
# Ensure BAM-DMUX wwan0 and PS/APN prerequisites are ready before cellular connect.
[ "${1:-}" = "qrtr0" ] || [ "${1:-}" = "wwan0" ] || exit 0
case "${2:-}" in
pre-up)
/usr/bin/bananarchy-dpm.sh open
;;
esac
exit 0
+16
View File
@@ -0,0 +1,16 @@
# Bananarchy IMS / VoLTE / VoWiFi configuration
# Default: disabled (idle) unless connected network is 4G-only (auto mode).
volte_mode=auto
vowifi_mode=auto
volte_backend=auto
epdg_server=
ims_apn=ims
ims_sim_slot=1
active_mbn=
auto_install_mbn=1
vowifi_roaming=0
wfc_preference=cellular_preferred
vowifi_codec=amr-wb
sip_realm=
pcscf_override=
keep_lte_on_screen_off=1
+3
View File
@@ -56,6 +56,9 @@ permit nopass :wheel as root cmd bananarchy-privacy-ctl
permit nopass :wheel as root cmd /usr/bin/bananarchy-display-power-sync permit nopass :wheel as root cmd /usr/bin/bananarchy-display-power-sync
permit nopass :wheel as root cmd /usr/bin/bananarchy-power-policy.sh permit nopass :wheel as root cmd /usr/bin/bananarchy-power-policy.sh
permit nopass :wheel as root cmd bananarchy-power-policy.sh permit nopass :wheel as root cmd bananarchy-power-policy.sh
permit nopass :wheel as root cmd /usr/bin/bananarchy-imsctl
permit nopass :wheel as root cmd bananarchy-imsctl
permit nopass :wheel as root cmd /usr/bin/bananarchy-ims-bearer.sh
permit nopass :wheel as root cmd /usr/bin/bananarchy-time-sync.sh permit nopass :wheel as root cmd /usr/bin/bananarchy-time-sync.sh
permit nopass :wheel as root cmd bananarchy-time-sync.sh permit nopass :wheel as root cmd bananarchy-time-sync.sh
permit nopass :wheel as root cmd bananarchy-display-power-sync permit nopass :wheel as root cmd bananarchy-display-power-sync
+11
View File
@@ -0,0 +1,11 @@
#!/sbin/openrc-run
description="Bananarchy event-driven IMS / VoLTE / VoWiFi / MBN daemon"
supervisor=supervise-daemon
command="/usr/bin/bananarchy-imsd"
respawn_delay=3
respawn_max=5
retry="TERM/3/KILL/1"
depend() {
after rmtfs msm-modem-uim-selection modemmanager networkmanager
}
+3
View File
@@ -15,6 +15,9 @@ depend() {
start_pre() { start_pre() {
killall -q ModemManager 2>/dev/null || true killall -q ModemManager 2>/dev/null || true
if [ -r /usr/lib/libmm-wds-bind.so ]; then
export LD_PRELOAD="/usr/lib/libmm-wds-bind.so${LD_PRELOAD:+:$LD_PRELOAD}"
fi
} }
stop_post() { stop_post() {
+1
View File
@@ -0,0 +1 @@
/etc/init.d/bananarchy-imsd
@@ -42,6 +42,14 @@ if command -v nmcli >/dev/null 2>&1; then
*wifi:connected*) line="$line WIFI" ;; *wifi:connected*) line="$line WIFI" ;;
esac esac
fi fi
IMS_STATE_FILE="${BANANARCHY_IMS_STATE_PATH:-/run/bananarchy/ims/state.env}"
if [ -r "$IMS_STATE_FILE" ]; then
if grep -q '^VOWIFI_REGISTERED=1$' "$IMS_STATE_FILE" 2>/dev/null; then
line="$line VOWIFI"
elif grep -q '^VOLTE_REGISTERED=1$' "$IMS_STATE_FILE" 2>/dev/null; then
line="$line VOLTE"
fi
fi
line="$(printf '%s' "$line" | tr -s ' ' | sed 's/^ *//' | cut -c1-40)" line="$(printf '%s' "$line" | tr -s ' ' | sed 's/^ *//' | cut -c1-40)"
[ -n "$line" ] && "$COVERCTL" NETWORK "$line" >/dev/null 2>&1 || true [ -n "$line" ] && "$COVERCTL" NETWORK "$line" >/dev/null 2>&1 || true
+112
View File
@@ -0,0 +1,112 @@
#!/bin/sh
# Bananarchy dedicated IMS APN (QMI WDS + RmNet / WWAN) bearer helper.
set -eu
ACTION="${1:-up}"
APN="${2:-ims}"
STATE_DIR="${BANANARCHY_IMS_STATE_DIR:-/run/bananarchy/ims}"
BEARER_ENV="$STATE_DIR/bearer.env"
mkdir -p "$STATE_DIR"
if [ -n "${BANANARCHY_MOCK_BEARER_IP:-}" ]; then
MOCK_IF="${BANANARCHY_MOCK_BEARER_IFACE:-wwan1}"
if [ "$ACTION" = "up" ]; then
cat >"$BEARER_ENV" <<EOF
IFACE=$MOCK_IF
IP=$BANANARCHY_MOCK_BEARER_IP
EOF
printf "IFACE=%s\nIP=%s\n" "$MOCK_IF" "$BANANARCHY_MOCK_BEARER_IP"
else
rm -f "$BEARER_ENV"
printf "IFACE=\nIP=\n"
fi
exit 0
fi
find_qmi_dev() {
for d in /dev/wwan0qmi0 /dev/cdc-wdm0 qrtr://0; do
if [ "$d" = "qrtr://0" ] || [ -e "$d" ]; then
printf '%s\n' "$d"
return 0
fi
done
return 1
}
if [ "$ACTION" = "down" ]; then
if [ -r "$BEARER_ENV" ]; then
IFACE=""
HANDLE=""
QMI_DEV=""
# shellcheck disable=SC1090
. "$BEARER_ENV" 2>/dev/null || true
if [ -n "${HANDLE:-}" ] && [ -n "${QMI_DEV:-}" ] && command -v qmicli >/dev/null 2>&1; then
qmicli -p -d "$QMI_DEV" --wds-stop-network="$HANDLE" --client-no-release-cid >/dev/null 2>&1 || true
fi
if [ -n "${IFACE:-}" ] && [ "$IFACE" != "wwan0" ] && [ -e "/sys/class/net/$IFACE" ] && command -v ip >/dev/null 2>&1; then
ip route flush table 204 >/dev/null 2>&1 || true
ip addr flush dev "$IFACE" >/dev/null 2>&1 || true
fi
fi
rm -f "$BEARER_ENV"
printf "IFACE=\nIP=\n"
exit 0
fi
QMI_DEV="$(find_qmi_dev || true)"
IFACE="${BANANARCHY_IMS_NET_IFACE:-wwan1}"
if [ ! -e "/sys/class/net/$IFACE" ] && [ -e "/sys/class/net/rmnet_data1" ]; then
IFACE="rmnet_data1"
fi
# Never hijack ModemManager's primary mobile-data netdev (wwan0) for IMS.
if [ "$IFACE" = "wwan0" ]; then
printf "IFACE=\nIP=\n"
exit 1
fi
if [ ! -e "/sys/class/net/$IFACE" ] && [ -n "$QMI_DEV" ] && command -v qmicli >/dev/null 2>&1; then
timeout 3 qmicli --silent -pd "$QMI_DEV" --dpm-open-port="hw-data-ep-type=bam-dmux,hw-data-ep-iface-number=2,hw-data-rx-id=2,hw-data-tx-id=2" >/dev/null 2>&1 || true
_w=0
while [ "$_w" -lt 10 ] && [ ! -e "/sys/class/net/$IFACE" ]; do
sleep 0.1
_w=$((_w + 1))
done
fi
if [ ! -e "/sys/class/net/$IFACE" ]; then
rm -f "$BEARER_ENV"
printf "IFACE=\nIP=\n"
exit 1
fi
if [ -n "$QMI_DEV" ] && command -v qmicli >/dev/null 2>&1; then
[ "$IFACE" = "wwan1" ] && timeout 3 qmicli --silent -p -d "$QMI_DEV" --wds-bind-data-port="a2-mux-rmnet2" --client-no-release-cid >/dev/null 2>&1 || true
WDS_OUT="$(timeout 6 qmicli -p -d "$QMI_DEV" --device-open-sync \
--wds-start-network="apn=$APN,ip-type=4" --client-no-release-cid 2>/dev/null || true)"
HANDLE="$(printf '%s\n' "$WDS_OUT" | sed -n 's/.*Packet data handle: '\''\?\([0-9]*\)'\''\?.*/\1/p' | head -n1)"
SETTINGS="$(timeout 4 qmicli -p -d "$QMI_DEV" --wds-get-current-settings --client-no-release-cid 2>/dev/null || true)"
IP4="$(printf '%s\n' "$SETTINGS" | sed -n 's/.*IPv4 address: //p' | head -n1 | tr -d ' \r')"
GW4="$(printf '%s\n' "$SETTINGS" | sed -n 's/.*IPv4 gateway address: //p' | head -n1 | tr -d ' \r')"
PCSCF="$(printf '%s\n' "$SETTINGS" | sed -n 's/.*P-CSCF IPv4 address: //p' | head -n1 | tr -d ' \r')"
if [ -n "$IP4" ] && command -v ip >/dev/null 2>&1; then
ip link set dev "$IFACE" up >/dev/null 2>&1 || true
ip addr replace "$IP4/30" dev "$IFACE" >/dev/null 2>&1 || true
[ -n "$GW4" ] && ip route replace default via "$GW4" dev "$IFACE" table 204 >/dev/null 2>&1 || \
ip route replace default dev "$IFACE" table 204 >/dev/null 2>&1 || true
ip rule add from "$IP4/32" table 204 pref 204 >/dev/null 2>&1 || true
fi
cat >"$BEARER_ENV" <<EOF
IFACE=$IFACE
IP=${IP4:-}
GW=${GW4:-}
PCSCF=${PCSCF:-}
HANDLE=${HANDLE:-}
QMI_DEV=$QMI_DEV
EOF
printf "IFACE=%s\nIP=%s\nPCSCF=%s\n" "$IFACE" "${IP4:-}" "${PCSCF:-}"
[ -n "$IP4" ] && exit 0 || exit 1
fi
printf "IFACE=\nIP=\n"
exit 1
Binary file not shown.
Binary file not shown.
@@ -191,10 +191,27 @@ apply_cpu_lpm() {
esac esac
} }
ims_state_val() {
_key="$1"
_st="${BANANARCHY_IMS_STATE_PATH:-/run/bananarchy/ims/state.env}"
[ -r "$_st" ] || return 0
awk -F= -v k="$_key" '$1 == k { gsub(/\047/, "", $2); print $2; exit }' "$_st" 2>/dev/null || true
}
ims_conf_val() {
_key="$1"
_cf="${BANANARCHY_IMS_CONF_PATH:-/etc/bananarchy/ims.conf}"
[ -r "$_cf" ] || return 0
awk -F= -v k="$_key" '$1 == k { print $2; exit }' "$_cf" 2>/dev/null || true
}
mute_wifi_ipv6_ra() { mute_wifi_ipv6_ra() {
[ "$WIFI_SCREEN_OFF_IPV6_MUTE" = "1" ] || return 0 [ "$WIFI_SCREEN_OFF_IPV6_MUTE" = "1" ] || return 0
[ -w "$ACCEPT_RA" ] || return 0 [ -w "$ACCEPT_RA" ] || return 0
ip -4 addr show dev wlan0 2>/dev/null | grep -q 'inet ' || return 0 ip -4 addr show dev wlan0 2>/dev/null | grep -q 'inet ' || return 0
if [ "$(ims_state_val VOWIFI_ACTIVE)" = "1" ] && [ "$(ims_state_val VOWIFI_IPV6_EPDG)" = "1" ]; then
return 0
fi
if [ ! -f "$IPV6_RA_SAVED" ]; then if [ ! -f "$IPV6_RA_SAVED" ]; then
cur_ra="" cur_ra=""
IFS= read -r cur_ra < "$ACCEPT_RA" 2>/dev/null || cur_ra="" IFS= read -r cur_ra < "$ACCEPT_RA" 2>/dev/null || cur_ra=""
@@ -243,6 +260,9 @@ park_wifi_rat() {
[ -f "$RAT_PARKED" ] && return 0 [ -f "$RAT_PARKED" ] && return 0
[ -f "$GSM_UNSUPPORTED" ] && return 0 [ -f "$GSM_UNSUPPORTED" ] && return 0
has_active_call && return 0 has_active_call && return 0
if [ "$(ims_state_val VOLTE_ACTIVE)" = "1" ] && [ "$(ims_state_val VOWIFI_ACTIVE)" != "1" ]; then
[ "$(ims_conf_val keep_lte_on_screen_off)" != "0" ] && return 0
fi
oper="" oper=""
[ -r "$WLAN_OPERSTATE_PATH" ] && { IFS= read -r oper < "$WLAN_OPERSTATE_PATH" 2>/dev/null || oper=""; } [ -r "$WLAN_OPERSTATE_PATH" ] && { IFS= read -r oper < "$WLAN_OPERSTATE_PATH" 2>/dev/null || oper=""; }
[ "$oper" = "up" ] || return 0 [ "$oper" = "up" ] || return 0
Binary file not shown.
+42 -2
View File
@@ -19,6 +19,21 @@ set -e
vid_to_number() { vid_to_number() {
case "$1" in case "$1" in
vowifi:*|vowifi_*|ims:*|ims_*)
_safe="$(printf '%s' "$1" | tr ':/' '__')"
for _cf in "$XDG_RUNTIME_DIR/sxmo_calls/${_safe}."* "$XDG_RUNTIME_DIR/sxmo_calls/${1}."*; do
[ -r "$_cf" ] || continue
head -n1 "$_cf" 2>/dev/null || true
return 0
done
;;
vowifi:*|vowifi_*|ims:*|ims_*)
_safe="$(printf '%s' "$CALLID" | tr ':/' '__')"
rm -f "$XDG_RUNTIME_DIR/sxmo_calls/${_safe}."* /tmp/sxmo_call_ringing /tmp/sxmo_active_call 2>/dev/null || true
"${BANANARCHY_IMS_CTL:-/usr/bin/bananarchy-imsctl}" call-hangup "$CALLID" >/dev/null 2>&1 || true
sxmo_hook_hangup.sh || true
return 0
;;
sub1_*|sub0_*) sub1_*|sub0_*)
doas -n /usr/libexec/msm-modem-uim-selection call-list 2>/dev/null | awk -F'\t' -v id="$1" '$1 == id {print $4; exit}' doas -n /usr/libexec/msm-modem-uim-selection call-list 2>/dev/null | awk -F'\t' -v id="$1" '$1 == id {print $4; exit}'
;; ;;
@@ -53,6 +68,17 @@ pickup() {
NUM="$(vid_to_number "$CALLID" 2>/dev/null || true)" NUM="$(vid_to_number "$CALLID" 2>/dev/null || true)"
case "$CALLID" in case "$CALLID" in
vowifi:*|vowifi_*|ims:*|ims_*)
sxmo_log "Invoking IMS userspace pickup for $CALLID"
sxmo_hook_pickup.sh || true
"${BANANARCHY_IMS_CTL:-/usr/bin/bananarchy-imsctl}" call-accept "$CALLID" >/dev/null 2>&1 || true
_safe="$(printf '%s' "$CALLID" | tr ':/' '__')"
touch "$XDG_RUNTIME_DIR/sxmo_calls/${_safe}.pickedupcall"
if command -v xcallscreen >/dev/null 2>&1; then
xcallscreen active "$CALLID" "$NUM" >/dev/null 2>&1 || true
fi
return 0
;;
sub1_*|sub0_*) sub1_*|sub0_*)
sxmo_log "Invoking pickup hook for $CALLID" sxmo_log "Invoking pickup hook for $CALLID"
sxmo_hook_pickup.sh || true sxmo_hook_pickup.sh || true
@@ -153,6 +179,8 @@ hangup() {
rm -f "$XDG_RUNTIME_DIR"/sxmo_calls/sub1_* "$XDG_RUNTIME_DIR"/sxmo_calls/sub0_* /tmp/sxmo_call_ringing /tmp/sxmo_active_call 2>/dev/null || true rm -f "$XDG_RUNTIME_DIR"/sxmo_calls/sub1_* "$XDG_RUNTIME_DIR"/sxmo_calls/sub0_* /tmp/sxmo_call_ringing /tmp/sxmo_active_call 2>/dev/null || true
doas -n /usr/libexec/msm-modem-uim-selection call-hangup all >/dev/null 2>&1 || \ doas -n /usr/libexec/msm-modem-uim-selection call-hangup all >/dev/null 2>&1 || \
/usr/libexec/msm-modem-uim-selection call-hangup all >/dev/null 2>&1 || true /usr/libexec/msm-modem-uim-selection call-hangup all >/dev/null 2>&1 || true
"${BANANARCHY_IMS_CTL:-/usr/bin/bananarchy-imsctl}" call-hangup >/dev/null 2>&1 || true
rm -f "$XDG_RUNTIME_DIR"/sxmo_calls/vowifi_* "$XDG_RUNTIME_DIR"/sxmo_calls/ims_* 2>/dev/null || true
mmcli -m any --voice-hangup-all >/dev/null 2>&1 || true mmcli -m any --voice-hangup-all >/dev/null 2>&1 || true
for cid in $(mmcli -m any --voice-list-calls 2>/dev/null | grep -oE 'Call/[0-9]+' | cut -d/ -f2); do for cid in $(mmcli -m any --voice-list-calls 2>/dev/null | grep -oE 'Call/[0-9]+' | cut -d/ -f2); do
mmcli -m any -o "$cid" --hangup >/dev/null 2>&1 || true mmcli -m any -o "$cid" --hangup >/dev/null 2>&1 || true
@@ -172,6 +200,13 @@ hangup() {
sxmo_hook_hangup.sh || true sxmo_hook_hangup.sh || true
return 0 return 0
;; ;;
vowifi:*|vowifi_*|ims:*|ims_*)
_safe="$(printf '%s' "$CALLID" | tr ':/' '__')"
rm -f "$XDG_RUNTIME_DIR/sxmo_calls/${_safe}."* /tmp/sxmo_call_ringing /tmp/sxmo_active_call 2>/dev/null || true
"${BANANARCHY_IMS_CTL:-/usr/bin/bananarchy-imsctl}" call-hangup "$CALLID" >/dev/null 2>&1 || true
sxmo_hook_hangup.sh || true
return 0
;;
sub1_*|sub0_*) sub1_*|sub0_*)
rm -f "$XDG_RUNTIME_DIR/sxmo_calls/${CALLID}."* "$XDG_RUNTIME_DIR/sxmo_calls/sub1_dialing."* /tmp/sxmo_call_ringing /tmp/sxmo_active_call 2>/dev/null || true rm -f "$XDG_RUNTIME_DIR/sxmo_calls/${CALLID}."* "$XDG_RUNTIME_DIR/sxmo_calls/sub1_dialing."* /tmp/sxmo_call_ringing /tmp/sxmo_active_call 2>/dev/null || true
doas -n /usr/libexec/msm-modem-uim-selection call-hangup "$CALLID" >/dev/null 2>&1 || \ doas -n /usr/libexec/msm-modem-uim-selection call-hangup "$CALLID" >/dev/null 2>&1 || \
@@ -247,13 +282,13 @@ list_active_calls() {
fi fi
printf "%s\n" "$line" printf "%s\n" "$line"
done done
for f in "$XDG_RUNTIME_DIR"/sxmo_calls/sub1_*.*; do for f in "$XDG_RUNTIME_DIR"/sxmo_calls/sub1_*.* "$XDG_RUNTIME_DIR"/sxmo_calls/vowifi_*.* "$XDG_RUNTIME_DIR"/sxmo_calls/ims_*.*; do
[ -e "$f" ] || continue [ -e "$f" ] || continue
base="${f##*/}" base="${f##*/}"
cid="${base%%.*}" cid="${base%%.*}"
st="${base#*.}" st="${base#*.}"
case "$st" in case "$st" in
ringing-in|dialing|ringing-out|active|held|waiting) ringing-in|dialing|ringing-out|pickedupcall|initiatedcall|active|held|waiting)
if [ ! -e "$XDG_RUNTIME_DIR/sxmo_calls/${cid}.mutedring" ]; then if [ ! -e "$XDG_RUNTIME_DIR/sxmo_calls/${cid}.mutedring" ]; then
printf "/org/freedesktop/ModemManager1/Call/%s (%s)\n" "$cid" "$st" printf "/org/freedesktop/ModemManager1/Call/%s (%s)\n" "$cid" "$st"
fi fi
@@ -296,6 +331,11 @@ mute() {
incoming_call_menu() { incoming_call_menu() {
case "$1" in case "$1" in
vowifi:*|vowifi_*|ims:*|ims_*)
_safe="$(printf '%s' "$1" | tr ':/' '__')"
[ -e "$XDG_RUNTIME_DIR/sxmo_calls/${_safe}.ringing-in" ] || \
[ -e "$XDG_RUNTIME_DIR/sxmo_calls/${1}.ringing-in" ] || return 0
;;
sub1_*|sub0_*) sub1_*|sub0_*)
[ -e "$XDG_RUNTIME_DIR/sxmo_calls/${1}.ringing-in" ] || return 0 [ -e "$XDG_RUNTIME_DIR/sxmo_calls/${1}.ringing-in" ] || return 0
;; ;;
+89
View File
@@ -36,6 +36,75 @@ resolve_sim_state() {
[ -n "$DUAL_ACTIVE" ] || DUAL_ACTIVE="0" [ -n "$DUAL_ACTIVE" ] || DUAL_ACTIVE="0"
} }
is_emergency_number() {
case "$1" in
112|911|999|000|110|118|119|998) return 0 ;;
*) return 1 ;;
esac
}
ims_read_kv() {
awk -F= -v k="$1" '$1 == k { gsub(/\047/, "", $2); print $2; exit }' "$2" 2>/dev/null || true
}
ims_should_prefer_userspace() {
_slot="$1"
_emerg="$2"
_st="${BANANARCHY_IMS_STATE_PATH:-/run/bananarchy/ims/state.env}"
_cf="${BANANARCHY_IMS_CONF_PATH:-/etc/bananarchy/ims.conf}"
[ -r "$_st" ] || return 1
IMS_VOWIFI_REG="$(ims_read_kv VOWIFI_REGISTERED "$_st")"
IMS_VOLTE_REG="$(ims_read_kv VOLTE_REGISTERED "$_st")"
IMS_VOLTE_BACK="$(ims_read_kv VOLTE_BACKEND "$_st")"
IMS_NET4G="$(ims_read_kv NETWORK_4G_ONLY "$_st")"
IMS_SIM="$(ims_read_kv VOWIFI_SIM "$_st")"
IMS_WFC_PREF="$(ims_read_kv wfc_preference "$_cf")"
[ -n "$IMS_SIM" ] || IMS_SIM="1"
[ -n "$IMS_WFC_PREF" ] || IMS_WFC_PREF="cellular_preferred"
if [ "$_emerg" = "1" ]; then
return 1
fi
[ "$_slot" = "$IMS_SIM" ] || return 1
if [ "$IMS_VOWIFI_REG" = "1" ]; then
case "$IMS_WFC_PREF" in
wifi_only|wifi_preferred) return 0 ;;
*) [ "$IMS_NET4G" = "1" ] && return 0 ;;
esac
fi
if [ "$IMS_VOLTE_BACK" = "userspace" ] && [ "$IMS_VOLTE_REG" = "1" ]; then
return 0
fi
return 1
}
ims_dial_userspace() {
_num="$1"
_slot="$2"
_ctl="${BANANARCHY_IMS_CTL:-/usr/bin/bananarchy-imsctl}"
[ -x "$_ctl" ] || return 1
_tag="VOWIFI${_slot}"
[ "${IMS_VOWIFI_REG:-0}" = "1" ] || _tag="VOLTE${_slot}"
if [ -p "/tmp/dwm_plugin_callscreen.fifo" ]; then
printf "OUTGOING - %s %s\n" "$_num" "$_tag" > /tmp/dwm_plugin_callscreen.fifo 2>/dev/null || true
elif command -v xcallscreen >/dev/null 2>&1; then
xcallscreen outgoing "-" "$_num" "$_tag" >/dev/null 2>&1 || true
fi
_out="$("$_ctl" call-dial "$_num" 2>/dev/null || true)"
_cid="$(printf '%s\n' "$_out" | awk '/^OK / { print $2; exit }')"
[ -n "$_cid" ] || return 1
_safe_cid="$(printf '%s' "$_cid" | tr ':/' '__')"
touch "$XDG_RUNTIME_DIR/sxmo_calls/${_safe_cid}.initiatedcall" 2>/dev/null || true
if [ -p "/tmp/dwm_plugin_callscreen.fifo" ]; then
printf "OUTGOING %s %s %s\n" "$_cid" "$_num" "$_tag" > /tmp/dwm_plugin_callscreen.fifo 2>/dev/null || true
elif command -v xcallscreen >/dev/null 2>&1; then
xcallscreen outgoing "$_cid" "$_num" "$_tag" >/dev/null 2>&1 || true
fi
sxmo_hook_dial.sh || true
sxmo_modemaudio.sh setup_audio || true
sxmo_hook_statusbar.sh state &
return 0
}
dial_number() { dial_number() {
NUMBER="$(printf "%s" "$1" | tr -cd '+0-9*#')" NUMBER="$(printf "%s" "$1" | tr -cd '+0-9*#')"
if [ -z "$NUMBER" ]; then if [ -z "$NUMBER" ]; then
@@ -67,6 +136,21 @@ dial_number() {
fi fi
[ -n "$TARGET_SIM" ] || TARGET_SIM="$PRIM_SLOT" [ -n "$TARGET_SIM" ] || TARGET_SIM="$PRIM_SLOT"
IS_EMERG=0
is_emergency_number "$NUMBER" && IS_EMERG=1
if ims_should_prefer_userspace "$TARGET_SIM" "$IS_EMERG"; then
if ims_dial_userspace "$NUMBER" "$TARGET_SIM"; then
return 0
fi
[ "${IMS_WFC_PREF:-}" = "wifi_only" ] && {
if command -v xcallscreen >/dev/null 2>&1; then
xcallscreen ended >/dev/null 2>&1 || true
fi
sxmo_notify_user.sh --urgency=critical "VoWiFi call failed (wifi_only mode)"
return 1
}
fi
# Secondary GW SIM call via QMI VOICE sub=1 # Secondary GW SIM call via QMI VOICE sub=1
if [ "$TARGET_SIM" = "$SEC_SLOT" ] && [ "$SEC_SLOT" != "0" ]; then if [ "$TARGET_SIM" = "$SEC_SLOT" ] && [ "$SEC_SLOT" != "0" ]; then
sxmo_log "Attempting to dial on Secondary GW (SIM $TARGET_SIM): $NUMBER" sxmo_log "Attempting to dial on Secondary GW (SIM $TARGET_SIM): $NUMBER"
@@ -127,6 +211,11 @@ dial_number() {
fi fi
if [ -z "$CALLID" ]; then if [ -z "$CALLID" ]; then
if [ ! -f /tmp/sxmo_hangup_requested ]; then if [ ! -f /tmp/sxmo_hangup_requested ]; then
if [ "$IS_EMERG" = "1" ] && [ "${IMS_VOWIFI_REG:-0}" = "1" ]; then
if ims_dial_userspace "$NUMBER" "$TARGET_SIM"; then
return 0
fi
fi
if command -v xcallscreen >/dev/null 2>&1; then if command -v xcallscreen >/dev/null 2>&1; then
xcallscreen ended >/dev/null 2>&1 || true xcallscreen ended >/dev/null 2>&1 || true
fi fi
+14 -1
View File
@@ -154,7 +154,20 @@ else
[ -n "$TARGET_SIM" ] || TARGET_SIM="$PREF_SLOT" [ -n "$TARGET_SIM" ] || TARGET_SIM="$PREF_SLOT"
SENT_VIA_QMI=0 SENT_VIA_QMI=0
if [ "$TARGET_SIM" = "$SEC_SLOT" ] && [ "$SEC_SLOT" != "0" ]; then IMS_STATE_FILE="${BANANARCHY_IMS_STATE_PATH:-/run/bananarchy/ims/state.env}"
if [ -r "$IMS_STATE_FILE" ] && [ -x "${BANANARCHY_IMS_CTL:-/usr/bin/bananarchy-imsctl}" ]; then
IMS_VOWIFI_REG="$(awk -F= '$1=="VOWIFI_REGISTERED"{print $2; exit}' "$IMS_STATE_FILE" 2>/dev/null || true)"
IMS_VOLTE_REG="$(awk -F= '$1=="VOLTE_REGISTERED"{print $2; exit}' "$IMS_STATE_FILE" 2>/dev/null || true)"
IMS_VOLTE_BACK="$(awk -F= '$1=="VOLTE_BACKEND"{print $2; exit}' "$IMS_STATE_FILE" 2>/dev/null || true)"
IMS_SIM="$(awk -F= '$1=="VOWIFI_SIM"{print $2; exit}' "$IMS_STATE_FILE" 2>/dev/null || true)"
[ -n "$IMS_SIM" ] || IMS_SIM="1"
if [ "$TARGET_SIM" = "$IMS_SIM" ] && { [ "$IMS_VOWIFI_REG" = "1" ] || { [ "$IMS_VOLTE_BACK" = "userspace" ] && [ "$IMS_VOLTE_REG" = "1" ]; }; }; then
if "${BANANARCHY_IMS_CTL:-/usr/bin/bananarchy-imsctl}" sms-send "$NUMBER" "$(cat "$TEXTFILE")" >/dev/null 2>&1; then
SENT_VIA_QMI=1
fi
fi
fi
if [ "$SENT_VIA_QMI" = "0" ] && [ "$TARGET_SIM" = "$SEC_SLOT" ] && [ "$SEC_SLOT" != "0" ]; then
if doas -n /usr/libexec/msm-modem-uim-selection sms-send "$TARGET_SIM" "$NUMBER" "$TEXTFILE" >/dev/null 2>&1 || \ if doas -n /usr/libexec/msm-modem-uim-selection sms-send "$TARGET_SIM" "$NUMBER" "$TEXTFILE" >/dev/null 2>&1 || \
/usr/libexec/msm-modem-uim-selection sms-send "$TARGET_SIM" "$NUMBER" "$TEXTFILE" >/dev/null 2>&1; then /usr/libexec/msm-modem-uim-selection sms-send "$TARGET_SIM" "$NUMBER" "$TEXTFILE" >/dev/null 2>&1; then
SENT_VIA_QMI=1 SENT_VIA_QMI=1
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -10,6 +10,7 @@ fi
SIM_WAIT_TIME="${SIM_WAIT_TIME:-${sim_wait_time:-4}}" SIM_WAIT_TIME="${SIM_WAIT_TIME:-${sim_wait_time:-4}}"
PREFERRED_SIM_SLOT="${PREFERRED_SIM_SLOT:-${preferred_sim_slot:-1}}" PREFERRED_SIM_SLOT="${PREFERRED_SIM_SLOT:-${preferred_sim_slot:-1}}"
QMICLI_BIN="${BANANARCHY_QMICLI_BIN:-qmicli}"
QMICLI_MODEM="" QMICLI_MODEM=""
ensure_usb_network_gadget() { ensure_usb_network_gadget() {
@@ -62,30 +63,34 @@ ensure_usb_network_gadget() {
} }
detect_qmicli_modem() { detect_qmicli_modem() {
if ! command -v qmicli >/dev/null 2>&1; then if [ -n "${BANANARCHY_QMICLI_BIN:-}" ] && [ -x "$BANANARCHY_QMICLI_BIN" ]; then
QMICLI_MODEM="$BANANARCHY_QMICLI_BIN"
return 0
fi
if ! command -v "$QMICLI_BIN" >/dev/null 2>&1; then
return 1 return 1
fi fi
if [ -e "/dev/wwan0qmi0" ]; then if [ -e "/dev/wwan0qmi0" ]; then
if timeout 3 qmicli --silent -pd /dev/wwan0qmi0 --device-open-qmi --uim-noop >/dev/null 2>&1; then if timeout 3 "$QMICLI_BIN" --silent -pd /dev/wwan0qmi0 --device-open-qmi --uim-noop >/dev/null 2>&1; then
QMICLI_MODEM="timeout 4 qmicli --silent -pd /dev/wwan0qmi0 --device-open-qmi" QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -pd /dev/wwan0qmi0 --device-open-qmi"
return 0 return 0
elif timeout 3 qmicli --silent -d /dev/wwan0qmi0 --device-open-qmi --uim-noop >/dev/null 2>&1; then elif timeout 3 "$QMICLI_BIN" --silent -d /dev/wwan0qmi0 --device-open-qmi --uim-noop >/dev/null 2>&1; then
QMICLI_MODEM="timeout 4 qmicli --silent -d /dev/wwan0qmi0 --device-open-qmi" QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -d /dev/wwan0qmi0 --device-open-qmi"
return 0 return 0
fi fi
fi fi
if timeout 3 qmicli --silent -d qrtr://0 --uim-noop >/dev/null 2>&1; then if timeout 3 "$QMICLI_BIN" --silent -d qrtr://0 --uim-noop >/dev/null 2>&1; then
QMICLI_MODEM="timeout 4 qmicli --silent -d qrtr://0" QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -d qrtr://0"
return 0 return 0
elif timeout 3 qmicli --silent -pd qrtr://0 --uim-noop >/dev/null 2>&1; then elif timeout 3 "$QMICLI_BIN" --silent -pd qrtr://0 --uim-noop >/dev/null 2>&1; then
QMICLI_MODEM="timeout 4 qmicli --silent -pd qrtr://0" QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -pd qrtr://0"
return 0 return 0
elif [ -e "/dev/modem" ]; then elif [ -e "/dev/modem" ]; then
if timeout 3 qmicli --silent -pd /dev/modem --uim-noop >/dev/null 2>&1; then if timeout 3 "$QMICLI_BIN" --silent -pd /dev/modem --uim-noop >/dev/null 2>&1; then
QMICLI_MODEM="timeout 4 qmicli --silent -pd /dev/modem" QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -pd /dev/modem"
return 0 return 0
elif timeout 3 qmicli --silent -d /dev/modem --uim-noop >/dev/null 2>&1; then elif timeout 3 "$QMICLI_BIN" --silent -d /dev/modem --uim-noop >/dev/null 2>&1; then
QMICLI_MODEM="timeout 4 qmicli --silent -d /dev/modem" QMICLI_MODEM="timeout 4 $QMICLI_BIN --silent -d /dev/modem"
return 0 return 0
fi fi
fi fi
@@ -408,68 +413,465 @@ save_preferred_slot() {
} }
ensure_dsds_nas_registration() { ensure_dsds_nas_registration() {
dual_arg="${1:-auto}"
if ! command -v python3 >/dev/null 2>&1; then if ! command -v python3 >/dev/null 2>&1; then
return 0 return 0
fi fi
python3 - << 'PY' >/dev/null 2>&1 || true rat_parked=0
import socket, struct, select [ -f "${BANANARCHY_POWER_RUNDIR:-/run/bananarchy-power-policy}/rat_parked" ] && rat_parked=1
_dsds_file="${BANANARCHY_DSDS_ACTIVE_FILE:-/tmp/sxmo_dsds_active}"
if [ "$dual_arg" = "1" ] || [ "$dual_arg" = "0" ]; then
dual_flag="$dual_arg"
elif [ "${BANANARCHY_DUAL_SIM:-}" = "1" ]; then
dual_flag="1"
elif [ "${BANANARCHY_DUAL_SIM:-}" = "0" ]; then
dual_flag="0"
elif [ -r "$_dsds_file" ] && [ "$(tr -d ' \r\n' < "$_dsds_file" 2>/dev/null || echo 0)" = "1" ]; then
dual_flag="1"
else
dual_flag="0"
fi
python3 - "$dual_flag" "$rat_parked" << 'PY' >/dev/null 2>&1 || true
import os, select, socket, struct, sys, time
dual = (len(sys.argv) > 1 and sys.argv[1] == "1")
rat_parked = (len(sys.argv) > 2 and sys.argv[2] == "1")
mock_sock = os.environ.get("BANANARCHY_QRTR_MOCK_SOCK", "")
AF_QIPCRTR = 42 AF_QIPCRTR = 42
QRTR_PORT_CTRL = 0xfffffffe QRTR_PORT_CTRL = 0xfffffffe
QRTR_TYPE_NEW_SERVER = 4 QRTR_TYPE_NEW_SERVER = 4
QRTR_TYPE_NEW_LOOKUP = 10 QRTR_TYPE_NEW_LOOKUP = 10
QMI_SERVICE_NAS = 3 QMI_SERVICE_NAS = 3
QMI_SERVICE_DSD = 0x2A
ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) MOCK_MAGIC = 0x51525452
node, _ = ls.getsockname() MOCK_MSG_LOOKUP = 1
ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, QMI_SERVICE_NAS, 0, 0, 0), (node, QRTR_PORT_CTRL)) MOCK_MSG_DATA = 3
nas_addr = None MOCK_HDR_FMT = "<9I"
while True: MOCK_HDR_SIZE = struct.calcsize(MOCK_HDR_FMT)
r, _, _ = select.select([ls], [], [], 0.15)
class QrtrTransport:
def __init__(self):
self.is_mock = bool(mock_sock)
self.socks = []
def open_sock(self, svc=QMI_SERVICE_NAS):
if self.is_mock:
s = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
s.connect(mock_sock)
s.send(struct.pack(MOCK_HDR_FMT, MOCK_MAGIC, MOCK_MSG_LOOKUP, 1, 0, 0, 0, svc, 0, 0))
addr = None
r, _, _ = select.select([s], [], [], 0.5)
if r:
d = s.recv(4096)
if len(d) >= MOCK_HDR_SIZE:
magic, _, _, _, _, _, srv, _, plen = struct.unpack_from(MOCK_HDR_FMT, d, 0)
if magic == MOCK_MAGIC and srv == svc and plen >= 8:
dn, dp = struct.unpack_from("<II", d, MOCK_HDR_SIZE)
if dp != 0:
addr = (dn, dp)
self.socks.append(s)
return s, addr
else:
ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
node, _ = ls.getsockname()
ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, svc, 0, 0, 0), (node, QRTR_PORT_CTRL))
addr = None
while True:
r, _, _ = select.select([ls], [], [], 0.2)
if not r: if not r:
break break
data, _ = ls.recvfrom(256) data, _ = ls.recvfrom(256)
if len(data) >= 20: if len(data) >= 20:
cmd, srv, inst, srv_node, srv_port = struct.unpack("<IIIII", data[:20]) cmd, srv, inst, srv_node, srv_port = struct.unpack("<IIIII", data[:20])
if cmd == QRTR_TYPE_NEW_SERVER: if cmd == QRTR_TYPE_NEW_SERVER:
if srv == QMI_SERVICE_NAS and srv_port != 0: if srv == svc and srv_port != 0:
nas_addr = (srv_node, srv_port) addr = (srv_node, srv_port)
if srv == 0 and srv_node == 0 and srv_port == 0: if srv == 0 and srv_node == 0 and srv_port == 0:
break break
ls.close() ls.close()
if not nas_addr: if not addr:
raise SystemExit(0) return None, None
s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
self.socks.append(s)
return s, addr
def qmi_req(s, txn, msg_id, tlvs=b""): def qmi_req(self, s, addr, txn, msg_id, tlvs=b"", svc=QMI_SERVICE_NAS):
s.sendto(struct.pack("<BHHH", 0x00, txn, msg_id, len(tlvs)) + tlvs, nas_addr) if not s or not addr:
r, _, _ = select.select([s], [], [], 0.25) return b""
if r: qmi_pkt = struct.pack("<BHHH", 0x00, txn, msg_id, len(tlvs)) + tlvs
return s.recvfrom(1024)[0] if self.is_mock:
hdr = struct.pack(MOCK_HDR_FMT, MOCK_MAGIC, MOCK_MSG_DATA, 1, 0, addr[0], addr[1], svc, 0, len(qmi_pkt))
s.send(hdr + qmi_pkt)
else:
s.sendto(qmi_pkt, addr)
for _ in range(12):
r, _, _ = select.select([s], [], [], 0.3)
if not r:
return b""
raw = s.recv(4096) if self.is_mock else s.recvfrom(4096)[0]
if self.is_mock:
if len(raw) < MOCK_HDR_SIZE:
continue
magic, _, _, _, _, _, _, _, plen = struct.unpack_from(MOCK_HDR_FMT, raw, 0)
if magic != MOCK_MAGIC:
continue
resp = raw[MOCK_HDR_SIZE:MOCK_HDR_SIZE + plen]
else:
resp = raw
if len(resp) >= 7 and resp[0] == 0x02:
r_txn, r_msg, _ = struct.unpack("<HHH", resp[1:7])
if r_txn == txn and r_msg == msg_id:
return resp
return b"" return b""
def get_reg_state(s, txn): def close(self):
resp = qmi_req(s, txn, 0x0024) for s in self.socks:
try:
s.close()
except OSError:
pass
def parse_tlvs(resp):
res = {}
pos = 7 pos = 7
while pos + 3 <= len(resp): while pos + 3 <= len(resp):
tt, tl = struct.unpack("<BH", resp[pos:pos+3]) tt, tl = struct.unpack("<BH", resp[pos:pos + 3])
pos += 3 pos += 3
if tt == 0x01 and tl >= 1: if pos + tl > len(resp):
return resp[pos] break
res[tt] = resp[pos:pos + tl]
pos += tl pos += tl
return 0 return res
for sub in (0, 1):
s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) def get_serving_info(tr, s, addr, txn):
qmi_req(s, 1, 0x0045, struct.pack("<BHB", 0x01, 1, sub)) tlvs = parse_tlvs(tr.qmi_req(s, addr, txn, 0x0024))
reg_st = get_reg_state(s, 2) v = tlvs.get(0x01, b"")
if reg_st not in (1, 2): if len(v) >= 3:
if sub == 0: return v[0], v[1], v[2]
qmi_req(s, 3, 0x004B, struct.pack("<BHB", 0x10, 1, 2)) if len(v) >= 1:
qmi_req(s, 4, 0x0022, struct.pack("<BHB", 0x01, 1, 1)) return v[0], 0, 0
s.close() return 0, 0, 0
def get_sys_sel_pref(tr, s, addr, txn):
tlvs = parse_tlvs(tr.qmi_req(s, addr, txn, 0x0034))
mode_pref = struct.unpack("<H", tlvs[0x11][:2])[0] if 0x11 in tlvs and len(tlvs[0x11]) >= 2 else -1
srv_dom = struct.unpack("<I", tlvs[0x18][:4])[0] if 0x18 in tlvs and len(tlvs[0x18]) >= 4 else -1
return mode_pref, srv_dom
tr = QrtrTransport()
try:
# Step A: In Dual-SIM, lock Secondary GW (sub=1) to cs-only (0) + GSM (0x0004)
# BEFORE promoting Primary GW (sub=0) to cs-ps (2) because DMS is non-simultaneous-cs-ps.
if dual:
s1, addr1 = tr.open_sock(QMI_SERVICE_NAS)
if s1 and addr1:
tr.qmi_req(s1, addr1, 1, 0x0045, struct.pack("<BHB", 0x01, 1, 1))
mp1, sd1 = get_sys_sel_pref(tr, s1, addr1, 2)
if sd1 != 0 or mp1 != 0x0004:
tlvs1 = (
struct.pack("<BHH", 0x11, 2, 0x0004) +
struct.pack("<BHI", 0x18, 4, 0) +
struct.pack("<BHB", 0x17, 1, 1)
)
tr.qmi_req(s1, addr1, 3, 0x0033, tlvs1)
reg1, _, _ = get_serving_info(tr, s1, addr1, 4)
if reg1 not in (1, 2):
tr.qmi_req(s1, addr1, 5, 0x0022, struct.pack("<BHB", 0x01, 1, 1))
# Step B: Ensure QMI_DSD binds PRIMARY (1) and reports data_enabled=1 without calling 0x004E.
sd, addr_dsd = tr.open_sock(QMI_SERVICE_DSD)
if sd and addr_dsd:
tr.qmi_req(sd, addr_dsd, 1, 0x0027, struct.pack("<BHI", 0x01, 4, 1), svc=QMI_SERVICE_DSD)
tr.qmi_req(sd, addr_dsd, 2, 0x0034, struct.pack("<BHB", 0x10, 1, 1), svc=QMI_SERVICE_DSD)
# Step C: Ensure Primary GW (sub=0) allows cs-ps (2) and triggers PS attach.
s0, addr0 = tr.open_sock(QMI_SERVICE_NAS)
if s0 and addr0:
tr.qmi_req(s0, addr0, 1, 0x0045, struct.pack("<BHB", 0x01, 1, 0))
mp0, sd0 = get_sys_sel_pref(tr, s0, addr0, 2)
need_set0 = (sd0 != 2) or (not rat_parked and mp0 == 0x0004)
if need_set0:
tlvs0 = (
struct.pack("<BHI", 0x18, 4, 2) +
struct.pack("<BHB", 0x17, 1, 1)
)
if not rat_parked and mp0 == 0x0004:
tlvs0 += struct.pack("<BHH", 0x11, 2, 0x001c)
tr.qmi_req(s0, addr0, 3, 0x0033, tlvs0)
reg0, _, ps0 = get_serving_info(tr, s0, addr0, 4)
if reg0 not in (1, 2):
tr.qmi_req(s0, addr0, 5, 0x0022, struct.pack("<BHB", 0x01, 1, 1))
if ps0 != 1:
tr.qmi_req(s0, addr0, 6, 0x0023, struct.pack("<BHB", 0x10, 1, 1))
finally:
tr.close()
PY PY
} }
run_wds_qmicli() {
_wds_preload=""
if [ -n "${BANANARCHY_WDS_BIND_LIB:-}" ]; then
_wds_preload="$BANANARCHY_WDS_BIND_LIB"
elif [ -z "${BANANARCHY_QMICLI_BIN:-}" ] && [ -r /usr/lib/libmm-wds-bind.so ]; then
_wds_preload="/usr/lib/libmm-wds-bind.so"
fi
if [ -n "$_wds_preload" ] && [ -r "$_wds_preload" ]; then
LD_PRELOAD="${_wds_preload}${LD_PRELOAD:+:$LD_PRELOAD}" $QMICLI_MODEM "$@"
else
$QMICLI_MODEM "$@"
fi
}
sync_wds_apn() {
target_apn="${1:-}"
target_user="${2:-}"
target_pass="${3:-}"
nm_dir="${BANANARCHY_NM_CONNECTIONS_DIR:-/etc/NetworkManager/system-connections}"
has_explicit=0
[ -n "$target_apn" ] && has_explicit=1
if [ -z "$target_apn" ] && [ -d "$nm_dir" ]; then
for nmf in "$nm_dir"/*.nmconnection; do
[ -r "$nmf" ] || continue
if grep -q '^type=gsm$' "$nmf" 2>/dev/null; then
nm_apn="$(awk -F= '/^\[/{s=$0} s=="[gsm]" && $1=="apn"{print $2; exit}' "$nmf" 2>/dev/null | tr -d '\r"' || true)"
nm_user="$(awk -F= '/^\[/{s=$0} s=="[gsm]" && $1=="username"{print $2; exit}' "$nmf" 2>/dev/null | tr -d '\r"' || true)"
nm_pass="$(awk -F= '/^\[/{s=$0} s=="[gsm]" && $1=="password"{print $2; exit}' "$nmf" 2>/dev/null | tr -d '\r"' || true)"
if [ -n "$nm_apn" ]; then
target_apn="$nm_apn"
[ -z "$target_user" ] && target_user="$nm_user"
[ -z "$target_pass" ] && target_pass="$nm_pass"
has_explicit=1
break
fi
fi
done
fi
if [ -z "$target_apn" ] && detect_qmicli_modem; then
_nas_out="$($QMICLI_MODEM --nas-get-serving-system 2>/dev/null || true)"
if [ -n "$_nas_out" ]; then
eval "$(parse_nas_serving_system "$_nas_out" 2>/dev/null || true)"
case "${NAS_MCC:-}${NAS_MNC:-}" in
25501|25502|25503|25506|2551|2552|2553|2556) target_apn="internet" ;;
esac
fi
fi
[ -n "$target_apn" ] || return 0
detect_qmicli_modem || return 0
prof_list="$(run_wds_qmicli --wds-get-profile-list=3gpp 2>/dev/null || true)"
[ -n "$prof_list" ] || return 0
attach_pdn="$(run_wds_qmicli --wds-get-lte-attach-pdn-list 2>/dev/null | sed -n "s/.*Current list:[[:space:]]*'\([^']*\)'.*/\1/p" | head -n1 | awk -F',' '{print $1}' | tr -dc '0-9' || true)"
def_prof="$(run_wds_qmicli --wds-get-default-profile-number=3gpp 2>/dev/null | sed -n "s/.*Default profile number:[[:space:]]*'\([^']*\)'.*/\1/p" | head -n1 | tr -dc '0-9' || true)"
target_ids=""
has_prof1=""
printf '%s\n' "$prof_list" | grep -q '^[[:space:]]*\[1\][[:space:]]*3gpp' && has_prof1="1"
for idx in "$attach_pdn" "$def_prof" "$has_prof1"; do
case "$idx" in ''|*[!0-9]*) continue ;; esac
case " $target_ids " in *" $idx "*) ;; *) target_ids="$target_ids $idx" ;; esac
done
[ -n "$target_ids" ] || return 0
auth_opts=""
if [ -n "$target_user" ] && [ -n "$target_pass" ]; then
auth_opts=",auth=PAP,username=$target_user,password=$target_pass"
elif [ -n "$target_user" ]; then
auth_opts=",username=$target_user"
fi
SYNC_WDS_CHANGED=0
for idx in $target_ids; do
cur_apn="$(printf '%s\n' "$prof_list" | awk -v id="$idx" '
$0 ~ "\\[" id "\\]" { in_blk=1; next }
in_blk && /^[[:space:]]*\[[0-9]+\]/ { exit }
in_blk && /APN:/ {
line=$0
sub(/.*APN:[[:space:]]*\x27/, "", line)
sub(/\x27.*/, "", line)
print line
exit
}
' || true)"
case "$(printf '%s' "$cur_apn" | tr 'A-Z' 'a-z')" in
ims|sos) continue ;;
esac
if [ "$has_explicit" -eq 0 ] && [ "$idx" != "1" ] && [ -z "$cur_apn" ]; then
continue
fi
if [ "$cur_apn" != "$target_apn" ] || [ -n "$auth_opts" ]; then
run_wds_qmicli --wds-modify-profile="3gpp,$idx,apn=$target_apn,pdp-type=IPV4V6${auth_opts}" >/dev/null 2>&1 || \
run_wds_qmicli --wds-modify-profile="3gpp,$idx,apn=$target_apn,pdp-type=IP${auth_opts}" >/dev/null 2>&1 || true
SYNC_WDS_CHANGED=1
fi
done
}
mobile_data_prep() {
apn="${1:-}"
user="${2:-}"
pass="${3:-}"
_dpm_sh="${BANANARCHY_DPM_SH:-/usr/bin/bananarchy-dpm.sh}"
_run_dir="${BANANARCHY_RUNDIR:-/run/bananarchy}"
_dsds_file="${BANANARCHY_DSDS_ACTIVE_FILE:-/tmp/sxmo_dsds_active}"
_use_mm=0
if [ "${BANANARCHY_SKIP_MM:-0}" != "1" ] && { [ -z "${BANANARCHY_QMICLI_BIN:-}" ] || [ "${BANANARCHY_USE_MM:-0}" = "1" ]; } && command -v mmcli >/dev/null 2>&1; then
_use_mm=1
fi
if [ "$_use_mm" -eq 1 ] && { [ -z "${BANANARCHY_QMICLI_BIN:-}" ] || [ "${BANANARCHY_USE_MM:-0}" = "1" ]; } && command -v nmcli >/dev/null 2>&1; then
for _guuid in $(timeout 3 nmcli -t -f UUID,TYPE connection show 2>/dev/null | awk -F: '$2=="gsm"{print $1}' || true); do
timeout 3 nmcli connection modify "$_guuid" connection.autoconnect no >/dev/null 2>&1 || true
done
_qst="$(timeout 2 nmcli -t -f TYPE,STATE device status 2>/dev/null | awk -F: '$1=="gsm"{print $2; exit}' || true)"
case "$_qst" in
connecting*) timeout 4 nmcli device disconnect qrtr0 >/dev/null 2>&1 || true ;;
esac
fi
if [ -x "$_dpm_sh" ]; then
"$_dpm_sh" open >/dev/null 2>&1 || true
fi
if [ -f "${BANANARCHY_POWER_RUNDIR:-/run/bananarchy-power-policy}/rat_parked" ] && [ -x /usr/bin/bananarchy-power-policy.sh ]; then
/usr/bin/bananarchy-power-policy.sh unpark-rat >/dev/null 2>&1 || true
fi
if detect_qmicli_modem; then
$QMICLI_MODEM --dms-set-operating-mode=online >/dev/null 2>&1 || true
fi
if [ "$_use_mm" -eq 1 ]; then
_mi=0
_restarted_mm=0
while [ "$_mi" -lt 45 ]; do
if timeout 2 mmcli -L 2>/dev/null | grep -q '/Modem/'; then
_mm_st_pre="$(timeout 3 mmcli -m any -K 2>/dev/null | awk -F':[[:space:]]*' '/^modem\.generic\.state[[:space:]]*:/ {print $2; exit}' | tr -d ' \r' || true)"
if [ "$_mm_st_pre" = "failed" ] && [ "$_restarted_mm" -eq 0 ]; then
_restarted_mm=1
restart_modemmanager_clean
_mi=0
sleep 1
continue
fi
if [ "$_mm_st_pre" = "disabled" ]; then
timeout 5 mmcli -m any -e >/dev/null 2>&1 || true
fi
break
elif [ "$_mi" -eq 24 ] && [ "$_restarted_mm" -eq 0 ]; then
_restarted_mm=1
restart_modemmanager_clean
fi
sleep 0.5
_mi=$((_mi + 1))
done
fi
_did_mode_change=0
ensure_dsds_nas_registration auto
if detect_qmicli_modem; then
_ssp_out="$($QMICLI_MODEM --nas-get-system-selection-preference 2>/dev/null || true)"
if printf '%s\n' "$_ssp_out" | grep -q "Service domain preference: 'cs-only'"; then
QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)"
if [ -n "$QMI_CARDS" ]; then
eval "$(parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT")"
if [ "${SECONDARY_GW_SLOT:-0}" = "1" ] || [ "${SECONDARY_GW_SLOT:-0}" = "2" ]; then
eval "_sec_aid=\${SLOT${SECONDARY_GW_SLOT}_AID:-}"
mkdir -p "$_run_dir" 2>/dev/null || true
printf 'SLOT=%s\nAID=%s\n' "$SECONDARY_GW_SLOT" "$_sec_aid" > "$_run_dir/dsds_paused_for_data" 2>/dev/null || true
$QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=secondary-gw-provisioning' >/dev/null 2>&1 || true
printf '0\n' > "$_dsds_file" 2>/dev/null || true
ensure_dsds_nas_registration 0
_did_mode_change=1
fi
fi
fi
fi
SYNC_WDS_CHANGED=0
sync_wds_apn "$apn" "$user" "$pass"
if [ "${SYNC_WDS_CHANGED:-0}" = "1" ]; then
ensure_dsds_nas_registration auto
_did_mode_change=1
fi
if detect_qmicli_modem; then
_w=0
while [ "$_w" -lt 45 ]; do
_nas_ok=0
_dsd_ok=1
_mm_ok=1
_nm_ok=1
_nas_out="$($QMICLI_MODEM --nas-get-serving-system 2>/dev/null || true)"
eval "$(parse_nas_serving_system "$_nas_out" 2>/dev/null || true)"
[ "${NAS_PS_STATE:-}" = "attached" ] && _nas_ok=1
if [ -z "${BANANARCHY_QMICLI_BIN:-}" ]; then
_dsd_out="$($QMICLI_MODEM --dsd-get-system-status 2>/dev/null || true)"
if printf '%s\n' "$_dsd_out" | grep -q 'Available data systems retrieved:' && \
! printf '%s\n' "$_dsd_out" | grep -Eq "RAT:[[:space:]]*'3gpp-(lte|wcdma|geran|tdscdma|5g)"; then
_dsd_ok=0
fi
fi
if [ "$_use_mm" -eq 1 ]; then
_mm_ok=0
_mm_kv="$(timeout 3 mmcli -m any -K 2>/dev/null || true)"
_mm_st="$(printf '%s\n' "$_mm_kv" | awk -F':[[:space:]]*' '/^modem\.generic\.state[[:space:]]*:/ {print $2; exit}' | tr -d ' \r')"
_mm_ps="$(printf '%s\n' "$_mm_kv" | awk -F':[[:space:]]*' '/^modem\.3gpp\.packet-service-state[[:space:]]*:/ {print $2; exit}' | tr -d ' \r')"
case "$_mm_st" in
disabled)
timeout 5 mmcli -m any -e >/dev/null 2>&1 || true
;;
enabled)
timeout 4 mmcli -m any --3gpp-register-home >/dev/null 2>&1 || true
;;
registered|connected)
if [ "$_mm_ps" = "attached" ]; then
_mm_ok=1
fi
;;
esac
if command -v nmcli >/dev/null 2>&1; then
_nm_line="$(timeout 2 nmcli -t -f TYPE,STATE device status 2>/dev/null | grep '^gsm:' | head -n1 || true)"
case "$_nm_line" in
""|*:unavailable|*:unmanaged) _nm_ok=0 ;;
esac
fi
fi
if [ "$_nas_ok" -eq 1 ] && [ "$_dsd_ok" -eq 1 ] && [ "$_mm_ok" -eq 1 ] && [ "$_nm_ok" -eq 1 ]; then
break
fi
sleep 0.5
_w=$((_w + 1))
done
if [ "$_did_mode_change" = "1" ]; then
sleep 1
fi
fi
}
restore_dsds() {
_run_dir="${BANANARCHY_RUNDIR:-/run/bananarchy}"
_pause_file="$_run_dir/dsds_paused_for_data"
_dsds_file="${BANANARCHY_DSDS_ACTIVE_FILE:-/tmp/sxmo_dsds_active}"
[ -r "$_pause_file" ] || return 0
_slot="$(awk -F= '$1=="SLOT"{print $2; exit}' "$_pause_file" 2>/dev/null | tr -dc '0-9' || true)"
_aid="$(awk -F= '$1=="AID"{print $2; exit}' "$_pause_file" 2>/dev/null | tr -d ' \r\n' || true)"
rm -f "$_pause_file" 2>/dev/null || true
if [ "$_slot" != "1" ] && [ "$_slot" != "2" ]; then
return 0
fi
detect_qmicli_modem || return 0
ensure_dsds_nas_registration 0
if [ -n "$_aid" ]; then
$QMICLI_MODEM --uim-change-provisioning-session="slot=$_slot,activate=yes,session-type=secondary-gw-provisioning,aid=$_aid" >/dev/null 2>&1 || \
$QMICLI_MODEM --uim-change-provisioning-session="slot=$_slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true
else
$QMICLI_MODEM --uim-change-provisioning-session="slot=$_slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true
fi
printf '1\n' > "$_dsds_file" 2>/dev/null || true
ensure_dsds_nas_registration 1
}
provision_slot() { provision_slot() {
req_slot="$1" req_slot="$1"
wait_secs="$2" wait_secs="$2"
@@ -609,6 +1011,9 @@ provision_slot() {
echo "Slot $chosen_slot already bound to primary-gw-provisioning ($chosen_app_state)." echo "Slot $chosen_slot already bound to primary-gw-provisioning ($chosen_app_state)."
fi fi
# Promote Primary GW (sub=0) to cs-ps before activating secondary-gw-provisioning.
ensure_dsds_nas_registration 0
# Dual-SIM Dual Standby (DSDS): provision the second present SIM slot to secondary-gw-provisioning # Dual-SIM Dual Standby (DSDS): provision the second present SIM slot to secondary-gw-provisioning
if [ "$other_state" = "present" ]; then if [ "$other_state" = "present" ]; then
need_sec=1 need_sec=1
@@ -643,11 +1048,13 @@ provision_slot() {
;; ;;
esac esac
if [ "$other_state" = "present" ]; then if [ "$other_state" = "present" ]; then
ensure_dsds_nas_registration
printf '1\n' > /tmp/sxmo_dsds_active 2>/dev/null || true printf '1\n' > /tmp/sxmo_dsds_active 2>/dev/null || true
ensure_dsds_nas_registration 1
else else
printf '0\n' > /tmp/sxmo_dsds_active 2>/dev/null || true printf '0\n' > /tmp/sxmo_dsds_active 2>/dev/null || true
ensure_dsds_nas_registration 0
fi fi
sync_wds_apn "" "" "" || true
return 0 return 0
} }
@@ -717,7 +1124,7 @@ enable_and_register_modem() {
i=0 i=0
mm_state="" mm_state=""
while [ "$i" -lt 8 ]; do while [ "$i" -lt 22 ]; do
mm_state="$(timeout 3 mmcli -m any -K 2>/dev/null | awk -F': ' '/^modem\.generic\.state / {print $2; exit}' || true)" mm_state="$(timeout 3 mmcli -m any -K 2>/dev/null | awk -F': ' '/^modem\.generic\.state / {print $2; exit}' || true)"
if [ -n "$mm_state" ]; then if [ -n "$mm_state" ]; then
break break
@@ -730,7 +1137,7 @@ enable_and_register_modem() {
restart_modemmanager_clean restart_modemmanager_clean
i=0 i=0
mm_state="" mm_state=""
while [ "$i" -lt 10 ]; do while [ "$i" -lt 22 ]; do
mm_state="$(timeout 3 mmcli -m any -K 2>/dev/null | awk -F': ' '/^modem\.generic\.state / {print $2; exit}' || true)" mm_state="$(timeout 3 mmcli -m any -K 2>/dev/null | awk -F': ' '/^modem\.generic\.state / {print $2; exit}' || true)"
if [ -n "$mm_state" ] && [ "$mm_state" != "failed" ]; then if [ -n "$mm_state" ] && [ "$mm_state" != "failed" ]; then
break break
@@ -800,6 +1207,7 @@ case "$cmd" in
;; ;;
esac esac
provision_slot "$PREFERRED_SIM_SLOT" 10 || true provision_slot "$PREFERRED_SIM_SLOT" 10 || true
spawn_enable_and_register "$PREFERRED_SIM_SLOT" 0
exit 0 exit 0
;; ;;
@@ -3024,8 +3432,28 @@ PY
exit 1 exit 1
;; ;;
ensure-ps-domain)
ensure_dsds_nas_registration auto
exit 0
;;
sync-apn)
sync_wds_apn "${2:-}" "${3:-}" "${4:-}"
exit 0
;;
mobile-data-prep)
mobile_data_prep "${2:-}" "${3:-}" "${4:-}"
exit 0
;;
restore-dsds)
restore_dsds
exit 0
;;
*) *)
echo "Usage: $0 [boot|status|switch <1|2>|verify-pin <slot> <pin>|unblock-puk <slot> <puk> <newpin>|set-pin-lock <slot> <enable|disable> <pin>|change-pin <slot> <oldpin> <newpin>|imei|usb-tether <on|off|status>|at <port> <cmd>|sim-contacts-import [1|2|auto]|sim-contacts-export [1|2|auto] [tsv_file]]" >&2 echo "Usage: $0 [boot|status|switch <1|2>|ensure-ps-domain|sync-apn [apn] [user] [pass]|mobile-data-prep [apn] [user] [pass]|restore-dsds|verify-pin <slot> <pin>|unblock-puk <slot> <puk> <newpin>|set-pin-lock <slot> <enable|disable> <pin>|change-pin <slot> <oldpin> <newpin>|imei|usb-tether <on|off|status>|at <port> <cmd>|sim-contacts-import [1|2|auto]|sim-contacts-export [1|2|auto] [tsv_file]]" >&2
exit 1 exit 1
;; ;;
esac esac
@@ -91,6 +91,9 @@ case "$newstate" in
if [ -x /usr/bin/bananarchy-power-policy.sh ]; then if [ -x /usr/bin/bananarchy-power-policy.sh ]; then
/usr/bin/bananarchy-power-policy.sh modem-ready >/dev/null 2>&1 & /usr/bin/bananarchy-power-policy.sh modem-ready >/dev/null 2>&1 &
fi fi
if [ -x /usr/bin/bananarchy-imsctl ]; then
/usr/bin/bananarchy-imsctl notify modem "$newstate" >/dev/null 2>&1 &
fi
sxmo_modem.sh checkforfinishedcalls sxmo_modem.sh checkforfinishedcalls
sxmo_modem.sh checkforincomingcalls sxmo_modem.sh checkforincomingcalls
@@ -202,6 +202,21 @@ set_modem() {
modem-tech 11 "$MODEMTECHCMP" modem-tech 11 "$MODEMTECHCMP"
fi fi
IMS_STATE_FILE="${BANANARCHY_IMS_STATE_PATH:-/run/bananarchy/ims/state.env}"
IMS_BADGE=""
if [ -r "$IMS_STATE_FILE" ]; then
if grep -q '^VOWIFI_REGISTERED=1$' "$IMS_STATE_FILE" 2>/dev/null; then
IMS_BADGE="VoWiFi"
elif grep -q '^VOLTE_REGISTERED=1$' "$IMS_STATE_FILE" 2>/dev/null; then
IMS_BADGE="VoLTE"
fi
fi
if [ -n "$IMS_BADGE" ]; then
sxmobar -a -f "$fgcolor" -b "$bgcolor" -t "$style" ims-status 13 "$IMS_BADGE"
else
sxmobar -d ims-status 2>/dev/null || true
fi
MODEMSIGNALCMP="$icon_modem_signal_0" MODEMSIGNALCMP="$icon_modem_signal_0"
bgcolor=default bgcolor=default
fgcolor=default fgcolor=default
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+4 -2
View File
@@ -104,8 +104,10 @@ ensure_prebuilt_artifacts() {
if [ ! -x "$BANANARCHY_DIR/prebuilt/bananarchy-daemons/usr/bin/bananarchy-lid" ] || \ if [ ! -x "$BANANARCHY_DIR/prebuilt/bananarchy-daemons/usr/bin/bananarchy-lid" ] || \
[ ! -x "$BANANARCHY_DIR/prebuilt/bananarchy-daemons/usr/bin/bananarchy-cover-idle" ] || \ [ ! -x "$BANANARCHY_DIR/prebuilt/bananarchy-daemons/usr/bin/bananarchy-cover-idle" ] || \
[ ! -x "$BANANARCHY_DIR/prebuilt/bananarchy-daemons/usr/bin/bananarchy-volume-keys" ]; then [ ! -x "$BANANARCHY_DIR/prebuilt/bananarchy-daemons/usr/bin/bananarchy-volume-keys" ] || \
echo "[auto-deps] Missing compiled idle daemons; running scripts/build-bananarchy-daemons.sh..." [ ! -x "$BANANARCHY_DIR/prebuilt/bananarchy-daemons/usr/bin/bananarchy-imsctl" ] || \
[ ! -x "$BANANARCHY_DIR/prebuilt/bananarchy-daemons/usr/bin/bananarchy-imsd" ]; then
echo "[auto-deps] Missing compiled idle/IMS daemons; running scripts/build-bananarchy-daemons.sh..."
"$BANANARCHY_DIR/scripts/build-bananarchy-daemons.sh" "$BANANARCHY_DIR/scripts/build-bananarchy-daemons.sh"
fi fi
+37 -5
View File
@@ -105,13 +105,17 @@ if command -v docker >/dev/null 2>&1; then
for _req_daemon in bananarchy-lid bananarchy-cover-idle bananarchy-volume-keys \ for _req_daemon in bananarchy-lid bananarchy-cover-idle bananarchy-volume-keys \
bananarchy-dsds bananarchy-modemmonitor bananarchy-soundmonitor \ bananarchy-dsds bananarchy-modemmonitor bananarchy-soundmonitor \
bananarchy-notifmonitor bananarchy-run-aligned \ bananarchy-notifmonitor bananarchy-run-aligned \
bananarchy-session-loop; do bananarchy-session-loop bananarchy-imsctl bananarchy-imsd; do
if [ ! -x "$BASE_DIR/prebuilt/bananarchy-daemons/usr/bin/$_req_daemon" ]; then if [ ! -x "$BASE_DIR/prebuilt/bananarchy-daemons/usr/bin/$_req_daemon" ]; then
echo " -> Missing compiled daemons; running scripts/build-bananarchy-daemons.sh..." echo " -> Missing compiled daemons; running scripts/build-bananarchy-daemons.sh..."
"$BASE_DIR/scripts/build-bananarchy-daemons.sh" "$BASE_DIR/scripts/build-bananarchy-daemons.sh"
break break
fi fi
done done
if [ ! -f "$BASE_DIR/prebuilt/bananarchy-daemons/usr/lib/libmm-wds-bind.so" ]; then
echo " -> Missing compiled libmm-wds-bind.so; running scripts/build-bananarchy-daemons.sh..."
"$BASE_DIR/scripts/build-bananarchy-daemons.sh"
fi
if [ ! -f "$BASE_DIR/prebuilt/bantam/bantam" ]; then if [ ! -f "$BASE_DIR/prebuilt/bantam/bantam" ]; then
echo " -> Missing prebuilt bantam binary; running scripts/build-bantam.sh..." echo " -> Missing prebuilt bantam binary; running scripts/build-bantam.sh..."
"$BASE_DIR/scripts/build-bantam.sh" "$BASE_DIR/scripts/build-bantam.sh"
@@ -128,7 +132,7 @@ rm -f "$TARGET_ROOTFS/usr/bin/bananarchy-lid.py" \
for daemon in bananarchy-lid bananarchy-cover-idle bananarchy-volume-keys \ for daemon in bananarchy-lid bananarchy-cover-idle bananarchy-volume-keys \
bananarchy-dsds bananarchy-modemmonitor bananarchy-soundmonitor \ bananarchy-dsds bananarchy-modemmonitor bananarchy-soundmonitor \
bananarchy-notifmonitor bananarchy-run-aligned \ bananarchy-notifmonitor bananarchy-run-aligned \
bananarchy-session-loop; do bananarchy-session-loop bananarchy-imsctl bananarchy-imsd; do
cp -af "$BASE_DIR/prebuilt/bananarchy-daemons/usr/bin/$daemon" \ cp -af "$BASE_DIR/prebuilt/bananarchy-daemons/usr/bin/$daemon" \
"$TARGET_ROOTFS/usr/bin/$daemon" "$TARGET_ROOTFS/usr/bin/$daemon"
chmod 0755 "$TARGET_ROOTFS/usr/bin/$daemon" chmod 0755 "$TARGET_ROOTFS/usr/bin/$daemon"
@@ -213,12 +217,22 @@ chown 0:0 "$TARGET_ROOTFS/etc/chrony/chrony.conf" \
"$TARGET_ROOTFS/usr/bin/bananarchy-bt-scan.sh" \ "$TARGET_ROOTFS/usr/bin/bananarchy-bt-scan.sh" \
"$TARGET_ROOTFS/usr/bin/bananarchy-bt-le-enable.sh" \ "$TARGET_ROOTFS/usr/bin/bananarchy-bt-le-enable.sh" \
"$TARGET_ROOTFS/usr/bin/bananarchy-dpm.sh" \ "$TARGET_ROOTFS/usr/bin/bananarchy-dpm.sh" \
"$TARGET_ROOTFS/usr/bin/bananarchy-imsctl" \
"$TARGET_ROOTFS/usr/bin/bananarchy-imsd" \
"$TARGET_ROOTFS/usr/lib/libmm-wds-bind.so" \
"$TARGET_ROOTFS/usr/bin/bananarchy-vowifi" \
"$TARGET_ROOTFS/usr/bin/bananarchy-ims-bearer.sh" \
"$TARGET_ROOTFS/usr/bin/sxmo_run_aligned.sh" \ "$TARGET_ROOTFS/usr/bin/sxmo_run_aligned.sh" \
"$TARGET_ROOTFS/etc/bananarchy/ims.conf" \
"$TARGET_ROOTFS/etc/init.d/bananarchy-imsd" \
"$TARGET_ROOTFS/etc/init.d/modemmanager" \
"$TARGET_ROOTFS/etc/init.d/bananarchy-time-sync" \ "$TARGET_ROOTFS/etc/init.d/bananarchy-time-sync" \
"$TARGET_ROOTFS/etc/boot-deploy/hooks/10-initramfs-depmod.sh" \ "$TARGET_ROOTFS/etc/boot-deploy/hooks/10-initramfs-depmod.sh" \
"$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/pre-up.d/10-bananarchy-dpm.sh" \
"$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/10-bananarchy-dpm.sh" \ "$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/10-bananarchy-dpm.sh" \
"$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/20-bananarchy-time-sync.sh" \ "$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/20-bananarchy-time-sync.sh" \
"$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/30-bananarchy-network-status.sh" \ "$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/30-bananarchy-network-status.sh" \
"$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/40-bananarchy-ims.sh" \
"$TARGET_ROOTFS/usr/lib/NetworkManager/dispatcher.d/50-dns-filter.sh" \ "$TARGET_ROOTFS/usr/lib/NetworkManager/dispatcher.d/50-dns-filter.sh" \
"$TARGET_ROOTFS/usr/lib/NetworkManager/dispatcher.d/pre-up.d/90-nm-cloud-setup.sh" \ "$TARGET_ROOTFS/usr/lib/NetworkManager/dispatcher.d/pre-up.d/90-nm-cloud-setup.sh" \
"$TARGET_ROOTFS/usr/lib/NetworkManager/system-connections/USB_Networking.nmconnection" \ "$TARGET_ROOTFS/usr/lib/NetworkManager/system-connections/USB_Networking.nmconnection" \
@@ -227,6 +241,7 @@ chown 0:0 "$TARGET_ROOTFS/etc/chrony/chrony.conf" \
"$TARGET_ROOTFS/usr/bin/zramstart" \ "$TARGET_ROOTFS/usr/bin/zramstart" \
2>/dev/null || true 2>/dev/null || true
chmod 0644 "$TARGET_ROOTFS/etc/chrony/chrony.conf" \ chmod 0644 "$TARGET_ROOTFS/etc/chrony/chrony.conf" \
"$TARGET_ROOTFS/etc/bananarchy/ims.conf" \
"$TARGET_ROOTFS/etc/NetworkManager/conf.d/20-bananarchy-dns.conf" \ "$TARGET_ROOTFS/etc/NetworkManager/conf.d/20-bananarchy-dns.conf" \
"$TARGET_ROOTFS/etc/resolv.conf" \ "$TARGET_ROOTFS/etc/resolv.conf" \
2>/dev/null || true 2>/dev/null || true
@@ -252,12 +267,21 @@ chmod 0755 "$TARGET_ROOTFS/usr/bin/bananarchy-idle-blank.sh" \
"$TARGET_ROOTFS/usr/bin/bananarchy-bt-scan.sh" \ "$TARGET_ROOTFS/usr/bin/bananarchy-bt-scan.sh" \
"$TARGET_ROOTFS/usr/bin/bananarchy-bt-le-enable.sh" \ "$TARGET_ROOTFS/usr/bin/bananarchy-bt-le-enable.sh" \
"$TARGET_ROOTFS/usr/bin/bananarchy-dpm.sh" \ "$TARGET_ROOTFS/usr/bin/bananarchy-dpm.sh" \
"$TARGET_ROOTFS/usr/bin/bananarchy-imsctl" \
"$TARGET_ROOTFS/usr/bin/bananarchy-imsd" \
"$TARGET_ROOTFS/usr/lib/libmm-wds-bind.so" \
"$TARGET_ROOTFS/usr/bin/bananarchy-vowifi" \
"$TARGET_ROOTFS/usr/bin/bananarchy-ims-bearer.sh" \
"$TARGET_ROOTFS/usr/bin/sxmo_run_aligned.sh" \ "$TARGET_ROOTFS/usr/bin/sxmo_run_aligned.sh" \
"$TARGET_ROOTFS/etc/init.d/bananarchy-imsd" \
"$TARGET_ROOTFS/etc/init.d/modemmanager" \
"$TARGET_ROOTFS/etc/init.d/bananarchy-time-sync" \ "$TARGET_ROOTFS/etc/init.d/bananarchy-time-sync" \
"$TARGET_ROOTFS/etc/boot-deploy/hooks/10-initramfs-depmod.sh" \ "$TARGET_ROOTFS/etc/boot-deploy/hooks/10-initramfs-depmod.sh" \
"$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/pre-up.d/10-bananarchy-dpm.sh" \
"$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/10-bananarchy-dpm.sh" \ "$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/10-bananarchy-dpm.sh" \
"$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/20-bananarchy-time-sync.sh" \ "$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/20-bananarchy-time-sync.sh" \
"$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/30-bananarchy-network-status.sh" \ "$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/30-bananarchy-network-status.sh" \
"$TARGET_ROOTFS/etc/NetworkManager/dispatcher.d/40-bananarchy-ims.sh" \
"$TARGET_ROOTFS/usr/lib/NetworkManager/dispatcher.d/50-dns-filter.sh" \ "$TARGET_ROOTFS/usr/lib/NetworkManager/dispatcher.d/50-dns-filter.sh" \
"$TARGET_ROOTFS/usr/lib/NetworkManager/dispatcher.d/pre-up.d/90-nm-cloud-setup.sh" \ "$TARGET_ROOTFS/usr/lib/NetworkManager/dispatcher.d/pre-up.d/90-nm-cloud-setup.sh" \
"$TARGET_ROOTFS/usr/bin/zramstart" \ "$TARGET_ROOTFS/usr/bin/zramstart" \
@@ -267,9 +291,16 @@ CHRONY_GID="$(awk -F: '/^chrony:/ {print $4}' "$TARGET_ROOTFS/etc/passwd" 2>/dev
mkdir -p "$TARGET_ROOTFS/var/lib/chrony" mkdir -p "$TARGET_ROOTFS/var/lib/chrony"
chown -R "${CHRONY_UID:-101}:${CHRONY_GID:-102}" "$TARGET_ROOTFS/var/lib/chrony" 2>/dev/null || true chown -R "${CHRONY_UID:-101}:${CHRONY_GID:-102}" "$TARGET_ROOTFS/var/lib/chrony" 2>/dev/null || true
chmod 0750 "$TARGET_ROOTFS/var/lib/chrony" 2>/dev/null || true chmod 0750 "$TARGET_ROOTFS/var/lib/chrony" 2>/dev/null || true
mkdir -p "$TARGET_ROOTFS/etc/bananarchy" mkdir -p "$TARGET_ROOTFS/etc/bananarchy" \
chown 0:0 "$TARGET_ROOTFS/etc/bananarchy" 2>/dev/null || true "$TARGET_ROOTFS/var/lib/bananarchy/ims/profiles"
chmod 0700 "$TARGET_ROOTFS/etc/bananarchy" 2>/dev/null || true chown 0:0 "$TARGET_ROOTFS/etc/bananarchy" \
"$TARGET_ROOTFS/var/lib/bananarchy" \
"$TARGET_ROOTFS/var/lib/bananarchy/ims" \
"$TARGET_ROOTFS/var/lib/bananarchy/ims/profiles" 2>/dev/null || true
chmod 0755 "$TARGET_ROOTFS/etc/bananarchy" \
"$TARGET_ROOTFS/var/lib/bananarchy" \
"$TARGET_ROOTFS/var/lib/bananarchy/ims" \
"$TARGET_ROOTFS/var/lib/bananarchy/ims/profiles" 2>/dev/null || true
if [ -f "$TARGET_ROOTFS/etc/group" ]; then if [ -f "$TARGET_ROOTFS/etc/group" ]; then
grep -q '^openvpn:' "$TARGET_ROOTFS/etc/group" || echo 'openvpn:x:113:openvpn' >> "$TARGET_ROOTFS/etc/group" grep -q '^openvpn:' "$TARGET_ROOTFS/etc/group" || echo 'openvpn:x:113:openvpn' >> "$TARGET_ROOTFS/etc/group"
grep -q '^tor:' "$TARGET_ROOTFS/etc/group" || echo 'tor:x:114:tor' >> "$TARGET_ROOTFS/etc/group" grep -q '^tor:' "$TARGET_ROOTFS/etc/group" || echo 'tor:x:114:tor' >> "$TARGET_ROOTFS/etc/group"
@@ -498,6 +529,7 @@ ln -sf /etc/init.d/kill-plymouth "$TARGET_ROOTFS/etc/runlevels/default/kill-plym
ln -sf /etc/init.d/bananarchy-power-policy "$TARGET_ROOTFS/etc/runlevels/default/bananarchy-power-policy" ln -sf /etc/init.d/bananarchy-power-policy "$TARGET_ROOTFS/etc/runlevels/default/bananarchy-power-policy"
ln -sf /etc/init.d/bananarchy-time-sync "$TARGET_ROOTFS/etc/runlevels/default/bananarchy-time-sync" ln -sf /etc/init.d/bananarchy-time-sync "$TARGET_ROOTFS/etc/runlevels/default/bananarchy-time-sync"
ln -sf /etc/init.d/bananarchy-sshd-debug "$TARGET_ROOTFS/etc/runlevels/default/bananarchy-sshd-debug" ln -sf /etc/init.d/bananarchy-sshd-debug "$TARGET_ROOTFS/etc/runlevels/default/bananarchy-sshd-debug"
ln -sf /etc/init.d/bananarchy-imsd "$TARGET_ROOTFS/etc/runlevels/default/bananarchy-imsd"
if [ -e "$TARGET_ROOTFS/etc/init.d/loopback" ]; then if [ -e "$TARGET_ROOTFS/etc/init.d/loopback" ]; then
mkdir -p "$TARGET_ROOTFS/etc/runlevels/boot" mkdir -p "$TARGET_ROOTFS/etc/runlevels/boot"
ln -sf /etc/init.d/loopback "$TARGET_ROOTFS/etc/runlevels/boot/loopback" ln -sf /etc/init.d/loopback "$TARGET_ROOTFS/etc/runlevels/boot/loopback"
+1 -1
View File
@@ -214,7 +214,7 @@ for svc in bootmisc hostname loopback modules msm-firmware-loader-unpack osclock
swclock-offset-boot sysctl tmpfs; do swclock-offset-boot sysctl tmpfs; do
enable_service boot "$svc" enable_service boot "$svc"
done done
for svc in bluetooth cgroups chronyd dbus elogind kill-plymouth local \ for svc in bananarchy-imsd bluetooth cgroups chronyd dbus elogind kill-plymouth local \
modemmanager msm8909-modem-wwan-port msm-modem-uim-selection networkmanager \ modemmanager msm8909-modem-wwan-port msm-modem-uim-selection networkmanager \
postmarketos-zram-swap q6voiced rfkill rmtfs sshd tinydm udev-postmount \ postmarketos-zram-swap q6voiced rfkill rmtfs sshd tinydm udev-postmount \
wpa_supplicant; do wpa_supplicant; do
+34 -3
View File
@@ -6,7 +6,7 @@ BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
SRC_DIR="$BASE_DIR/src/bananarchy-daemons" SRC_DIR="$BASE_DIR/src/bananarchy-daemons"
PREBUILT="$BASE_DIR/prebuilt/bananarchy-daemons/usr/bin" PREBUILT="$BASE_DIR/prebuilt/bananarchy-daemons/usr/bin"
OVERLAY="$BASE_DIR/overlay/rootfs/usr/bin" OVERLAY="$BASE_DIR/overlay/rootfs/usr/bin"
NAMES="bananarchy-lid bananarchy-cover-idle bananarchy-volume-keys bananarchy-dsds bananarchy-modemmonitor bananarchy-soundmonitor bananarchy-notifmonitor bananarchy-run-aligned bananarchy-session-loop" NAMES="bananarchy-lid bananarchy-cover-idle bananarchy-volume-keys bananarchy-dsds bananarchy-modemmonitor bananarchy-soundmonitor bananarchy-notifmonitor bananarchy-run-aligned bananarchy-session-loop bananarchy-imsctl bananarchy-imsd"
check_artifacts() { check_artifacts() {
for name in $NAMES; do for name in $NAMES; do
@@ -33,6 +33,28 @@ check_artifacts() {
return 1 return 1
fi fi
done done
PREBUILT_LIB="$BASE_DIR/prebuilt/bananarchy-daemons/usr/lib/libmm-wds-bind.so"
OVERLAY_LIB="$BASE_DIR/overlay/rootfs/usr/lib/libmm-wds-bind.so"
[ -f "$PREBUILT_LIB" ] || {
echo "[!] missing compiled library: $PREBUILT_LIB" >&2
return 1
}
[ -f "$OVERLAY_LIB" ] || {
echo "[!] missing overlay library: $OVERLAY_LIB" >&2
return 1
}
cmp -s "$PREBUILT_LIB" "$OVERLAY_LIB" || {
echo "[!] compiled library drift: libmm-wds-bind.so" >&2
return 1
}
if [ "$(head -c 4 "$PREBUILT_LIB" | od -An -tx1 | tr -d ' \n')" != "7f454c46" ]; then
echo "[!] libmm-wds-bind.so is not an ELF binary" >&2
return 1
fi
if ! readelf -h "$PREBUILT_LIB" 2>/dev/null | grep -q 'Machine:.*ARM'; then
echo "[!] libmm-wds-bind.so is not an ARM binary" >&2
return 1
fi
echo "[ok] compiled idle daemons are ARM ELF binaries and overlay is in sync" echo "[ok] compiled idle daemons are ARM ELF binaries and overlay is in sync"
} }
@@ -57,11 +79,13 @@ EOF
apk add --no-cache build-base gcc-armv7 binutils-armv7 \ apk add --no-cache build-base gcc-armv7 binutils-armv7 \
musl-dev-armv7 linux-headers >/dev/null musl-dev-armv7 linux-headers >/dev/null
mkdir -p /bananarchy/prebuilt/bananarchy-daemons/usr/bin \ mkdir -p /bananarchy/prebuilt/bananarchy-daemons/usr/bin \
/bananarchy/overlay/rootfs/usr/bin /bananarchy/prebuilt/bananarchy-daemons/usr/lib \
/bananarchy/overlay/rootfs/usr/bin \
/bananarchy/overlay/rootfs/usr/lib
for name in bananarchy-lid bananarchy-cover-idle bananarchy-volume-keys \ for name in bananarchy-lid bananarchy-cover-idle bananarchy-volume-keys \
bananarchy-dsds bananarchy-modemmonitor bananarchy-soundmonitor \ bananarchy-dsds bananarchy-modemmonitor bananarchy-soundmonitor \
bananarchy-notifmonitor bananarchy-run-aligned \ bananarchy-notifmonitor bananarchy-run-aligned \
bananarchy-session-loop; do bananarchy-session-loop bananarchy-imsctl bananarchy-imsd; do
armv7-alpine-linux-musleabihf-gcc -std=c11 -O2 -Wall -Wextra -Werror -s \ armv7-alpine-linux-musleabihf-gcc -std=c11 -O2 -Wall -Wextra -Werror -s \
-I/bananarchy/src/bananarchy-daemons \ -I/bananarchy/src/bananarchy-daemons \
-o "/bananarchy/prebuilt/bananarchy-daemons/usr/bin/$name" \ -o "/bananarchy/prebuilt/bananarchy-daemons/usr/bin/$name" \
@@ -72,6 +96,13 @@ EOF
"/bananarchy/overlay/rootfs/usr/bin/$name" "/bananarchy/overlay/rootfs/usr/bin/$name"
echo "[+] built $name" echo "[+] built $name"
done done
armv7-alpine-linux-musleabihf-gcc -std=c11 -O2 -Wall -Wextra -Werror -shared -fPIC -s \
-o /bananarchy/prebuilt/bananarchy-daemons/usr/lib/libmm-wds-bind.so \
/bananarchy/src/bananarchy-daemons/mm-wds-bind.c
cp -a /bananarchy/prebuilt/bananarchy-daemons/usr/lib/libmm-wds-bind.so \
/bananarchy/overlay/rootfs/usr/lib/libmm-wds-bind.so
chown "$HOST_UID:$HOST_GID" /bananarchy/overlay/rootfs/usr/lib/libmm-wds-bind.so
echo "[+] built libmm-wds-bind.so"
chown -R "$HOST_UID:$HOST_GID" /bananarchy/prebuilt/bananarchy-daemons chown -R "$HOST_UID:$HOST_GID" /bananarchy/prebuilt/bananarchy-daemons
' '
check_artifacts check_artifacts
+8 -1
View File
@@ -128,7 +128,7 @@ EOF
pids="$pids $!" pids="$pids $!"
$CXX $CXX_PLUG_FLAGS $PLUG_INCS \ $CXX $CXX_PLUG_FLAGS $PLUG_INCS \
/bananarchy/src/dwm-plugins/sip_plugin.cpp $NEOUI_LIBS $PLUG_LIBS -lssl -lcrypto -lopus -lgsm -lpthread \ /bananarchy/src/dwm-plugins/sip_plugin.cpp $NEOUI_LIBS $PLUG_LIBS -lssl -lcrypto -lopus -lgsm -ldl -lpthread \
-o /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sip.so & -o /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sip.so &
pids="$pids $!" pids="$pids $!"
@@ -217,6 +217,13 @@ EOF
-o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody -o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody
$STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody $STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody
$CXX $OPT_CFLAGS -std=c++20 -Wall -Wextra -Wno-psabi \
$(pkgconf --cflags openssl) -I/bananarchy/src/dwm-plugins \
/bananarchy/src/dwm-plugins/bananarchy_vowifi.cpp \
$(pkgconf --libs openssl) -ldl -lpthread \
-o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-vowifi
$STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-vowifi
ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xquagr ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xquagr
ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/quagr ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/quagr
mkdir -p /bananarchy/overlay/rootfs/usr/bin /bananarchy/overlay/rootfs/usr/lib/dwm/plugins mkdir -p /bananarchy/overlay/rootfs/usr/bin /bananarchy/overlay/rootfs/usr/lib/dwm/plugins
+8 -1
View File
@@ -205,7 +205,7 @@ EOF
pids="$pids $!" pids="$pids $!"
$CXX $CXX_PLUG_FLAGS $PLUG_INCS \ $CXX $CXX_PLUG_FLAGS $PLUG_INCS \
/bananarchy/src/dwm-plugins/sip_plugin.cpp $NEOUI_LIBS $PLUG_LIBS -lssl -lcrypto -lopus -lgsm -lpthread \ /bananarchy/src/dwm-plugins/sip_plugin.cpp $NEOUI_LIBS $PLUG_LIBS -lssl -lcrypto -lopus -lgsm -ldl -lpthread \
-o /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sip.so & -o /bananarchy/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sip.so &
pids="$pids $!" pids="$pids $!"
@@ -325,6 +325,13 @@ EOF
-o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody -o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody
$STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody $STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody
$CXX $OPT_CFLAGS -std=c++20 -Wall -Wextra -Wno-psabi \
$(pkgconf --cflags openssl) -I/bananarchy/src/dwm-plugins \
/bananarchy/src/dwm-plugins/bananarchy_vowifi.cpp \
$(pkgconf --libs openssl) -ldl -lpthread \
-o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-vowifi
$STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-vowifi
ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/dmenu ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/dmenu
ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xdmenu ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xdmenu
ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xlocker ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xlocker
+126 -9
View File
@@ -564,15 +564,15 @@ fi
echo "[check] Known-good flashable image set..." echo "[check] Known-good flashable image set..."
for pair in \ for pair in \
"dfd5361d4c38f2a88d45693f7456f7464a89f121ad05e7f8ac0497b498788d20 images/bananarchy-nokia-argon.img" \ "22014270bb62ebc825afe5ef60fe8aefa65776eb9efc511b92e834a61b59fb0e images/bananarchy-nokia-argon.img" \
"83d7369e114b4db90ae3dfeefc88f3aa864bf3283469fe00965addd86fa8751f images/bananarchy-nokia-beatles.img" \ "dce127a00efcf1e19aeaa8b21e4f28b33cdd5dd0044dcea0051a2e880c021ef7 images/bananarchy-nokia-beatles.img" \
"7f21313963f2868349924da0eb8e6a54131de76bd03bdd3a900f6eb68250b3e2 images/boot-bananarchy-nokia-beatles.img" \ "480d6988f57028006ce0227092de077dffe5d6a51dadeedb0ef1f16a9a35a3e0 images/boot-bananarchy-nokia-beatles.img" \
"f13db705a714aaebd2d8fcc2e0f7266d0e40268c0a276208117dfdf9d8f45351 images/boot-lk2nd-nokia-beatles-display.img" \ "f13db705a714aaebd2d8fcc2e0f7266d0e40268c0a276208117dfdf9d8f45351 images/boot-lk2nd-nokia-beatles-display.img" \
"cf0826eaf298b9161012cad38d66f979af004aeb71f29fa1818f4f7fe222db86 images/bananarchy-nokia-coconut.img" \ "1d5f20a0f6677748c25eedd044b23bb168ddaee0e4ae71c47ceefc0b0878c86f images/bananarchy-nokia-coconut.img" \
"310169cfb5d434c10a0af56e4185aeea8d74013c0b548ea27ec581236d9ac131 images/boot-bananarchy-nokia-coconut.img" \ "7f56459f258857ed0252d0cd81e8fe496e55af2cff48e3cf6defe39a341dfc4a images/boot-bananarchy-nokia-coconut.img" \
"9a5bd2da6cfd95c745d9c1acb2e3bc61afa339824810e3d160bf079e17b23192 images/boot-lk2nd-nokia-coconut-display.img" \ "9a5bd2da6cfd95c745d9c1acb2e3bc61afa339824810e3d160bf079e17b23192 images/boot-lk2nd-nokia-coconut-display.img" \
"01860ac705afe193cd5252f0d42907ba35fe98be1a0509097d4994d824d0cb4d images/bananarchy-nokia-sparkler.img" \ "99d54d6bc001e97f41dc314bbf012ef266251a70b6663a82260f32b1ffeff9e5 images/bananarchy-nokia-sparkler.img" \
"7f95573f8caa6b07387836feb52bac9167ad0dede9922fb3b0cbf1eb32ad9119 images/boot-bananarchy-nokia-sparkler.img" \ "a57973505f56754be74fdea9536e656af82a93d3d3722dcb61b3c6b6e9f6782b images/boot-bananarchy-nokia-sparkler.img" \
"120ade81bc5416263a1afd95a29981675358b98516e105e5ed611edf258a29f7 images/boot-lk2nd-nokia-sparkler-display.img"; do "120ade81bc5416263a1afd95a29981675358b98516e105e5ed611edf258a29f7 images/boot-lk2nd-nokia-sparkler-display.img"; do
set -- $pair set -- $pair
want=$1 want=$1
@@ -592,7 +592,7 @@ for pair in \
done done
echo "[check] Compiled idle daemons..." echo "[check] Compiled idle daemons..."
DAEMONS="bananarchy-lid bananarchy-cover-idle bananarchy-volume-keys bananarchy-dsds bananarchy-modemmonitor bananarchy-soundmonitor bananarchy-notifmonitor bananarchy-run-aligned bananarchy-session-loop" DAEMONS="bananarchy-lid bananarchy-cover-idle bananarchy-volume-keys bananarchy-dsds bananarchy-modemmonitor bananarchy-soundmonitor bananarchy-notifmonitor bananarchy-run-aligned bananarchy-session-loop bananarchy-imsctl bananarchy-imsd"
for daemon in $DAEMONS; do for daemon in $DAEMONS; do
for artifact in "prebuilt/bananarchy-daemons/usr/bin/$daemon" \ for artifact in "prebuilt/bananarchy-daemons/usr/bin/$daemon" \
"overlay/rootfs/usr/bin/$daemon"; do "overlay/rootfs/usr/bin/$daemon"; do
@@ -615,6 +615,8 @@ if ! "$BASE_DIR/scripts/build-bananarchy-daemons.sh" --check >/dev/null 2>&1; th
fail "compiled idle daemon build check failed" fail "compiled idle daemon build check failed"
fi fi
for src in src/bananarchy-daemons/common.h \ for src in src/bananarchy-daemons/common.h \
src/bananarchy-daemons/ims_mbn.h \
src/bananarchy-daemons/ims_qrtr.h \
src/bananarchy-daemons/bananarchy-lid.c \ src/bananarchy-daemons/bananarchy-lid.c \
src/bananarchy-daemons/bananarchy-cover-idle.c \ src/bananarchy-daemons/bananarchy-cover-idle.c \
src/bananarchy-daemons/bananarchy-volume-keys.c \ src/bananarchy-daemons/bananarchy-volume-keys.c \
@@ -623,11 +625,28 @@ for src in src/bananarchy-daemons/common.h \
src/bananarchy-daemons/bananarchy-soundmonitor.c \ src/bananarchy-daemons/bananarchy-soundmonitor.c \
src/bananarchy-daemons/bananarchy-notifmonitor.c \ src/bananarchy-daemons/bananarchy-notifmonitor.c \
src/bananarchy-daemons/bananarchy-run-aligned.c \ src/bananarchy-daemons/bananarchy-run-aligned.c \
src/bananarchy-daemons/bananarchy-session-loop.c; do src/bananarchy-daemons/bananarchy-session-loop.c \
src/bananarchy-daemons/bananarchy-imsctl.c \
src/bananarchy-daemons/bananarchy-imsd.c \
src/bananarchy-daemons/mm-wds-bind.c; do
if [ ! -f "$BASE_DIR/$src" ]; then if [ ! -f "$BASE_DIR/$src" ]; then
fail "missing C daemon source: $src" fail "missing C daemon source: $src"
fi fi
done done
for wds_lib in prebuilt/bananarchy-daemons/usr/lib/libmm-wds-bind.so \
overlay/rootfs/usr/lib/libmm-wds-bind.so; do
path="$BASE_DIR/$wds_lib"
if [ ! -x "$path" ] || \
[ "$(head -c 4 "$path" | od -An -tx1 | tr -d ' \n')" != "7f454c46" ] || \
! readelf -h "$path" 2>/dev/null | grep -q 'Type:.*DYN' || \
! readelf -h "$path" 2>/dev/null | grep -q 'Machine:.*ARM'; then
fail "$wds_lib is missing, not executable, or not an ARM ELF DYN library"
fi
done
if ! cmp -s "$BASE_DIR/prebuilt/bananarchy-daemons/usr/lib/libmm-wds-bind.so" \
"$BASE_DIR/overlay/rootfs/usr/lib/libmm-wds-bind.so"; then
fail "compiled library drift: libmm-wds-bind.so"
fi
if ! grep -q 'CLOSED_MASK' "$BASE_DIR/src/bananarchy-daemons/bananarchy-lid.c" || \ if ! grep -q 'CLOSED_MASK' "$BASE_DIR/src/bananarchy-daemons/bananarchy-lid.c" || \
! grep -q 'bananarchy-lid-state.sh' "$BASE_DIR/src/bananarchy-daemons/bananarchy-lid.c" || \ ! grep -q 'bananarchy-lid-state.sh' "$BASE_DIR/src/bananarchy-daemons/bananarchy-lid.c" || \
! grep -q 'sxmo_state.sh' \ ! grep -q 'sxmo_state.sh' \
@@ -2643,6 +2662,104 @@ if [ -x "$BASE_DIR/scripts/test-quagr.py" ] && \
fail "scripts/test-quagr.py failed" fail "scripts/test-quagr.py failed"
fi fi
echo "[check] IMS MBN profile manager, VoLTE, and VoWiFi stack..."
for artifact in \
src/bananarchy-daemons/ims_mbn.h \
src/bananarchy-daemons/ims_qrtr.h \
src/bananarchy-daemons/bananarchy-imsctl.c \
src/bananarchy-daemons/bananarchy-imsd.c \
src/dwm-plugins/amr_rtp.h \
src/dwm-plugins/vowifi_aka.h \
src/dwm-plugins/vowifi_ikev2.h \
src/dwm-plugins/bananarchy_vowifi.cpp \
prebuilt/bananarchy-daemons/usr/bin/bananarchy-imsctl \
overlay/rootfs/usr/bin/bananarchy-imsctl \
prebuilt/bananarchy-daemons/usr/bin/bananarchy-imsd \
overlay/rootfs/usr/bin/bananarchy-imsd \
prebuilt/sxmo-x11/usr/bin/bananarchy-vowifi \
overlay/rootfs/usr/bin/bananarchy-vowifi \
overlay/rootfs/etc/bananarchy/ims.conf \
overlay/rootfs/etc/init.d/bananarchy-imsd \
overlay/rootfs/usr/bin/bananarchy-ims-bearer.sh \
overlay/rootfs/etc/NetworkManager/dispatcher.d/40-bananarchy-ims.sh \
scripts/test-ims-mbn.py \
scripts/test-imsd-volte.py \
scripts/test-vowifi-swu-ims.py; do
if [ ! -f "$BASE_DIR/$artifact" ]; then
fail "missing IMS/VoLTE/VoWiFi artifact: $artifact"
fi
done
for bin in \
prebuilt/sxmo-x11/usr/bin/bananarchy-vowifi \
overlay/rootfs/usr/bin/bananarchy-vowifi; do
path="$BASE_DIR/$bin"
if [ ! -x "$path" ] || \
[ "$(head -c 4 "$path" | od -An -tx1 | tr -d ' \n')" != "7f454c46" ] || \
! readelf -h "$path" 2>/dev/null | grep -q 'Machine:.*ARM'; then
fail "$bin is missing, not executable, or not an ARM ELF binary"
fi
done
if ! cmp -s "$BASE_DIR/prebuilt/sxmo-x11/usr/bin/bananarchy-vowifi" \
"$BASE_DIR/overlay/rootfs/usr/bin/bananarchy-vowifi"; then
fail "compiled bananarchy-vowifi drift between prebuilt and overlay"
fi
if [ ! -L "$BASE_DIR/overlay/rootfs/etc/runlevels/default/bananarchy-imsd" ]; then
fail "missing OpenRC default runlevel link for bananarchy-imsd"
fi
if [ ! -d "$BASE_DIR/overlay/rootfs/var/lib/bananarchy/ims/profiles" ]; then
fail "missing IMS profile repository directory in overlay"
fi
if ! grep -q '^volte_mode=auto$' "$BASE_DIR/overlay/rootfs/etc/bananarchy/ims.conf" || \
! grep -q '^vowifi_mode=auto$' "$BASE_DIR/overlay/rootfs/etc/bananarchy/ims.conf"; then
fail "ims.conf must ship volte_mode=auto and vowifi_mode=auto by default"
fi
for shf in \
overlay/rootfs/usr/bin/bananarchy-ims-bearer.sh \
overlay/rootfs/etc/NetworkManager/dispatcher.d/40-bananarchy-ims.sh \
overlay/rootfs/etc/NetworkManager/dispatcher.d/10-bananarchy-dpm.sh \
overlay/rootfs/etc/NetworkManager/dispatcher.d/pre-up.d/10-bananarchy-dpm.sh \
overlay/rootfs/etc/init.d/modemmanager \
overlay/rootfs/usr/libexec/msm-modem-uim-selection \
overlay/rootfs/usr/bin/bananarchy-power-policy.sh \
overlay/rootfs/usr/bin/bananarchy-cover-status.sh \
overlay/rootfs/usr/bin/sxmo_modemdial.sh \
overlay/rootfs/usr/bin/sxmo_modemcall.sh \
overlay/rootfs/usr/bin/sxmo_modemsendsms.sh \
overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_modem.sh \
overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_statusbar.sh; do
if [ ! -x "$BASE_DIR/$shf" ] || ! sh -n "$BASE_DIR/$shf" 2>/dev/null; then
fail "IMS/call script invalid or not executable: $shf"
fi
done
if [ ! -x "$BASE_DIR/scripts/test-lte-mobile-data.py" ]; then
fail "scripts/test-lte-mobile-data.py missing or not executable"
fi
if ! grep -qF 'libmm-wds-bind.so' "$BASE_DIR/overlay/rootfs/etc/init.d/modemmanager" || \
! grep -qF 'restore-dsds' "$BASE_DIR/overlay/rootfs/etc/NetworkManager/dispatcher.d/10-bananarchy-dpm.sh" || \
! grep -qF 'mobile-data-prep' "$BASE_DIR/overlay/rootfs/usr/libexec/msm-modem-uim-selection" || \
! grep -qF 'close_imsdcm' "$BASE_DIR/src/bananarchy-daemons/bananarchy-imsd.c"; then
fail "LTE mobile data WDS bind, restore-dsds, mobile-data-prep, or close_imsdcm guard missing"
fi
if ! grep -qF 'bananarchy-imsctl' "$BASE_DIR/overlay/rootfs/etc/doas.d/50-sxmo.conf" || \
! grep -qF 'bananarchy-ims-bearer.sh' "$BASE_DIR/overlay/rootfs/etc/doas.d/50-sxmo.conf" || \
! grep -qF 'isMbnExt' "$BASE_DIR/src/dwm-plugins/files_plugin.cpp" || \
! grep -qF 'ImsProfiles' "$BASE_DIR/src/dwm-plugins/modem_plugin.cpp" || \
! grep -qF 'isImsUserspaceCall' "$BASE_DIR/src/dwm-plugins/callscreen_plugin.cpp" || \
! grep -qF 'AmrWb' "$BASE_DIR/src/dwm-plugins/sip_plugin.cpp"; then
fail "IMS/VoLTE/VoWiFi wiring in doas, files, modem, callscreen, or sip is incomplete"
fi
if command -v python3 >/dev/null 2>&1; then
for tst in \
scripts/test-lte-mobile-data.py \
scripts/test-ims-mbn.py \
scripts/test-imsd-volte.py \
scripts/test-vowifi-swu-ims.py; do
if ! python3 "$BASE_DIR/$tst" >/dev/null 2>&1; then
fail "$tst failed"
fi
done
fi
if [ "$FAILURES" -ne 0 ]; then if [ "$FAILURES" -ne 0 ]; then
echo "[check] $FAILURES check(s) failed." echo "[check] $FAILURES check(s) failed."
exit 1 exit 1
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
# Offline host verification for Qualcomm ELF32 MCFG (.mbn) parser,
# profile store, PLMN auto-matching, and duress blocking in bananarchy-imsctl.
import hashlib
import os
import struct
import subprocess
import sys
import tempfile
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parents[1]
IMSCTL_SRC = BASE_DIR / "src/bananarchy-daemons/bananarchy-imsctl.c"
INC_DIR = BASE_DIR / "src/bananarchy-daemons"
def build_synthetic_mbn(config_type=1, desc="Telia_SE-Commercial", version=(5, 1, 1, 1),
plmns=((240, 1), (240, 5)), include_ims_nv=True):
# Build MCFG_TRL TLVs
trl_body = bytearray()
trl_body += struct.pack("<BH", 0x00, 2) + struct.pack("<H", 3)
desc_b = desc.encode("ascii") + b"\x00"
trl_body += struct.pack("<BH", 0x01, len(desc_b)) + desc_b
ver_u32 = ((version[0] & 0xFF) << 24) | ((version[1] & 0xFF) << 16) | ((version[2] & 0xFF) << 8) | (version[3] & 0xFF)
trl_body += struct.pack("<BH", 0x02, 4) + struct.pack("<I", ver_u32)
plmn_b = bytearray([0x00, len(plmns)])
for mcc, mnc in plmns:
plmn_b += struct.pack("<HH", mcc, mnc)
trl_body += struct.pack("<BH", 0x03, len(plmn_b)) + plmn_b
trl = b"MCFG_TRL" + struct.pack("<H", len(trl_body)) + trl_body
items = bytearray()
num_items = 1
if include_ims_nv:
nv_payload = struct.pack("<IB", 67218, 1)
items += struct.pack("<IBBH", 8 + len(nv_payload), 1, 0, 0) + nv_payload
efs_path = b"/nv/item_files/ims/qp_ims_reg_config\x00\x01"
items += struct.pack("<IBBH", 8 + len(efs_path), 2, 0, 0) + efs_path
num_items += 2
items += struct.pack("<IBBH", 8 + len(trl), 10, 0, 0) + trl
mcfg = b"MCFG" + struct.pack("<HHII", 3, config_type, num_items, 0) + items
# Minimal ELF32 LE container with 1 PT_LOAD header
ehdr_sz = 52
phdr_sz = 32
seg_off = ehdr_sz + phdr_sz
ehdr = (
b"\x7fELF\x01\x01\x01" + b"\x00" * 9 +
struct.pack("<HHIIIIIHHHHHH", 2, 40, 1, 0, ehdr_sz, 0, 0, ehdr_sz, phdr_sz, 1, 0, 0, 0)
)
phdr = struct.pack("<IIIIIIII", 1, seg_off, 0, 0, len(mcfg), len(mcfg), 4, 4)
return ehdr + phdr + mcfg
def fail(msg):
print(f"[FAIL] {msg}", file=sys.stderr)
return 1
def main():
with tempfile.TemporaryDirectory(prefix="bananarchy-mbn-test-") as td:
tmp = Path(td)
bin_path = tmp / "bananarchy-imsctl"
subprocess.run(
["gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror",
f"-I{INC_DIR}", str(IMSCTL_SRC), "-o", str(bin_path)],
check=True
)
conf_path = tmp / "ims.conf"
state_dir = tmp / "state"
lib_dir = tmp / "lib"
prof_dir = lib_dir / "profiles"
duress_flag = tmp / "duress_mode"
env = os.environ.copy()
env.update({
"BANANARCHY_IMS_CONF_PATH": str(conf_path),
"BANANARCHY_IMS_STATE_DIR": str(state_dir),
"BANANARCHY_IMS_LIB_DIR": str(lib_dir),
"BANANARCHY_IMS_PROFILES_DIR": str(prof_dir),
"BANANARCHY_DURESS_FLAG_PATH": str(duress_flag),
})
# 1. Inspect valid SW MCFG
sw_bytes = build_synthetic_mbn(config_type=1, desc="Telia_SE-VoLTE", plmns=((240, 1), (240, 5)))
sw_path = tmp / "telia_se_sw.mbn"
sw_path.write_bytes(sw_bytes)
expected_id = "ba_" + hashlib.sha1(sw_bytes).hexdigest()[:16]
r = subprocess.run([str(bin_path), "profile", "inspect", str(sw_path)],
env=env, capture_output=True, text=True, check=True)
if f"ID={expected_id}" not in r.stdout or "CONFIG_TYPE=SW" not in r.stdout or \
"IMS_CAPABLE=1" not in r.stdout or "PLMNS=240-01,240-05" not in r.stdout:
return fail(f"unexpected inspect output:\n{r.stdout}")
# 2. Reject HW MCFG on install
hw_path = tmp / "bad_hw.mbn"
hw_path.write_bytes(build_synthetic_mbn(config_type=0, desc="HW_Config"))
r = subprocess.run([str(bin_path), "profile", "install", str(hw_path)],
env=env, capture_output=True, text=True)
if r.returncode == 0:
return fail("HW MCFG (config_type=0) must be rejected by profile install")
# 3. Reject corrupted / truncated ELF
bad_path = tmp / "corrupt.mbn"
bad_path.write_bytes(b"\x7fELF\x01\x01\x01" + b"\x00" * 100)
r = subprocess.run([str(bin_path), "profile", "install", str(bad_path)],
env=env, capture_output=True, text=True)
if r.returncode == 0:
return fail("corrupted ELF without MCFG segment must be rejected")
# 4. Install + activate SW MCFG and verify list --tsv & config
r = subprocess.run([str(bin_path), "profile", "install", str(sw_path), "--activate"],
env=env, capture_output=True, text=True, check=True)
if f"INSTALLED={expected_id}" not in r.stdout or "ACTIVATED=1" not in r.stdout:
return fail(f"install output mismatch: {r.stdout}")
if not (prof_dir / f"{expected_id}.mbn").is_file():
return fail("installed .mbn file missing in store")
r = subprocess.run([str(bin_path), "profile", "list", "--tsv"],
env=env, capture_output=True, text=True, check=True)
if f"{expected_id}\t1\tSW\t1\t5.1.1.1\t240-01,240-05\tTelia_SE-VoLTE" not in r.stdout:
return fail(f"profile list --tsv mismatch:\n{r.stdout}")
# 5. PLMN auto-match (clear active_mbn first, then auto-match 240-05)
subprocess.run([str(bin_path), "profile", "reset-default"], env=env, check=True)
match_env = env.copy()
match_env["BANANARCHY_MOCK_MCC"] = "240"
match_env["BANANARCHY_MOCK_MNC"] = "05"
r = subprocess.run([str(bin_path), "auto-match"], env=match_env, capture_output=True, text=True, check=True)
if f"MATCHED={expected_id}" not in r.stdout:
return fail(f"auto-match failed for PLMN 240-05: {r.stdout}")
# 6. Settings validation & duress blocking
subprocess.run([str(bin_path), "set", "volte_mode", "auto"], env=env, check=True)
r = subprocess.run([str(bin_path), "get", "volte_mode"], env=env, capture_output=True, text=True, check=True)
if r.stdout.strip() != "auto":
return fail(f"expected volte_mode=auto, got {r.stdout.strip()}")
r = subprocess.run([str(bin_path), "set", "volte_mode", "bogus"], env=env, capture_output=True, text=True)
if r.returncode == 0:
return fail("invalid volte_mode must fail")
duress_flag.write_text("1\n")
r = subprocess.run([str(bin_path), "set", "volte_mode", "on"], env=env, capture_output=True, text=True)
if r.returncode == 0:
return fail("mutating imsctl set must be blocked in duress mode")
r = subprocess.run([str(bin_path), "profile", "remove", expected_id], env=env, capture_output=True, text=True)
if r.returncode == 0:
return fail("mutating imsctl profile remove must be blocked in duress mode")
duress_flag.unlink()
subprocess.run([str(bin_path), "profile", "remove", expected_id], env=env, check=True)
if (prof_dir / f"{expected_id}.mbn").exists():
return fail("removed .mbn still exists")
print("[ok] test-ims-mbn: ELF32 MCFG parser, HW/corrupt rejection, store, PLMN match, and duress guards")
return 0
if __name__ == "__main__":
sys.exit(main())
+488
View File
@@ -0,0 +1,488 @@
#!/usr/bin/env python3
# Offline host integration test for bananarchy-imsd + bananarchy-imsctl over a
# mock AF_UNIX SEQPACKET QRTR router (NAS 4G-only auto-activation, QMI_PDC chunked
# MBN install, QMI_DSD ims APN, QMI_IMSDCM bearer control, and userspace VoLTE fallback).
import hashlib
import os
import selectors
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parents[1]
SRC_DIR = BASE_DIR / "src/bananarchy-daemons"
sys.path.insert(0, str(BASE_DIR / "scripts"))
from importlib.machinery import SourceFileLoader
MOCK_MAGIC = 0x51525452
MSG_LOOKUP = 1
MSG_REGISTER = 2
MSG_DATA = 3
HDR_FMT = "<9I"
HDR_SIZE = struct.calcsize(HDR_FMT)
SVC_NAS = 0x0003
SVC_IMS = 0x0012
SVC_IMSA = 0x0021
SVC_PDC = 0x0024
SVC_DSD = 0x002A
SVC_IMSDCM = 0x0302
def tlv(t, val_bytes):
return struct.pack("<BH", t, len(val_bytes)) + val_bytes
def find_tlvs(buf):
out = {}
off = 0
while off + 3 <= len(buf):
t, l = struct.unpack_from("<BH", buf, off)
off += 3
if off + l > len(buf):
break
out[t] = buf[off:off + l]
off += l
return out
def pack_qmi_rsp(txn_id, msg_id, extra_tlvs=b"", err=0):
res = struct.pack("<HH", 0 if err == 0 else 1, err)
tlvs = tlv(0x02, res) + extra_tlvs
return struct.pack("<BHHH", 0x02, txn_id, msg_id, len(tlvs)) + tlvs
class MockQrtrRouter:
def __init__(self, sock_path):
self.sock_path = sock_path
self.srv = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
self.srv.bind(str(sock_path))
self.srv.listen(16)
self.srv.setblocking(False)
self.sel = selectors.DefaultSelector()
self.sel.register(self.srv, selectors.EVENT_READ)
self.clients = {} # conn -> (node, port)
self.ports = {} # (node, port) -> conn
self.services = {} # svc -> (node, port)
self.stop_evt = threading.Event()
# Configurable modem simulation state
self.lte_only = False
self.has_ims_qmi = True
self.imsa_reg = True
self.pdc_chunks = bytearray()
self.pdc_selected = ""
self.pdc_activated = False
self.dsd_ims_apn_set = False
self.ims_set_calls = []
self.pending_local_rsp = {}
self.lock = threading.Lock()
self.thread = threading.Thread(target=self._loop, daemon=True)
def start(self):
self.thread.start()
def stop(self):
self.stop_evt.set()
self.thread.join(timeout=2)
self.sel.close()
self.srv.close()
def _send_mock_pkt(self, conn, msg_type, src_n, src_p, dst_n, dst_p, svc, inst, payload=b""):
pkt = struct.pack(HDR_FMT, MOCK_MAGIC, msg_type, src_n, src_p, dst_n, dst_p,
svc, inst, len(payload)) + payload
try:
conn.send(pkt)
except OSError:
pass
def _handle_builtin_qmi(self, svc_port, payload):
if len(payload) < 7:
return pack_qmi_rsp(0, 0, err=1)
flags, txn_id, msg_id, tlen = struct.unpack_from("<BHHH", payload, 0)
tlvs = find_tlvs(payload[7:7 + tlen])
with self.lock:
if svc_port == 100 + SVC_NAS:
if msg_id == 0x0024:
# Serving system
if self.lte_only:
srv = struct.pack("<BBBBBB", 1, 0, 1, 0, 1, 0x08) # LTE only, no CS
else:
srv = struct.pack("<BBBBBBB", 1, 1, 1, 0, 2, 0x08, 0x05) # LTE + UMTS
plmn = struct.pack("<HHB", 240, 1, 0)
return pack_qmi_rsp(txn_id, msg_id, tlv(0x01, srv) + tlv(0x12, plmn))
if msg_id == 0x0034:
mask = 0x0010 if self.lte_only else 0x001F
return pack_qmi_rsp(txn_id, msg_id, tlv(0x11, struct.pack("<H", mask)))
elif svc_port == 100 + SVC_DSD:
if msg_id == 0x0051:
v = tlvs.get(0x01, b"")
if len(v) >= 10:
alen = v[0]
apn = v[1:1 + alen].decode("ascii", errors="ignore")
mask = struct.unpack_from("<Q", v, 1 + alen)[0]
if apn == "ims" and (mask & 0x04):
self.dsd_ims_apn_set = True
return pack_qmi_rsp(txn_id, msg_id)
elif svc_port == 100 + SVC_IMS:
if msg_id == 0x008F:
en_volte = tlvs.get(0x11, b"\x00")[0]
en_vowifi = tlvs.get(0x1C, b"\x00")[0]
self.ims_set_calls.append((en_volte, en_vowifi))
return pack_qmi_rsp(txn_id, msg_id)
elif svc_port == 100 + SVC_IMSA:
if msg_id == 0x0020:
return pack_qmi_rsp(txn_id, msg_id, tlv(0x10, bytes([2 if self.imsa_reg else 0])))
if msg_id == 0x0021:
return pack_qmi_rsp(txn_id, msg_id, tlv(0x11, bytes([2 if self.imsa_reg else 0])))
elif svc_port == 100 + SVC_PDC:
if msg_id == 0x0026:
fr = tlvs.get(0x03, b"")
if len(fr) >= 2:
clen = struct.unpack_from("<H", fr, 0)[0]
self.pdc_chunks.extend(fr[2:2 + clen])
return pack_qmi_rsp(txn_id, msg_id)
if msg_id == 0x0023:
sel = tlvs.get(0x01, b"")
if len(sel) >= 2:
ilen = sel[1]
self.pdc_selected = sel[2:2 + ilen].decode("ascii", errors="ignore")
return pack_qmi_rsp(txn_id, msg_id)
if msg_id == 0x0027:
self.pdc_activated = True
return pack_qmi_rsp(txn_id, msg_id)
if msg_id in (0x0020, 0x0025, 0x002B):
return pack_qmi_rsp(txn_id, msg_id)
return pack_qmi_rsp(txn_id, msg_id)
def _lookup_addr(self, svc):
with self.lock:
if svc in self.services:
return self.services[svc]
if svc == SVC_NAS:
return (2, 100 + SVC_NAS)
if svc == SVC_DSD:
return (2, 100 + SVC_DSD)
if svc == SVC_PDC:
return (2, 100 + SVC_PDC)
if svc in (SVC_IMS, SVC_IMSA) and self.has_ims_qmi:
return (2, 100 + svc)
return (0, 0)
def query_imsdcm(self, msg_id, tlvs_bytes):
dn, dp = self._lookup_addr(SVC_IMSDCM)
if dp == 0:
raise RuntimeError("IMSDCM not registered")
evt = threading.Event()
txn = 900 + msg_id
with self.lock:
self.pending_local_rsp[txn] = (evt, None)
conn = self.ports[(dn, dp)]
qmi_req = struct.pack("<BHHH", 0x00, txn, msg_id, len(tlvs_bytes)) + tlvs_bytes
self._send_mock_pkt(conn, MSG_DATA, 2, 999, dn, dp, 0, 0, qmi_req)
if not evt.wait(timeout=3.0):
raise RuntimeError("timeout waiting for IMSDCM response")
with self.lock:
_, rsp = self.pending_local_rsp.pop(txn)
return rsp
def _loop(self):
next_port = 1000
while not self.stop_evt.is_set():
events = self.sel.select(timeout=0.05)
for key, _ in events:
if key.fileobj is self.srv:
conn, _ = self.srv.accept()
conn.setblocking(False)
self.sel.register(conn, selectors.EVENT_READ)
self.clients[conn] = None
else:
conn = key.fileobj
try:
data = conn.recv(8192)
except OSError:
data = b""
if not data:
addr = self.clients.pop(conn, None)
if addr:
self.ports.pop(addr, None)
with self.lock:
for svc_k in [k for k, v in self.services.items() if v == addr]:
del self.services[svc_k]
self.sel.unregister(conn)
conn.close()
continue
if len(data) < HDR_SIZE:
continue
magic, mtype, sn, sp, dn, dp, svc, inst, plen = struct.unpack_from(HDR_FMT, data, 0)
if magic != MOCK_MAGIC:
continue
payload = data[HDR_SIZE:HDR_SIZE + plen]
if self.clients[conn] is None:
if sp == 0:
sp = next_port
next_port += 1
self.clients[conn] = (sn, sp)
self.ports[(sn, sp)] = conn
else:
sn, sp = self.clients[conn]
if mtype == MSG_LOOKUP:
rn, rp = self._lookup_addr(svc)
self._send_mock_pkt(conn, MSG_LOOKUP, 0, 0, rn, rp, svc, inst)
elif mtype == MSG_REGISTER:
with self.lock:
self.services[svc] = (sn, sp)
elif mtype == MSG_DATA:
if dn == 2 and dp in self.pending_local_rsp_match(payload):
txn = struct.unpack_from("<H", payload, 1)[0]
with self.lock:
evt, _ = self.pending_local_rsp[txn]
self.pending_local_rsp[txn] = (evt, payload)
evt.set()
elif dn == 2:
rsp = self._handle_builtin_qmi(dp, payload)
self._send_mock_pkt(conn, MSG_DATA, dn, dp, sn, sp, 0, 0, rsp)
else:
tconn = self.ports.get((dn, dp))
if tconn:
self._send_mock_pkt(tconn, MSG_DATA, sn, sp, dn, dp, 0, 0, payload)
def pending_local_rsp_match(self, payload):
if len(payload) < 7 or payload[0] != 0x02:
return set()
txn = struct.unpack_from("<H", payload, 1)[0]
if txn in self.pending_local_rsp:
return {999}
return set()
def fail(msg):
print(f"[FAIL] {msg}", file=sys.stderr)
return 1
def read_state_dict(path):
d = {}
for line in Path(path).read_text().splitlines():
if "=" in line:
k, v = line.split("=", 1)
d[k] = v.strip("'")
return d
def wait_for_state(st_path, pred, timeout=3.0):
deadline = time.monotonic() + timeout
st = {}
while time.monotonic() < deadline:
if st_path.exists():
st = read_state_dict(st_path)
if pred(st):
return st
time.sleep(0.05)
return st
def main():
test_mbn_mod = SourceFileLoader("test_ims_mbn", str(BASE_DIR / "scripts/test-ims-mbn.py")).load_module()
with tempfile.TemporaryDirectory(prefix="bananarchy-imsd-test-") as td:
tmp = Path(td)
imsd_bin = tmp / "bananarchy-imsd"
ctl_bin = tmp / "bananarchy-imsctl"
subprocess.run(
["gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror",
f"-I{SRC_DIR}", str(SRC_DIR / "bananarchy-imsd.c"), "-o", str(imsd_bin)],
check=True
)
subprocess.run(
["gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror",
f"-I{SRC_DIR}", str(SRC_DIR / "bananarchy-imsctl.c"), "-o", str(ctl_bin)],
check=True
)
state_dir = tmp / "state"
state_dir.mkdir()
conf_path = tmp / "ims.conf"
lib_dir = tmp / "lib"
prof_dir = lib_dir / "profiles"
qrtr_sock = tmp / "qrtr.sock"
vowifi_log = tmp / "vowifi.log"
bearer_log = tmp / "bearer.log"
conf_path.write_text(
"volte_mode=auto\n"
"vowifi_mode=auto\n"
"volte_backend=auto\n"
"ims_apn=ims\n"
"ims_sim_slot=1\n"
"auto_install_mbn=1\n"
)
# Mock bananarchy-vowifi script creating vowifi.sock and reporting registered=1
mock_vowifi = tmp / "mock-vowifi.py"
mock_vowifi.write_text(f"""#!/usr/bin/env python3
import os, signal, socket, sys, time
sd = os.environ["BANANARCHY_IMS_STATE_DIR"]
open(r"{vowifi_log}", "a").write("START " + " ".join(sys.argv[1:]) + "\\n")
sp = sd + "/vowifi.sock"
try: os.unlink(sp)
except OSError: pass
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.bind(sp)
s.listen(4)
s.settimeout(0.2)
stop = False
def on_sig(*_):
global stop
stop = True
signal.signal(signal.SIGTERM, on_sig)
mode = "vowifi"
for a in sys.argv[1:]:
if a.startswith("--mode="): mode = a.split("=", 1)[1]
while not stop:
try:
c, _ = s.accept()
except socket.timeout:
continue
d = c.recv(256).decode().strip()
if d == "STATUS":
c.send(f"OK registered=1 active_calls=0 tech={{mode}} ipv6=0 pcscf=10.99.0.10 tun_ip=10.99.0.2 epdg=epdg.test\\n".encode())
elif d == "STOP":
c.send(b"OK\\n")
stop = True
c.close()
open(r"{vowifi_log}", "a").write("STOP " + mode + "\\n")
""")
mock_vowifi.chmod(0o755)
# Mock bearer script
mock_bearer = tmp / "mock-bearer.sh"
mock_bearer.write_text(f"""#!/bin/sh
echo "$*" >> "{bearer_log}"
if [ "$1" = "up" ]; then
echo "IFACE=wwan1"
echo "IP=10.64.0.2"
else
echo "IFACE="
echo "IP="
fi
""")
mock_bearer.chmod(0o755)
router = MockQrtrRouter(qrtr_sock)
router.start()
env = os.environ.copy()
env.update({
"BANANARCHY_IMS_CONF_PATH": str(conf_path),
"BANANARCHY_IMS_STATE_DIR": str(state_dir),
"BANANARCHY_IMS_LIB_DIR": str(lib_dir),
"BANANARCHY_IMS_PROFILES_DIR": str(prof_dir),
"BANANARCHY_QRTR_MOCK_SOCK": str(qrtr_sock),
"BANANARCHY_VOWIFI_BIN": str(mock_vowifi),
"BANANARCHY_IMS_BEARER_SH": str(mock_bearer),
"BANANARCHY_IMS_ALLOW_NONROOT": "1",
"BANANARCHY_IMS_NO_UI_NOTIFY": "1",
"BANANARCHY_VOWIFI_WIFI_UP": "1",
})
imsd_proc = subprocess.Popen([str(imsd_bin)], env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
st_path = state_dir / "state.env"
deadline = time.monotonic() + 4.0
while time.monotonic() < deadline and not st_path.exists():
time.sleep(0.05)
if not st_path.exists():
return fail("bananarchy-imsd did not write state.env")
# 1) Default auto mode on LTE+UMTS -> DISABLED (VOLTE_ACTIVE=0, VOWIFI_ACTIVE=0, 0x0302 not registered)
st = read_state_dict(st_path)
if st.get("VOLTE_ACTIVE") != "0" or st.get("VOWIFI_ACTIVE") != "0" or st.get("NETWORK_4G_ONLY") != "0":
return fail(f"expected auto mode disabled on LTE+UMTS, got {st}")
with router.lock:
if SVC_IMSDCM in router.services:
return fail(f"QMI_IMSDCM (0x0302) must not be registered at idle: {router.services}")
if vowifi_log.exists():
return fail("vowifi must not start when network is not 4G-only")
# 2) Switch mock NAS to 4G-only -> both VoLTE and VoWiFi auto-activate!
with router.lock:
router.lte_only = True
subprocess.run([str(ctl_bin), "notify", "wwan0", "up"], env=env, check=True)
st = wait_for_state(st_path, lambda s: (
s.get("NETWORK_4G_ONLY") == "1" and s.get("VOLTE_REGISTERED") == "1" and
s.get("VOWIFI_REGISTERED") == "1"
), timeout=3.5)
if st.get("NETWORK_4G_ONLY") != "1" or st.get("VOLTE_ACTIVE") != "1" or \
st.get("VOLTE_REGISTERED") != "1" or st.get("VOWIFI_ACTIVE") != "1" or \
st.get("VOWIFI_REGISTERED") != "1":
return fail(f"expected 4G-only auto-activation, got {st}")
if not router.dsd_ims_apn_set or (1, 0) not in router.ims_set_calls:
return fail(f"expected QMI_DSD ims APN & QMI_IMS enable, calls={router.ims_set_calls}")
# 3) Install + activate SW MBN through imsctl -> chunked QMI_PDC upload!
sw_bytes = test_mbn_mod.build_synthetic_mbn(desc="MockCarrier-4G")
mbn_file = tmp / "carrier.mbn"
mbn_file.write_bytes(sw_bytes)
exp_id = "ba_" + hashlib.sha1(sw_bytes).hexdigest()[:16]
subprocess.run([str(ctl_bin), "profile", "install", str(mbn_file), "--activate"],
env=env, check=True)
time.sleep(0.2)
with router.lock:
uploaded_sha1 = hashlib.sha1(bytes(router.pdc_chunks)).hexdigest()
sel_id = router.pdc_selected
act_ok = router.pdc_activated
if uploaded_sha1 != hashlib.sha1(sw_bytes).hexdigest() or sel_id != exp_id or not act_ok:
return fail(f"QMI_PDC MBN install mismatch: sel={sel_id} act={act_ok}")
# 4) QMI_IMSDCM (0x0302) PDP_ACTIVATE / PDP_DEACTIVATE bearer driving
apn_tlv = tlv(0x03, bytes([3]) + b"ims")
rsp_act = router.query_imsdcm(0x0020, apn_tlv)
if len(rsp_act) < 7 or find_tlvs(rsp_act[7:]).get(0x10) != b"10.64.0.2":
return fail(f"QMI_IMSDCM activate response mismatch: {rsp_act!r}")
router.query_imsdcm(0x0021, b"")
blogs = bearer_log.read_text().splitlines()
if "up ims" not in blogs or "down ims" not in blogs:
return fail(f"expected bearer up/down calls, got {blogs}")
# 5) Turn Wi-Fi off and simulate missing QMI_IMS -> auto fallback to userspace VoLTE!
env["BANANARCHY_VOWIFI_WIFI_UP"] = "0"
# Restart imsd briefly with Wi-Fi down & no QMI_IMS to verify userspace VoLTE launch
subprocess.run([str(ctl_bin), "notify", "wlan0", "down"], env=env, check=True)
imsd_proc.terminate()
imsd_proc.wait(timeout=3)
with router.lock:
router.has_ims_qmi = False
imsd_proc = subprocess.Popen([str(imsd_bin)], env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
st = wait_for_state(st_path, lambda s: (
s.get("VOLTE_BACKEND") == "userspace" and s.get("VOLTE_REGISTERED") == "1"
), timeout=3.5)
if st.get("VOLTE_BACKEND") != "userspace" or st.get("VOLTE_REGISTERED") != "1":
return fail(f"expected userspace VoLTE fallback when QMI_IMS absent, got {st}")
if "START --mode=volte" not in vowifi_log.read_text():
return fail(f"expected bananarchy-vowifi --mode=volte launch, log={vowifi_log.read_text()}")
finally:
if imsd_proc.poll() is None:
imsd_proc.terminate()
try:
imsd_proc.wait(timeout=3)
except subprocess.TimeoutExpired:
imsd_proc.kill()
router.stop()
print("[ok] test-imsd-volte: 4G-only auto-activation, QMI_PDC chunked MBN, QMI_IMSDCM bearer, and userspace VoLTE fallback")
return 0
if __name__ == "__main__":
sys.exit(main())
+780
View File
@@ -0,0 +1,780 @@
#!/usr/bin/env python3
"""Offline host regression tests for LTE attach, PS domain recovery, WDS bind, and APN sync."""
import os
import selectors
import socket
import struct
import subprocess
import sys
import tempfile
import threading
from pathlib import Path
BASE = Path(__file__).resolve().parents[1]
UIM_SEL = BASE / "overlay/rootfs/usr/libexec/msm-modem-uim-selection"
IMS_BEARER_SH = BASE / "overlay/rootfs/usr/bin/bananarchy-ims-bearer.sh"
DPM_DISP_SH = BASE / "overlay/rootfs/etc/NetworkManager/dispatcher.d/10-bananarchy-dpm.sh"
WDS_BIND_SRC = BASE / "src/bananarchy-daemons/mm-wds-bind.c"
NETWORKS_SRC = BASE / "src/dwm-plugins/networks_plugin.cpp"
MOCK_MAGIC = 0x51525452
MSG_LOOKUP = 1
MSG_DATA = 3
HDR_FMT = "<9I"
HDR_SIZE = struct.calcsize(HDR_FMT)
SVC_NAS = 3
SVC_DSD = 0x2A
def fail(msg):
sys.stderr.write(f"[fail] {msg}\n")
return 1
def tlv(t, val):
return struct.pack("<BH", t, len(val)) + val
def parse_tlvs(buf):
out = {}
pos = 0
while pos + 3 <= len(buf):
tt, tl = struct.unpack_from("<BH", buf, pos)
pos += 3
if pos + tl > len(buf):
break
out[tt] = buf[pos:pos + tl]
pos += tl
return out
def pack_qmi_rsp(txn_id, msg_id, extra=b"", err=0):
res = struct.pack("<HH", 0 if err == 0 else 1, err)
tlvs = tlv(0x02, res) + extra
return struct.pack("<BHHH", 0x02, txn_id, msg_id, len(tlvs)) + tlvs
class MockQmiServer:
def __init__(self, sock_path):
self.sock_path = sock_path
self.srv = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
self.srv.bind(str(sock_path))
self.srv.listen(8)
self.srv.setblocking(False)
self.sel = selectors.DefaultSelector()
self.sel.register(self.srv, selectors.EVENT_READ)
self.conn_sub = {}
self.dsd_sub = 0
self.dsd_data_enabled = 0
self.dsd_switch_calls = 0
self.stop_evt = threading.Event()
self.lock = threading.Lock()
self.events = []
self.subs = {
0: {"reg": 1, "cs": 1, "ps": 2, "mode": 0x001C, "dom": 0},
1: {"reg": 1, "cs": 1, "ps": 0, "mode": 0x0004, "dom": 2},
}
self.thread = threading.Thread(target=self._loop, daemon=True)
def start(self):
self.thread.start()
def stop(self):
self.stop_evt.set()
self.thread.join(timeout=2)
self.sel.close()
self.srv.close()
def _handle_qmi(self, conn, svc, payload):
if len(payload) < 7:
return pack_qmi_rsp(0, 0, err=1)
_, txn, msg_id, tlen = struct.unpack_from("<BHHH", payload, 0)
tlvs = parse_tlvs(payload[7:7 + tlen])
with self.lock:
if svc == SVC_DSD:
if msg_id == 0x0027: # BIND_SUBSCRIPTION
if 0x01 in tlvs and len(tlvs[0x01]) >= 4:
self.dsd_sub = struct.unpack("<I", tlvs[0x01][:4])[0]
self.events.append(("dsd_bind", self.dsd_sub))
return pack_qmi_rsp(txn, msg_id)
if msg_id == 0x0034: # NOTIFY_DATA_SETTINGS
if 0x10 in tlvs and len(tlvs[0x10]) >= 1:
self.dsd_data_enabled = tlvs[0x10][0]
self.events.append(("dsd_data", self.dsd_data_enabled))
return pack_qmi_rsp(txn, msg_id)
if msg_id == 0x004E: # SWITCH_DDS (must NOT be called)
self.dsd_switch_calls += 1
self.events.append(("dsd_switch_dds",))
return pack_qmi_rsp(txn, msg_id)
return pack_qmi_rsp(txn, msg_id)
sub = self.conn_sub.get(conn, 0)
st = self.subs[sub]
if msg_id == 0x0045: # BIND_SUBSCRIPTION
if 0x01 in tlvs and len(tlvs[0x01]) >= 1:
new_sub = tlvs[0x01][0]
if new_sub in self.subs:
self.conn_sub[conn] = new_sub
self.events.append(("bind", new_sub))
return pack_qmi_rsp(txn, msg_id)
if msg_id == 0x0034: # GET_SYSTEM_SELECTION_PREFERENCE
extra = (
tlv(0x11, struct.pack("<H", st["mode"])) +
tlv(0x18, struct.pack("<I", st["dom"]))
)
return pack_qmi_rsp(txn, msg_id, extra)
if msg_id == 0x0033: # SET_SYSTEM_SELECTION_PREFERENCE
dur = tlvs[0x17][0] if 0x17 in tlvs and len(tlvs[0x17]) >= 1 else None
new_mode = struct.unpack("<H", tlvs[0x11][:2])[0] if 0x11 in tlvs and len(tlvs[0x11]) >= 2 else None
new_dom = struct.unpack("<I", tlvs[0x18][:4])[0] if 0x18 in tlvs and len(tlvs[0x18]) >= 4 else None
if new_mode is not None:
st["mode"] = new_mode
if new_dom is not None:
st["dom"] = new_dom
self.events.append(("set_ssp", sub, new_mode, new_dom, dur))
return pack_qmi_rsp(txn, msg_id)
if msg_id == 0x0024: # GET_SERVING_SYSTEM
srv = struct.pack("<BBBBBB", st["reg"], st["cs"], st["ps"], 0, 1, 0x05)
plmn = struct.pack("<HHB", 255, 6, 0)
return pack_qmi_rsp(txn, msg_id, tlv(0x01, srv) + tlv(0x12, plmn))
if msg_id == 0x0022: # INITIATE_NETWORK_REGISTER
st["reg"] = 1
st["cs"] = 1
self.events.append(("reg", sub))
return pack_qmi_rsp(txn, msg_id)
if msg_id == 0x0023: # ATTACH_DETACH
act = tlvs[0x10][0] if 0x10 in tlvs and len(tlvs[0x10]) >= 1 else 0
if act == 1:
st["ps"] = 1
elif act == 2:
st["ps"] = 2
self.events.append(("attach", sub, act))
return pack_qmi_rsp(txn, msg_id)
return pack_qmi_rsp(txn, msg_id)
def _loop(self):
while not self.stop_evt.is_set():
for key, _ in self.sel.select(timeout=0.05):
if key.fileobj is self.srv:
c, _ = self.srv.accept()
c.setblocking(False)
self.sel.register(c, selectors.EVENT_READ)
with self.lock:
self.conn_sub[c] = 0
else:
c = key.fileobj
try:
data = c.recv(4096)
except OSError:
data = b""
if not data:
self.sel.unregister(c)
with self.lock:
self.conn_sub.pop(c, None)
c.close()
continue
if len(data) < HDR_SIZE:
continue
magic, mtype, sn, sp, dn, dp, svc, inst, plen = struct.unpack_from(HDR_FMT, data, 0)
if magic != MOCK_MAGIC:
continue
if mtype == MSG_LOOKUP:
rsp_p = struct.pack("<II", 2, 100 + svc) if svc in (SVC_NAS, SVC_DSD) else struct.pack("<II", 0, 0)
hdr = struct.pack(HDR_FMT, MOCK_MAGIC, MSG_LOOKUP, 0, 0, sn, sp, svc, inst, len(rsp_p))
c.send(hdr + rsp_p)
elif mtype == MSG_DATA:
payload = data[HDR_SIZE:HDR_SIZE + plen]
qmi_rsp = self._handle_qmi(c, svc, payload)
hdr = struct.pack(HDR_FMT, MOCK_MAGIC, MSG_DATA, dn, dp, sn, sp, svc, inst, len(qmi_rsp))
c.send(hdr + qmi_rsp)
def test_dual_and_single_sim_ps_domain(tmp):
sock_path = tmp / "qrtr.sock"
srv = MockQmiServer(sock_path)
srv.start()
try:
# 1) Dual-SIM: sub=1 holds cs-ps and sub=0 is stuck in cs-only + PS detached.
env = os.environ.copy()
env["BANANARCHY_QRTR_MOCK_SOCK"] = str(sock_path)
env["BANANARCHY_DUAL_SIM"] = "1"
env["BANANARCHY_POWER_RUNDIR"] = str(tmp / "pp_run")
res = subprocess.run([str(UIM_SEL), "ensure-ps-domain"], env=env,
capture_output=True, text=True)
if res.returncode != 0:
return fail(f"ensure-ps-domain dual-SIM failed: {res.stderr}")
with srv.lock:
ev = list(srv.events)
s0 = dict(srv.subs[0])
s1 = dict(srv.subs[1])
dsd_sub = srv.dsd_sub
dsd_en = srv.dsd_data_enabled
sw_calls = srv.dsd_switch_calls
if sw_calls != 0 or ("dsd_switch_dds",) in ev:
return fail(f"ensure-ps-domain must never call QMI_DSD 0x004E SWITCH_DDS: ev={ev}")
if dsd_sub != 1 or dsd_en != 1:
return fail(f"expected DSD 0x0027=1 and 0x0034=1, got sub={dsd_sub} data={dsd_en}")
idx_s1_demote = next(
(i for i, e in enumerate(ev) if e[:2] == ("set_ssp", 1) and e[3] == 0 and e[2] == 0x0004 and e[4] == 1),
-1,
)
idx_s0_promote = next(
(i for i, e in enumerate(ev) if e[:2] == ("set_ssp", 0) and e[3] == 2 and e[4] == 1),
-1,
)
if idx_s1_demote < 0 or idx_s0_promote < 0 or idx_s1_demote > idx_s0_promote:
return fail(f"expected sub=1 demoted to cs-only before sub=0 promoted to cs-ps; events={ev}")
if ("attach", 0, 1) not in ev or s0["dom"] != 2 or s0["ps"] != 1 or s1["dom"] != 0:
return fail(f"unexpected final dual-SIM NAS state: s0={s0} s1={s1} ev={ev}")
# 2a) Single-SIM with rat_parked present: promote to cs-ps, do NOT overwrite mode=0x0004.
pp_dir = tmp / "pp_run"
pp_dir.mkdir(parents=True, exist_ok=True)
rat_parked = pp_dir / "rat_parked"
rat_parked.write_text("")
with srv.lock:
srv.events.clear()
srv.subs[0] = {"reg": 1, "cs": 1, "ps": 2, "mode": 0x0004, "dom": 0}
env["BANANARCHY_DUAL_SIM"] = "0"
res = subprocess.run([str(UIM_SEL), "ensure-ps-domain"], env=env,
capture_output=True, text=True)
if res.returncode != 0:
return fail(f"ensure-ps-domain single-SIM (parked) failed: {res.stderr}")
with srv.lock:
ev = list(srv.events)
s0 = dict(srv.subs[0])
if s0["dom"] != 2 or s0["mode"] != 0x0004 or s0["ps"] != 1:
return fail(f"rat_parked must keep GSM mode while promoting PS domain; s0={s0} ev={ev}")
if any(e[0] == "set_ssp" and e[1] == 1 for e in ev):
return fail(f"single-SIM must not touch sub=1: ev={ev}")
# 2b) Single-SIM without rat_parked and stuck in mode=0x0004 + cs-only: restores mode=0x001C.
rat_parked.unlink()
with srv.lock:
srv.events.clear()
srv.subs[0] = {"reg": 1, "cs": 1, "ps": 2, "mode": 0x0004, "dom": 0}
res = subprocess.run([str(UIM_SEL), "ensure-ps-domain"], env=env,
capture_output=True, text=True)
if res.returncode != 0:
return fail(f"ensure-ps-domain single-SIM (unparked) failed: {res.stderr}")
with srv.lock:
s0 = dict(srv.subs[0])
if s0["dom"] != 2 or s0["mode"] != 0x001C or s0["ps"] != 1:
return fail(f"unparked single-SIM must restore mode=0x001c and cs-ps; s0={s0}")
print("[ok] test-lte-mobile-data: dual-SIM cs-only handoff, single-SIM PS attach, and rat_parked guard")
return 0
finally:
srv.stop()
def test_wds_apn_sync_and_mobile_data_prep(tmp):
sock_path = tmp / "qrtr_apn.sock"
srv = MockQmiServer(sock_path)
srv.start()
try:
nm_dir = tmp / "nm_cons"
nm_dir.mkdir(parents=True, exist_ok=True)
(nm_dir / "internet.nmconnection").write_text(
"[connection]\nid=internet\ntype=gsm\n\n[gsm]\napn=internet\n\n[ipv4]\nmethod=auto\n"
)
qmi_log = tmp / "qmicli_wds.log"
mm_log = tmp / "mmcli_wds.log"
dpm_log = tmp / "dpm.log"
bin_dir = tmp / "apn_bin"
bin_dir.mkdir(parents=True, exist_ok=True)
ssp_state_file = tmp / "ssp_dom.txt"
ssp_state_file.write_text("cs-only\n")
mock_qmi = bin_dir / "mock_qmicli"
mock_qmi.write_text(f"""#!/bin/sh
echo "$*" >> "{qmi_log}"
for a in "$@"; do
case "$a" in
--wds-get-profile-list=3gpp)
cat <<'EOF'
Profile list retrieved:
\t[1] 3gpp - profile1
\t\tAPN: ''
\t\tPDP type: 'ipv4-or-ipv6'
\t[2] 3gpp - profile2
\t\tAPN: 'ims'
\t\tPDP type: 'ipv4-or-ipv6'
\t[3] 3gpp - sos
\t\tAPN: 'sos'
\t\tPDP type: 'ipv4-or-ipv6'
\t[4] 3gpp - qdp_profile_ia
\t\tAPN: '3g.utel.ua'
\t\tPDP type: 'ipv4'
\t[5] 3gpp - modem_def_prof
\t\tAPN: '3g.utel.ua'
\t\tPDP type: 'ipv4'
EOF
exit 0
;;
--wds-get-lte-attach-pdn-list)
echo "Attach PDN list retrieved:"
echo "\tCurrent list: '4'"
exit 0
;;
--wds-get-default-profile-number=3gpp)
echo "Default profile number retrieved:"
echo "\tDefault profile number: '5'"
exit 0
;;
--nas-get-serving-system)
echo "Registration state: 'registered'"
echo "CS: 'attached'"
echo "PS: 'attached'"
echo "MCC: '255'"
echo "MNC: '6'"
exit 0
;;
--nas-get-system-selection-preference)
echo "Service domain preference: '$(cat "{ssp_state_file}")'"
exit 0
;;
--uim-get-card-status)
cat <<'EOF'
Provisioning applications:
\tPrimary GW: slot '2', application '1'
\tSecondary GW: slot '1', application '1'
Slot [1]:
\tCard state: 'present'
\tApplication [1]:
\t\tApplication type: 'usim (2)'
\t\tApplication state: 'ready'
\t\tApplication ID:
\t\t\tA0:00:00:00:87:10:02:FF:FF:FF:FF:89:03:02:00:00
Slot [2]:
\tCard state: 'present'
\tApplication [1]:
\t\tApplication type: 'usim (2)'
\t\tApplication state: 'ready'
\t\tApplication ID:
\t\t\tA0:00:00:00:87:10:02:FF:FF:FF:FF:89:03:02:00:00
EOF
exit 0
;;
--uim-change-provisioning-session=*)
case "$a" in
*activate=no*) echo "cs-ps" > "{ssp_state_file}" ;;
esac
exit 0
;;
esac
done
exit 0
""")
mock_qmi.chmod(0o755)
# Also test mmcli -K ANSI-free state: failed recovery, nmcli gsm check, and
# --3gpp-set-initial-eps-bearer-settings skip when APN matches.
mm_state_file = tmp / "mm_state.txt"
mm_state_file.write_text("failed\n")
rc_log = tmp / "rc_service.log"
mock_rc = bin_dir / "rc-service"
mock_rc.write_text(f"""#!/bin/sh
echo "$*" >> "{rc_log}"
if [ "$1" = "modemmanager" ] && [ "$2" = "restart" ]; then
echo "disabled" > "{mm_state_file}"
fi
exit 0
""")
mock_rc.chmod(0o755)
nm_log = tmp / "nmcli_ops.log"
nm_conn_state = tmp / "nm_gsm_state.txt"
nm_conn_state.write_text("gsm:connecting (prepare)\n")
mock_nmcli = bin_dir / "nmcli"
mock_nmcli.write_text(f"""#!/bin/sh
echo "$*" >> "{nm_log}"
case "$*" in
*"-t -f UUID,TYPE connection show"*)
echo "0d15223d-0492-4d43-b85f-981fee0a2ff0:gsm"
echo "83bd1823-feca-4c2b-9205-4b83dc792e1f:802-3-ethernet"
exit 0
;;
*"device disconnect qrtr0"*)
echo "gsm:disconnected" > "{nm_conn_state}"
exit 0
;;
*"-t -f TYPE,STATE device status"*)
cat "{nm_conn_state}"
exit 0
;;
esac
exit 0
""")
mock_nmcli.chmod(0o755)
mock_mm = bin_dir / "mmcli"
mock_mm.write_text(f"""#!/bin/sh
echo "$*" >> "{mm_log}"
st="$(cat "{mm_state_file}" 2>/dev/null || echo failed)"
case "$*" in
"-L") echo "/org/freedesktop/ModemManager1/Modem/0"; exit 0 ;;
"-m any -e")
echo "registered" > "{mm_state_file}"
exit 0
;;
*"--3gpp-set-initial-eps-bearer-settings"*) exit 0 ;;
*"-m any -K"*)
echo "modem.generic.state : $st"
echo "modem.3gpp.packet-service-state : attached"
echo "modem.3gpp.eps.initial-bearer.settings.apn : --"
exit 0
;;
*"-m any"*)
if [ "$st" = "failed" ]; then
printf 'state: \\033[31mfailed\\033[0m\\n'
else
echo "state: $st"
fi
echo "packet service state: attached"
echo "initial bearer apn: internet"
exit 0
;;
esac
exit 0
""")
mock_mm.chmod(0o755)
mock_dpm = tmp / "mock_dpm.sh"
mock_dpm.write_text(f"#!/bin/sh\necho \"$*\" >> \"{dpm_log}\"\nexit 0\n")
mock_dpm.chmod(0o755)
run_dir = tmp / "ba_run"
dsds_file = tmp / "sxmo_dsds_active"
dsds_file.write_text("1\n")
env = os.environ.copy()
env.update({
"PATH": f"{bin_dir}:{env.get('PATH', '')}",
"BANANARCHY_QRTR_MOCK_SOCK": str(sock_path),
"BANANARCHY_DUAL_SIM": "1",
"BANANARCHY_USE_MM": "1",
"BANANARCHY_QMICLI_BIN": str(mock_qmi),
"BANANARCHY_DPM_SH": str(mock_dpm),
"BANANARCHY_NM_CONNECTIONS_DIR": str(nm_dir),
"BANANARCHY_POWER_RUNDIR": str(tmp / "pp_run2"),
"BANANARCHY_RUNDIR": str(run_dir),
"BANANARCHY_DSDS_ACTIVE_FILE": str(dsds_file),
"BANANARCHY_UIM_SEL": str(UIM_SEL),
})
res = subprocess.run([str(UIM_SEL), "mobile-data-prep"], env=env,
capture_output=True, text=True)
if res.returncode != 0:
return fail(f"mobile-data-prep failed: {res.stderr}")
if "modemmanager restart" not in rc_log.read_text():
return fail(f"mobile-data-prep must restart failed ModemManager under mmcli -K; rc_log={rc_log.read_text()}")
mm_pre_log = mm_log.read_text()
if "-m any -e" not in mm_pre_log or "-m any -K" not in mm_pre_log:
return fail(f"expected mmcli -K and -m any -e calls; mm_log:\n{mm_pre_log}")
if "--3gpp-set-initial-eps-bearer-settings" in mm_pre_log:
return fail(f"mobile-data-prep must skip initial-bearer write when APN matches; mm_log:\n{mm_pre_log}")
nm_ops = nm_log.read_text()
if "connection modify 0d15223d-0492-4d43-b85f-981fee0a2ff0 connection.autoconnect no" not in nm_ops:
return fail(f"mobile-data-prep must disable gsm autoconnect; nm_log:\n{nm_ops}")
if "device disconnect qrtr0" not in nm_ops:
return fail(f"mobile-data-prep must clear connecting qrtr0 before dial; nm_log:\n{nm_ops}")
qlog = qmi_log.read_text()
for pid in (1, 4, 5):
if f"--wds-modify-profile=3gpp,{pid},apn=internet" not in qlog:
return fail(f"expected profile {pid} modified to internet; log:\n{qlog}")
if "--wds-modify-profile=3gpp,2" in qlog or "--wds-modify-profile=3gpp,3" in qlog:
return fail(f"must never overwrite ims/sos profiles 2 or 3; log:\n{qlog}")
if "activate=no,session-type=secondary-gw-provisioning" not in qlog:
return fail(f"expected cs-only fallback pausing secondary-gw; log:\n{qlog}")
pause_file = run_dir / "dsds_paused_for_data"
if not pause_file.is_file() or "SLOT=1" not in pause_file.read_text():
return fail(f"expected dsds_paused_for_data SLOT=1, got {pause_file.exists()}")
if dsds_file.read_text().strip() != "0":
return fail(f"expected sxmo_dsds_active=0 while paused, got {dsds_file.read_text()!r}")
if "open" not in dpm_log.read_text().splitlines():
return fail(f"expected bananarchy-dpm.sh open call; log={dpm_log.read_text()}")
with srv.lock:
s0 = dict(srv.subs[0])
if s0["dom"] != 2 or s0["ps"] != 1:
return fail(f"mobile-data-prep did not promote PS domain: {s0}")
# Test dispatcher qrtr0 down invokes restore-dsds and clears dsds_paused_for_data.
qmi_log.write_text("")
disp_res = subprocess.run([str(DPM_DISP_SH), "qrtr0", "down"], env=env,
capture_output=True, text=True)
if disp_res.returncode != 0:
return fail(f"10-bananarchy-dpm.sh qrtr0 down failed: {disp_res.stderr}")
if pause_file.exists():
return fail("dsds_paused_for_data should be removed after restore-dsds")
if dsds_file.read_text().strip() != "1":
return fail(f"expected sxmo_dsds_active=1 after restore-dsds, got {dsds_file.read_text()!r}")
qlog_rest = qmi_log.read_text()
if "slot=1,activate=yes,session-type=secondary-gw-provisioning" not in qlog_rest:
return fail(f"expected secondary-gw reactivated by restore-dsds; log:\n{qlog_rest}")
# Verify sync-apn never triggers --3gpp-set-initial-eps-bearer-settings 3GPP detach.
mm_log.write_text("")
env["BANANARCHY_SKIP_MM"] = "0"
res2 = subprocess.run([str(UIM_SEL), "sync-apn", "internet"], env=env,
capture_output=True, text=True)
if res2.returncode != 0:
return fail(f"sync-apn failed: {res2.stderr}")
if "--3gpp-set-initial-eps-bearer-settings" in mm_log.read_text():
return fail(f"sync-apn must never call --3gpp-set-initial-eps-bearer-settings; log={mm_log.read_text()}")
print("[ok] test-lte-mobile-data: WDS profiles [1/4/5] sync, initial-bearer skip, cs-only pause & dispatcher restore-dsds")
return 0
finally:
srv.stop()
def test_mm_wds_bind_preload(tmp):
# Compile mm-wds-bind.c alongside a tiny stub libqmi harness and verify via ctypes
# that QMI_SERVICE_WDS (1) binds PRIMARY (1), post-mux/data port binds serialize a
# fresh PRIMARY bind before firing caller callback, non-WDS services are skipped,
# and BANANARCHY_WDS_SUBSCRIPTION=0 disables binding.
harness_c = tmp / "wds_harness.c"
harness_c.write_text("""
#include <stddef.h>
typedef struct {
int service;
unsigned int bound_sub;
int bind_calls;
int port_binds;
} FakeClient;
static FakeClient g_clients[4];
static int g_next = 0;
void *qmi_device_allocate_client_finish(void *self, void *res, void **err) {
(void)res; (void)err;
int idx = g_next++ & 3;
g_clients[idx].service = (int)(long)self;
g_clients[idx].bound_sub = 0;
g_clients[idx].bind_calls = 0;
g_clients[idx].port_binds = 0;
return &g_clients[idx];
}
int qmi_client_get_service(void *client) {
return client ? ((FakeClient *)client)->service : 0;
}
void *qmi_message_wds_bind_subscription_input_new(void) {
static unsigned int inp_slot;
inp_slot = 0;
return &inp_slot;
}
int qmi_message_wds_bind_subscription_input_set_subscription_id(void *inp, unsigned int sub, void **err) {
(void)err;
if (!inp) return 0;
*(unsigned int *)inp = sub;
return 1;
}
void qmi_message_wds_bind_subscription_input_unref(void *inp) {
(void)inp;
}
void *qmi_client_wds_bind_subscription_finish(void *client, void *res, void **err) {
(void)client; (void)res; (void)err;
return (void *)0x1;
}
void qmi_message_wds_bind_subscription_output_unref(void *out) {
(void)out;
}
void qmi_client_wds_bind_subscription(void *client, void *inp, unsigned int timeout,
void *canc, void (*cb)(void *, void *, void *), void *ud) {
(void)timeout; (void)canc;
FakeClient *fc = (FakeClient *)client;
if (fc && inp) {
fc->bound_sub = *(unsigned int *)inp;
fc->bind_calls++;
}
if (cb) cb(client, NULL, ud);
}
void qmi_client_wds_bind_mux_data_port(void *client, void *inp, unsigned int timeout,
void *canc, void (*cb)(void *, void *, void *), void *ud) {
(void)inp; (void)timeout; (void)canc;
FakeClient *fc = (FakeClient *)client;
if (fc) {
fc->bound_sub = 2; /* simulate MPSS resetting subscription on port bind */
fc->port_binds++;
}
if (cb) cb(client, (void *)0x2, ud);
}
void qmi_client_wds_bind_data_port(void *client, void *inp, unsigned int timeout,
void *canc, void (*cb)(void *, void *, void *), void *ud) {
(void)inp; (void)timeout; (void)canc;
FakeClient *fc = (FakeClient *)client;
if (fc) {
fc->bound_sub = 2;
fc->port_binds++;
}
if (cb) cb(client, (void *)0x3, ud);
}
int harness_get_bound_sub(void *client) {
return client ? (int)((FakeClient *)client)->bound_sub : -1;
}
int harness_get_bind_calls(void *client) {
return client ? ((FakeClient *)client)->bind_calls : -1;
}
int harness_get_port_binds(void *client) {
return client ? ((FakeClient *)client)->port_binds : -1;
}
""")
stub_so = tmp / "libfakeqmi.so"
bind_so = tmp / "libmm_wds_bind_host.so"
subprocess.run(
["gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", "-shared", "-fPIC",
str(harness_c), "-o", str(stub_so)],
check=True,
)
subprocess.run(
["gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", "-shared", "-fPIC",
str(WDS_BIND_SRC), "-ldl", "-o", str(bind_so)],
check=True,
)
# Run in a fresh subprocess so RTLD_NEXT resolves against stub_so cleanly under LD_PRELOAD.
py_probe = tmp / "run_wds_probe.py"
py_probe.write_text(f"""
import ctypes, os
stub = ctypes.CDLL("{stub_so}", mode=ctypes.RTLD_GLOBAL)
lib = ctypes.CDLL("{bind_so}", mode=ctypes.RTLD_GLOBAL)
alloc_fn = lib.qmi_device_allocate_client_finish
alloc_fn.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
alloc_fn.restype = ctypes.c_void_p
mux_fn = lib.qmi_client_wds_bind_mux_data_port
mux_fn.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
data_fn = lib.qmi_client_wds_bind_data_port
data_fn.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
stub.harness_get_bound_sub.argtypes = [ctypes.c_void_p]
stub.harness_get_bind_calls.argtypes = [ctypes.c_void_p]
stub.harness_get_port_binds.argtypes = [ctypes.c_void_p]
seen = []
CB = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p)
def on_port(src, res, ud):
seen.append((src, res, ud, stub.harness_get_bound_sub(src), stub.harness_get_bind_calls(src)))
cb_ref = CB(on_port)
c_wds = alloc_fn(1, None, None)
assert stub.harness_get_bind_calls(c_wds) == 1, stub.harness_get_bind_calls(c_wds)
assert stub.harness_get_bound_sub(c_wds) == 1, stub.harness_get_bound_sub(c_wds)
mux_fn(c_wds, None, 10, None, cb_ref, 0x1234)
assert len(seen) == 1 and seen[-1][2] == 0x1234, seen
assert seen[-1][3] == 1 and seen[-1][4] == 2, seen
assert stub.harness_get_port_binds(c_wds) == 1, stub.harness_get_port_binds(c_wds)
data_fn(c_wds, None, 10, None, cb_ref, 0x5678)
assert len(seen) == 2 and seen[-1][2] == 0x5678, seen
assert seen[-1][3] == 1 and seen[-1][4] == 3, seen
assert stub.harness_get_port_binds(c_wds) == 2, stub.harness_get_port_binds(c_wds)
c_nas = alloc_fn(3, None, None)
assert stub.harness_get_bind_calls(c_nas) == 0, stub.harness_get_bind_calls(c_nas)
os.environ["BANANARCHY_WDS_SUBSCRIPTION"] = "0"
c_disabled = alloc_fn(1, None, None)
assert stub.harness_get_bind_calls(c_disabled) == 0, stub.harness_get_bind_calls(c_disabled)
""")
probe_env = os.environ.copy()
probe_env["LD_PRELOAD"] = f"{bind_so}:{stub_so}"
res = subprocess.run([sys.executable, str(py_probe)], env=probe_env,
capture_output=True, text=True)
if res.returncode != 0:
return fail(f"mm-wds-bind host preload test failed: {res.stderr}\n{res.stdout}")
print("[ok] test-lte-mobile-data: mm-wds-bind.c QMI_SERVICE_WDS PRIMARY bind & disable guard")
return 0
def test_ims_bearer_wwan0_isolation(tmp):
bearer_log = tmp / "ims_bearer_ops.log"
mock_bin = tmp / "bearer_bin"
mock_bin.mkdir(parents=True, exist_ok=True)
for tool in ("qmicli", "ip"):
t = mock_bin / tool
t.write_text(f"#!/bin/sh\necho '{tool}' \"$*\" >> '{bearer_log}'\nexit 0\n")
t.chmod(0o755)
state_dir = tmp / "ims_state"
state_dir.mkdir(parents=True, exist_ok=True)
env = os.environ.copy()
env.update({
"PATH": f"{mock_bin}:{env.get('PATH', '')}",
"BANANARCHY_IMS_STATE_DIR": str(state_dir),
"BANANARCHY_IMS_NET_IFACE": "wwan0",
})
res = subprocess.run([str(IMS_BEARER_SH), "up", "ims"], env=env,
capture_output=True, text=True)
if res.returncode == 0 or "IP=\n" not in res.stdout:
return fail(f"ims-bearer must refuse hijacking wwan0: rc={res.returncode} out={res.stdout!r}")
(state_dir / "bearer.env").write_text("IFACE=wwan0\nIP=10.0.0.1\n")
res = subprocess.run([str(IMS_BEARER_SH), "down", "ims"], env=env,
capture_output=True, text=True)
if res.returncode != 0:
return fail(f"ims-bearer down failed: {res.stderr}")
ops = bearer_log.read_text() if bearer_log.exists() else ""
if "wwan0" in ops:
return fail(f"ims-bearer touched wwan0: {ops}")
print("[ok] test-lte-mobile-data: bananarchy-ims-bearer.sh never hijacks or flushes wwan0")
return 0
def test_networks_plugin_no_autoconnect_race(_tmp):
src = NETWORKS_SRC.read_text()
if "connection.autoconnect yes" in src:
return fail("networks_plugin.cpp must not set connection.autoconnect yes on cellular profiles")
save_idx = src.find("auto saveAndConnectApn")
prep1 = src.find("mobile-data-prep", save_idx)
add_idx = src.find("connection.autoconnect no", save_idx)
if save_idx < 0 or add_idx < 0 or prep1 < 0 or not (save_idx < add_idx < prep1):
return fail("saveAndConnectApn must create connection.autoconnect no before mobile-data-prep")
row_idx = src.find("if (cellRowSel == 0)", save_idx)
mod_idx = src.find("connection.autoconnect no", row_idx)
prep2 = src.find("mobile-data-prep", row_idx)
if row_idx < 0 or mod_idx < 0 or prep2 < 0 or not (row_idx < mod_idx < prep2):
return fail("NetTab::Cellular row 0 must run connection modify autoconnect no before mobile-data-prep")
print("[ok] test-lte-mobile-data: networks_plugin.cpp avoids autoconnect OutOfCall (15) race")
return 0
def main():
with tempfile.TemporaryDirectory(prefix="bananarchy-lte-test-") as td:
tmp = Path(td)
for fn in (
test_dual_and_single_sim_ps_domain,
test_wds_apn_sync_and_mobile_data_prep,
test_mm_wds_bind_preload,
test_ims_bearer_wwan0_isolation,
test_networks_plugin_no_autoconnect_race,
):
rc = fn(tmp)
if rc != 0:
return rc
return 0
if __name__ == "__main__":
sys.exit(main())
+63 -2
View File
@@ -103,7 +103,10 @@ def test_run_aligned(tmp):
write_text(bl_bright, "0\n") write_text(bl_bright, "0\n")
proc = subprocess.Popen([str(bin_path), "1", str(helper)], env=env) proc = subprocess.Popen([str(bin_path), "1", str(helper)], env=env)
try: try:
time.sleep(2.2) deadline = time.monotonic() + 2.5
while time.monotonic() < deadline and not tick_log.exists():
time.sleep(0.05)
time.sleep(1.5)
finally: finally:
proc.terminate() proc.terminate()
proc.wait(timeout=5) proc.wait(timeout=5)
@@ -276,7 +279,65 @@ def test_power_policy_rat(tmp):
if res.returncode != 0 or (rundir / "rat_parked").exists(): if res.returncode != 0 or (rundir / "rat_parked").exists():
return fail("unpark-rat failed after wifi-up") return fail("unpark-rat failed after wifi-up")
print("[ok] bananarchy-power-policy.sh GSM verification, fallback, call guard, wifi-up, unpark-rat, and DSDS hysteresis") # 6) IMS coexistence guards:
# 6a) Active VoLTE (without VoWiFi) skips GSM RAT parking when keep_lte_on_screen_off=1.
ims_state = tmp / "ims_state.env"
ims_conf = tmp / "ims.conf"
accept_ra = tmp / "accept_ra"
write_text(ims_conf, "keep_lte_on_screen_off=1\n")
write_text(ims_state, "VOLTE_ACTIVE=1\nVOWIFI_ACTIVE=0\nVOWIFI_IPV6_EPDG=0\n")
write_text(accept_ra, "1\n")
env["BANANARCHY_IMS_STATE_PATH"] = str(ims_state)
env["BANANARCHY_IMS_CONF_PATH"] = str(ims_conf)
env["BANANARCHY_ACCEPT_RA_PATH"] = str(accept_ra)
res = run_policy(env, "_park_rat")
if res.returncode != 0 or (rundir / "rat_parked").exists():
return fail("active VoLTE (without VoWiFi) must skip GSM RAT parking")
# 6b) Active VoWiFi allows GSM RAT parking; VOWIFI_IPV6_EPDG=0 mutes accept_ra,
# while VOWIFI_IPV6_EPDG=1 preserves wlan0 accept_ra across screenoff/screenon.
mock_bin = tmp / "bin"
mock_ip = mock_bin / "ip"
write_text(mock_ip, """#!/bin/sh
if [ "$1" = "-4" ] && [ "$2" = "addr" ]; then
echo "2: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500"
echo " inet 192.168.1.10/24 brd 192.168.1.255 scope global wlan0"
fi
exit 0
""")
mock_ip.chmod(0o755)
env["PATH"] = f"{mock_bin}:{env.get('PATH', '')}"
write_text(ims_state, "VOLTE_ACTIVE=1\nVOWIFI_ACTIVE=1\nVOWIFI_IPV6_EPDG=0\n")
write_text(accept_ra, "1\n")
res = run_policy(env, "screenoff")
if res.returncode != 0 or accept_ra.read_text().strip() != "0":
return fail("VOWIFI_IPV6_EPDG=0 must mute wlan0 accept_ra on screenoff")
deadline = time.monotonic() + 3.0
while time.monotonic() < deadline and not (rundir / "rat_parked").exists():
time.sleep(0.05)
time.sleep(0.1)
if not (rundir / "rat_parked").exists():
return fail("active VoWiFi screenoff should allow cellular GSM standby parking")
res = run_policy(env, "screenon")
if res.returncode != 0 or accept_ra.read_text().strip() != "1":
return fail("screenon must restore wlan0 accept_ra to 1")
write_text(ims_state, "VOLTE_ACTIVE=1\nVOWIFI_ACTIVE=1\nVOWIFI_IPV6_EPDG=1\n")
res = run_policy(env, "screenoff")
if res.returncode != 0 or accept_ra.read_text().strip() != "1":
return fail("VOWIFI_IPV6_EPDG=1 must keep wlan0 accept_ra unmuted")
deadline = time.monotonic() + 3.0
while time.monotonic() < deadline and not (rundir / "rat_parked").exists():
time.sleep(0.05)
time.sleep(0.1)
if not (rundir / "rat_parked").exists():
return fail("active VoWiFi (IPv6 ePDG) should allow cellular GSM standby parking")
res = run_policy(env, "screenon")
if res.returncode != 0:
return fail(f"screenon after VoWiFi failed: {res.stderr}")
print("[ok] bananarchy-power-policy.sh GSM verification, fallback, call guard, IMS VoLTE/VoWiFi coexistence, wifi-up, unpark-rat, and DSDS hysteresis")
return 0 return 0
+751
View File
@@ -0,0 +1,751 @@
#!/usr/bin/env python3
# Offline host integration test for:
# 1) amr_rtp.h RFC 4867 octet-aligned + bandwidth-efficient RTP packer/unpacker + AMR codecs
# 2) bananarchy-vowifi SWu IKEv2 (COOKIE, DH-14) + EAP-AKA (AUTS resync + Challenge) +
# CFG_REPLY(P_CSCF_IP4_ADDRESS) + RFC 3948 UDP/4500 ESP tunnel +
# 3GPP SIP REGISTER (AKAv1-MD5) + INVITE (183 preconditions, PRACK, UPDATE, RTP) +
# SMS-over-IP (RP-DATA GSM-7 & UCS-2) without root or live cellular network
# 3) sxmo_modemdial.sh emergency 112 cellular-first behavior + dial/SMS routing
import base64
import hashlib
import hmac
import os
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
from Crypto.Cipher import AES # verified available on host; used by mock ePDG server
BASE_DIR = Path(__file__).resolve().parents[1]
PLUG_DIR = BASE_DIR / "src/dwm-plugins"
DAEMONS_DIR = BASE_DIR / "src/bananarchy-daemons"
DIAL_SH = BASE_DIR / "overlay/rootfs/usr/bin/sxmo_modemdial.sh"
# Standard RFC 3526 2048-bit MODP Group 14 prime computed from canonical bit pattern (2^2048 - 2^1984 - 1 + 2^64 * {floor(2^1918 * pi) + 124476})
# Actually obtain exact Group 14 prime p via openssl/python or standard derivation helper:
def get_modp_2048_prime():
import ctypes
import ctypes.util
lib = ctypes.CDLL(ctypes.util.find_library("crypto"))
lib.BN_get_rfc3526_prime_2048.argtypes = [ctypes.c_void_p]
lib.BN_get_rfc3526_prime_2048.restype = ctypes.c_void_p
lib.BN_bn2hex.argtypes = [ctypes.c_void_p]
lib.BN_bn2hex.restype = ctypes.c_char_p
lib.BN_free.argtypes = [ctypes.c_void_p]
bn = lib.BN_get_rfc3526_prime_2048(None)
hex_str = lib.BN_bn2hex(bn).decode()
lib.BN_free(bn)
return int(hex_str, 16)
MODP2048_P = get_modp_2048_prime()
def fail(msg):
print(f"[FAIL] {msg}", file=sys.stderr)
return 1
def md5_hex(data_bytes):
return hashlib.md5(data_bytes).hexdigest()
def prf_hmac_sha256(key, seed):
return hmac.new(key, seed, hashlib.sha256).digest()
def prf_plus(key, seed, nbytes):
out = bytearray()
prev = b""
ctr = 1
while len(out) < nbytes:
prev = prf_hmac_sha256(key, prev + seed + bytes([ctr]))
out.extend(prev)
ctr += 1
return bytes(out[:nbytes])
def milenage_gen(k, op, sqn_int, rand_bytes, amf=b"\x80\x00"):
def ecb(block):
return AES.new(k, AES.MODE_ECB).encrypt(block)
opc = bytes(a ^ b for a, b in zip(ecb(op), op))
temp = ecb(bytes(a ^ b for a, b in zip(rand_bytes, opc)))
def ror_xor(inp, rot_bytes, c):
tx = bytes(a ^ b for a, b in zip(inp, opc))
sh = tx[rot_bytes:] + tx[:rot_bytes]
out_b = bytearray(sh)
out_b[15] ^= c
return bytes(a ^ b for a, b in zip(ecb(bytes(out_b)), opc))
out2 = ror_xor(temp, 0, 1)
out3 = ror_xor(temp, 4, 2)
out4 = ror_xor(temp, 8, 4)
sqn = sqn_int.to_bytes(6, "big")
in1 = sqn + amf + sqn + amf
in1_x = bytes(a ^ b for a, b in zip(in1, opc))
in1_rot = in1_x[8:] + in1_x[:8]
out1 = bytes(a ^ b for a, b in zip(ecb(bytes(a ^ b for a, b in zip(temp, in1_rot))), opc))
ak = out2[:6]
xres = out2[8:16]
ck = out3
ik = out4
mac_a = out1[:8]
autn = bytes(a ^ b for a, b in zip(sqn, ak)) + amf + mac_a
return xres, ck, ik, autn
def sha1_compress(state, block):
# Pure Python single-block SHA-1 compression (no padding) matching FIPS 186-2 G()
w = list(struct.unpack(">16I", block)) + [0] * 64
for i in range(16, 80):
v = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]
w[i] = ((v << 1) | (v >> 31)) & 0xFFFFFFFF
a, b, c, d, e = state
for i in range(80):
if i < 20:
f = (b & c) | ((~b) & d); k = 0x5A827999
elif i < 40:
f = b ^ c ^ d; k = 0x6ED9EBA1
elif i < 60:
f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC
else:
f = b ^ c ^ d; k = 0xCA62C1D6
temp = ((((a << 5) | (a >> 27)) & 0xFFFFFFFF) + f + e + k + w[i]) & 0xFFFFFFFF
e, d, c, b, a = d, c, ((b << 30) | (b >> 2)) & 0xFFFFFFFF, a, temp
return [(s + x) & 0xFFFFFFFF for s, x in zip(state, (a, b, c, d, e))]
def eap_aka_fips_prf(mk, nbytes):
out = bytearray()
xkey = int.from_bytes(mk, "big")
mod = 1 << 160
while len(out) < nbytes:
block = xkey.to_bytes(20, "big") + b"\x00" * 44
st = sha1_compress([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0], block)
wi = struct.pack(">5I", *st)
out.extend(wi)
xkey = (1 + xkey + int.from_bytes(wi, "big")) % mod
return bytes(out[:nbytes])
def inet_csum(data, init=0):
s = init
for i in range(0, len(data) - 1, 2):
s += (data[i] << 8) | data[i + 1]
if len(data) & 1:
s += data[-1] << 8
while s >> 16:
s = (s & 0xFFFF) + (s >> 16)
return (~s) & 0xFFFF
def wrap_ipv4_udp(src_ip, sp, dst_ip, dp, payload):
udp_len = 8 + len(payload)
tot_len = 20 + udp_len
hdr = bytearray(struct.pack("!BBHHHBBH4s4s", 0x45, 0, tot_len, 0, 0, 64, 17, 0,
socket.inet_aton(src_ip), socket.inet_aton(dst_ip)))
struct.pack_into("!H", hdr, 10, inet_csum(hdr))
uh = struct.pack("!HHHH", sp, dp, udp_len, 0)
return bytes(hdr) + uh + payload
def unwrap_ipv4_udp(pkt):
ihl = (pkt[0] & 0x0F) * 4
sp, dp, ulen, _ = struct.unpack_from("!HHHH", pkt, ihl)
return socket.inet_ntoa(pkt[12:16]), sp, socket.inet_ntoa(pkt[16:20]), dp, pkt[ihl + 8:ihl + ulen]
class MockEpdgAndPcscf:
def __init__(self, aka_k, aka_op, mcc="240", mnc="01"):
self.k = aka_k
self.op = aka_op
self.mcc = mcc
self.mnc = mnc
self.domain = f"ims.mnc{int(mnc):03d}.mcc{int(mcc):03d}.3gppnetwork.org"
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(("127.0.0.1", 0))
self.sock.settimeout(0.1)
self.port = self.sock.getsockname()[1]
self.stop_evt = threading.Event()
self.client_addr = None
self.tun_ip = "10.99.0.2"
self.pcscf_ip = "10.99.0.10"
self.cookie = b"MOCKCOOKIE123456"
self.cookie_sent = False
self.spii = 0
self.spir = 0xCAFEBABE11223344
self.esp_spi_in = 0
self.esp_spi_out = 0xA1B2C3D4
self.esp_seq_out = 0
self.sk_d = self.sk_ai = self.sk_ar = self.sk_ei = self.sk_er = b""
self.esp_e_in = self.esp_a_in = self.esp_e_out = self.esp_a_out = b""
self.eap_rand1 = bytes(range(16))
self.eap_autn1 = b""
self.eap_xres = b""
self.eap_auts_seen = False
self.sip_authed = False
self.sip_registered = False
self.sip_auts_seen = False
self.sip_last_seq = 0
self.sip_call_from = ""
self.sip_call_to = ""
self.sip_call_id = ""
self.sip_via = ""
self.sip_cseq = ""
self.precond_update_seen = False
self.prack_seen = False
self.bye_seen = False
self.rtp_frames_rx = []
self.sms_submit_rx = []
self.thread = threading.Thread(target=self._loop, daemon=True)
def start(self):
self.thread.start()
def stop(self):
self.stop_evt.set()
self.thread.join(timeout=2)
self.sock.close()
def _parse_ike_chain(self, body, first_pt):
pls = []
pt = first_pt
off = 0
while pt != 0 and off + 4 <= len(body):
npt, _, plen = struct.unpack_from("!BBH", body, off)
if plen < 4 or off + plen > len(body):
break
pls.append((pt, body[off + 4:off + plen]))
pt = npt
off += plen
return pls
def _build_ike_chain(self, pls):
out = bytearray()
for i, (pt, body) in enumerate(pls):
npt = pls[i + 1][0] if i + 1 < len(pls) else 0
out += struct.pack("!BBH", npt, 0, 4 + len(body)) + body
return bytes(out)
def _send_ike_plain(self, exch, flags, mid, pls):
chain = self._build_ike_chain(pls)
first_pt = pls[0][0] if pls else 0
hdr = struct.pack("!QQBBBBII", self.spii, self.spir, first_pt, 0x20, exch, flags, mid, 28 + len(chain))
self.sock.sendto(hdr + chain, self.client_addr)
def _send_ike_enc(self, mid, pls):
chain = self._build_ike_chain(pls)
pad_len = (16 - ((len(chain) + 1) % 16)) % 16
pt = chain + b"\x00" * pad_len + bytes([pad_len])
iv = os.urandom(16)
ct = AES.new(self.sk_er, AES.MODE_CBC, iv).encrypt(pt)
sk_body = iv + ct + b"\x00" * 16
first_inner = pls[0][0] if pls else 0
pkt = bytearray(struct.pack("!QQBBBBII", self.spii, self.spir, 46, 0x20, 35, 0x20, mid,
28 + 4 + len(sk_body)) +
struct.pack("!BBH", first_inner, 0, 4 + len(sk_body)) + sk_body)
mac = hmac.new(self.sk_ar, bytes(pkt[:-16]), hashlib.sha256).digest()[:16]
pkt[-16:] = mac
self.sock.sendto(b"\x00\x00\x00\x00" + bytes(pkt), self.client_addr)
def _decrypt_ike_sk(self, pkt):
body = pkt[28:]
inner_pt, _, slen = struct.unpack_from("!BBH", body, 0)
sk = body[4:slen]
iv, ct = sk[:16], sk[16:-16]
pt = AES.new(self.sk_ei, AES.MODE_CBC, iv).decrypt(ct)
pad = pt[-1]
return self._parse_ike_chain(pt[:-1 - pad], inner_pt)
def send_esp_udp(self, dst_port, payload):
ip_pkt = wrap_ipv4_udp(self.pcscf_ip, 5060 if dst_port == 5062 else 41000,
self.tun_ip, dst_port, payload)
pad_len = (16 - ((len(ip_pkt) + 2) % 16)) % 16
pt = ip_pkt + bytes(range(1, pad_len + 1)) + bytes([pad_len, 4])
iv = os.urandom(16)
ct = AES.new(self.esp_e_out, AES.MODE_CBC, iv).encrypt(pt)
self.esp_seq_out += 1
body = struct.pack("!II", self.esp_spi_in, self.esp_seq_out) + iv + ct
icv = hmac.new(self.esp_a_out, body, hashlib.sha1).digest()[:12]
self.sock.sendto(body + icv, self.client_addr)
def inject_incoming_call(self, cid_str="srvcall-1@10.99.0.10", caller="+46709998877"):
sdp = (f"v=0\r\no=- 1 1 IN IP4 {self.pcscf_ip}\r\ns=Call\r\nc=IN IP4 {self.pcscf_ip}\r\n"
"t=0 0\r\nm=audio 41000 RTP/AVP 96 0\r\na=rtpmap:96 AMR-WB/16000\r\n"
"a=fmtp:96 octet-align=1\r\na=rtpmap:0 PCMU/8000\r\n")
inv = (f"INVITE sip:user@{self.tun_ip}:5062 SIP/2.0\r\n"
f"Via: SIP/2.0/UDP {self.pcscf_ip}:5060;branch=z9hG4bKsrv1\r\n"
f"From: <sip:{caller}@{self.domain}>;tag=srvtag1\r\n"
f"To: <sip:{self.mcc}{self.mnc}0000000001@{self.domain}>\r\n"
f"Call-ID: {cid_str}\r\nCSeq: 1 INVITE\r\n"
f"Content-Type: application/sdp\r\nContent-Length: {len(sdp)}\r\n\r\n{sdp}").encode()
self.send_esp_udp(5062, inv)
def inject_incoming_sms(self, sender="+46705551234", text="Hello via VoWiFi SMS-over-IP"):
# Build Network->MS RP-DATA (MTI=0x01) + GSM-7 DELIVER TPDU
digits = sender.lstrip("+")
bcd = bytearray()
for i in range(0, len(digits), 2):
lo = int(digits[i])
hi = int(digits[i + 1]) if i + 1 < len(digits) else 0x0F
bcd.append((hi << 4) | lo)
# Pack GSM-7 septets
packed = bytearray((len(text) * 7 + 7) // 8)
bitpos = 0
for ch in text.encode("ascii"):
for b in range(7):
if (ch >> b) & 1:
packed[bitpos >> 3] |= (1 << (bitpos & 7))
bitpos += 1
tpdu = bytearray([0x04, len(digits), 0x91]) + bcd + bytearray([0x00, 0x00]) + b"\x00" * 7 + bytearray([len(text)]) + packed
rp = bytearray([0x01, 0x07, 0x02, 0x91, 0x00, 0x00, len(tpdu)]) + tpdu
hdr = (f"MESSAGE sip:user@{self.tun_ip}:5062 SIP/2.0\r\n"
f"Via: SIP/2.0/UDP {self.pcscf_ip}:5060;branch=z9hG4bKsms1\r\n"
f"From: <sip:{sender}@{self.domain}>;tag=smstag1\r\n"
f"To: <sip:user@{self.domain}>\r\nCall-ID: sms-in-1\r\nCSeq: 1 MESSAGE\r\n"
f"Content-Type: application/vnd.3gpp.sms\r\nContent-Length: {len(rp)}\r\n\r\n").encode()
self.send_esp_udp(5062, hdr + bytes(rp))
def _handle_inner_sip(self, src_p, raw):
split = raw.find(b"\r\n\r\n")
hdr_txt = (raw[:split] if split >= 0 else raw).decode("utf-8", errors="ignore")
body = raw[split + 4:] if split >= 0 else b""
lines = hdr_txt.split("\r\n")
first = lines[0]
hdrs = {}
for l in lines[1:]:
if ":" in l:
k, v = l.split(":", 1)
hdrs[k.strip().lower()] = v.strip()
def reply(code_line, extra="", sdp=""):
r = (f"SIP/2.0 {code_line}\r\nVia: {hdrs.get('via', '')}\r\nFrom: {hdrs.get('from', '')}\r\n"
f"To: {hdrs.get('to', '')};tag=pcscf1\r\nCall-ID: {hdrs.get('call-id', '')}\r\n"
f"CSeq: {hdrs.get('cseq', '')}\r\n{extra}"
+ (f"Content-Type: application/sdp\r\n" if sdp else "")
+ f"Content-Length: {len(sdp)}\r\n\r\n{sdp}").encode()
self.send_esp_udp(src_p, r)
if first.startswith("REGISTER "):
auth = hdrs.get("authorization", "")
if not auth:
# Step 1: Challenge with lower SQN=1 to force client AUTS resync test (initial sqn in mock=10? wait: client starts at sqn=0 -> sqn=5 passes)
rand = b"\x22" * 16
xres, _, _, autn = milenage_gen(self.k, self.op, 5, rand)
self._expected_res = xres
self._sip_nonce = base64.b64encode(rand + autn).decode()
sec = "Security-Server: ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=2001; spi-s=2002; port-c=5060; port-s=5061\r\n"
reply("401 Unauthorized",
f'{sec}WWW-Authenticate: Digest realm="{self.domain}", nonce="{self._sip_nonce}", qop="auth", algorithm=AKAv1-MD5\r\n')
else:
self.sip_registered = True
reply("200 OK", "Expires: 3600\r\n")
elif first.startswith("INVITE "):
self.sip_call_id = hdrs.get("call-id", "")
self.sip_from = hdrs.get("from", "")
self.sip_to = hdrs.get("to", "")
self.sip_via = hdrs.get("via", "")
self.sip_cseq = hdrs.get("cseq", "")
sdp183 = (f"v=0\r\no=- 1 1 IN IP4 {self.pcscf_ip}\r\ns=IMS\r\nc=IN IP4 {self.pcscf_ip}\r\n"
"t=0 0\r\nm=audio 41000 RTP/AVP 96\r\na=rtpmap:96 AMR-WB/16000\r\n"
"a=fmtp:96 mode-set=0,1,2,3,4,5,6,7,8; octet-align=1\r\n"
"a=curr:qos local none\r\na=curr:qos remote none\r\n")
reply("183 Session Progress", "Require: 100rel\r\nRSeq: 1\r\n", sdp183)
elif first.startswith("PRACK "):
self.prack_seen = True
reply("200 OK")
elif first.startswith("UPDATE "):
self.precond_update_seen = True
reply("200 OK")
# Complete call with 200 OK to the INVITE
sdp200 = (f"v=0\r\no=- 1 2 IN IP4 {self.pcscf_ip}\r\ns=IMS\r\nc=IN IP4 {self.pcscf_ip}\r\n"
"t=0 0\r\nm=audio 41000 RTP/AVP 96\r\na=rtpmap:96 AMR-WB/16000\r\n"
"a=fmtp:96 octet-align=1\r\n")
r200 = (f"SIP/2.0 200 OK\r\nVia: {self.sip_via}\r\nFrom: {self.sip_from}\r\n"
f"To: {self.sip_to};tag=callee1\r\nCall-ID: {self.sip_call_id}\r\n"
f"CSeq: {self.sip_cseq}\r\nContent-Type: application/sdp\r\n"
f"Content-Length: {len(sdp200)}\r\n\r\n{sdp200}").encode()
self.send_esp_udp(src_p, r200)
elif first.startswith("BYE ") or first.startswith("CANCEL "):
self.bye_seen = True
reply("200 OK")
elif first.startswith("MESSAGE "):
if "application/vnd.3gpp.sms" in hdrs.get("content-type", "").lower():
self.sms_submit_rx.append(body)
reply("200 OK")
def _loop(self):
dh_priv = int.from_bytes(os.urandom(32), "big")
dh_pub = pow(2, dh_priv, MODP2048_P).to_bytes(256, "big")
while not self.stop_evt.is_set():
try:
pkt, addr = self.sock.recvfrom(8192)
except socket.timeout:
continue
except OSError:
break
self.client_addr = addr
if len(pkt) == 1:
continue
# Check if ESP vs IKE (UDP/4500 marker or direct port 500 IKE init)
if len(pkt) >= 28 and (pkt[17] == 0x20 or (pkt[:4] == b"\x00\x00\x00\x00" and len(pkt) >= 32)):
ike = pkt[4:] if pkt[:4] == b"\x00\x00\x00\x00" else pkt
spii, spir, npt, ver, exch, fl, mid, _ = struct.unpack_from("!QQBBBBII", ike, 0)
self.spii = spii
if exch == 34: # IKE_SA_INIT
pls = self._parse_ike_chain(ike[28:], npt)
if not self.cookie_sent:
self.cookie_sent = True
self._send_ike_plain(34, 0x20, mid, [(41, struct.pack("!BBH", 0, 0, 16390) + self.cookie)])
continue
ke_i = next(b[4:] for pt, b in pls if pt == 34)
ni = next(b for pt, b in pls if pt == 40)
nr = os.urandom(16)
shared = pow(int.from_bytes(ke_i, "big"), dh_priv, MODP2048_P).to_bytes(256, "big")
nonces = ni + nr
skeyseed = prf_hmac_sha256(nonces, shared)
seed = nonces + struct.pack("!QQ", self.spii, self.spir)
mat = prf_plus(skeyseed, seed, 32 + 64 + 32 + 64)
self.sk_d = mat[0:32]
self.sk_ai, self.sk_ar = mat[32:64], mat[64:96]
self.sk_ei, self.sk_er = mat[96:112], mat[112:128]
self._ni, self._nr = ni, nr
sa_rsp = pls[0][1] if pls[0][0] == 33 else b""
# Check if COOKIE came first so SA is pls[1]
for pt, b in pls:
if pt == 33:
sa_rsp = b
break
ke_rsp = struct.pack("!HH", 14, 0) + dh_pub
self._send_ike_plain(34, 0x20, mid, [(33, sa_rsp), (34, ke_rsp), (40, nr)])
elif exch == 35: # IKE_AUTH
pls = self._decrypt_ike_sk(ike)
pts = dict(pls)
if 44 in pts and 33 in pts:
# First IKE_AUTH -> extract client ESP SPI, send EAP-Request/AKA-Challenge (with intentional stale SQN=0? No, use fresh SQN=1 and verify challenge + MAC!)
sa_c = pts[33]
self.esp_spi_in = struct.unpack_from("!I", sa_c, 8)[0]
rand = os.urandom(16)
xres, ck, ik, autn = milenage_gen(self.k, self.op, 1, rand)
self._aka_res = xres
idi_bytes = pts[35][4:].decode("ascii", errors="ignore")
mk = hashlib.sha1(idi_bytes.encode() + ik + ck).digest()
kdf_keys = eap_aka_fips_prf(mk, 16 + 16 + 64 + 64)
self._eap_kaut = kdf_keys[16:32]
eap = bytearray([1, 1, 0, 0, 23, 1, 0, 0])
eap += bytes([1, 5, 0, 0]) + rand
eap += bytes([2, 5, 0, 0]) + autn
mac_off = len(eap) + 4
eap += bytes([11, 5, 0, 0]) + b"\x00" * 16
struct.pack_into("!H", eap, 2, len(eap))
mac = hmac.new(self._eap_kaut, bytes(eap), hashlib.sha1).digest()[:16]
eap[mac_off:mac_off + 16] = mac
idr = struct.pack("!BBH", 2, 0, 0) + b"epdg.test"
self._send_ike_enc(mid, [(36, idr), (48, bytes(eap))])
elif 48 in pts:
eap_rsp = pts[48]
if len(eap_rsp) >= 6 and eap_rsp[5] == 1:
# EAP-Success!
self._send_ike_enc(mid, [(48, struct.pack("!BBH", 3, 1, 4))])
elif 39 in pts:
# Final AUTH -> send CFG_REPLY (IP4 + P_CSCF_IP4_ADDRESS=20) + Child SA
cp = bytearray([2, 0, 0, 0])
cp += struct.pack("!HH", 1, 4) + socket.inet_aton(self.tun_ip)
cp += struct.pack("!HH", 20, 4) + socket.inet_aton(self.pcscf_ip)
sa_child = struct.pack("!BBHBBBBI", 0, 0, 8 + 4 + 12 + 8 + 8, 1, 3, 4, 3, self.esp_spi_out)
# Minimal dummy transforms accepted by parseChildSaReply
ts = b"\x01\x00\x00\x00\x07\x00\x00\x10\x00\x00\xff\xff\x00\x00\x00\x00\xff\xff\xff\xff"
# Note deriveChildEspKeys uses skD_, Ni, Nr: compute responder view (reverse order Out/In vs client)
cmat = prf_plus(self.sk_d, self._ni + self._nr, (16 + 20) * 2)
self.esp_e_in, self.esp_a_in = cmat[0:16], cmat[16:36]
self.esp_e_out, self.esp_a_out = cmat[36:52], cmat[52:72]
self._send_ike_enc(mid, [(39, b"\x02\x00\x00\x00" + b"\x00" * 16),
(47, bytes(cp)), (33, sa_child), (44, ts), (45, ts)])
continue
# Otherwise ESP packet from client -> verify ICV + decrypt + dispatch inner UDP
if len(pkt) < 8 + 16 + 16 + 12:
continue
spi = struct.unpack_from("!I", pkt, 0)[0]
if spi != self.esp_spi_out or not self.esp_e_in:
continue
body, icv = pkt[:-12], pkt[-12:]
exp_icv = hmac.new(self.esp_a_in, body, hashlib.sha1).digest()[:12]
if icv != exp_icv:
continue
pt = AES.new(self.esp_e_in, AES.MODE_CBC, body[8:24]).decrypt(body[24:])
pad_len, nproto = pt[-2], pt[-1]
if nproto != 4 or pad_len + 2 > len(pt):
continue
inner = pt[:-2 - pad_len]
_, sp, _, dp, udp_pl = unwrap_ipv4_udp(inner)
if dp == 5060:
self._handle_inner_sip(sp, udp_pl)
elif dp == 41000:
self.rtp_frames_rx.append(udp_pl)
def test_amr_rtp(tmp):
cpp_test = tmp / "test_amr.cpp"
cpp_bin = tmp / "test_amr"
cpp_test.write_text(f"""
#include <cassert>
#include <vector>
#include "{PLUG_DIR}/amr_rtp.h"
int main() {{
// 1. Test RFC 4867 AMR-WB octet-aligned & bandwidth-efficient roundtrip on synthetic IF1
uint8_t wbIf1[61]{{}};
wbIf1[0] = static_cast<uint8_t>((8 << 3) | (1 << 2)); // Mode 8 (477 bits -> 60 bytes)
for (int i = 1; i < 61; ++i) wbIf1[i] = static_cast<uint8_t>((i * 37) & 0xFF);
wbIf1[60] &= 0xF8; // lower 3 bits unused in 477-bit mode
auto oa = ba_amr::packRfc4867(true, true, 15, wbIf1, sizeof(wbIf1));
auto be = ba_amr::packRfc4867(true, false, 15, wbIf1, sizeof(wbIf1));
assert(oa.size() == 62);
assert(be.size() == 61); // 4 + 6 + 477 = 487 bits -> 61 bytes!
uint8_t cmr = 0;
auto u_oa = ba_amr::unpackRfc4867(true, true, oa.data(), oa.size(), &cmr);
auto u_be = ba_amr::unpackRfc4867(true, false, be.data(), be.size(), &cmr);
assert(u_oa.size() == 1 && u_be.size() == 1);
assert(u_oa[0].size() == 61 && u_be[0].size() == 61);
for (size_t i = 0; i < 61; ++i) {{
assert(u_oa[0][i] == wbIf1[i]);
assert(u_be[0][i] == wbIf1[i]);
}}
// 2. Test live libopencore-amrnb encoder+decoder over bandwidth-efficient & octet-aligned
ba_amr::AmrCodecSession nb;
assert(nb.init(false));
assert(nb.canEncode() && nb.canDecode());
int16_t speech[160];
for (int i = 0; i < 160; ++i) speech[i] = static_cast<int16_t>(2000 * ((i % 20) - 10));
auto rtp = nb.encodeRtp(speech, 160, false);
assert(!rtp.empty());
auto pcm = nb.decodeRtp(rtp.data(), rtp.size(), false);
assert(pcm.size() == 160);
return 0;
}}
""")
subprocess.run(
["g++", "-std=c++20", "-O2", "-Wall", "-Wextra", "-Werror",
str(cpp_test), "-ldl", "-o", str(cpp_bin)],
check=True
)
subprocess.run([str(cpp_bin)], check=True)
print("[ok] amr_rtp.h RFC 4867 octet-aligned + bandwidth-efficient + libopencore-amrnb roundtrip")
def test_emergency_cellular_first(tmp):
state_dir = tmp / "emerg_state"
state_dir.mkdir()
conf = tmp / "emerg_ims.conf"
conf.write_text("wfc_preference=wifi_preferred\n")
st_file = state_dir / "state.env"
st_file.write_text("VOWIFI_REGISTERED=1\nVOLTE_REGISTERED=0\nVOWIFI_SIM=1\nNETWORK_4G_ONLY=1\n")
fake_bin = tmp / "fake_bin"
fake_bin.mkdir()
calls_log = tmp / "emerg_calls.log"
(fake_bin / "mmcli").write_text(f"""#!/bin/sh
echo "mmcli $*" >> "{calls_log}"
case "$*" in
*--voice-create-call=*) echo "/org/freedesktop/ModemManager1/Call/7" ;;
esac
exit 0
""")
(fake_bin / "doas").write_text('#!/bin/sh\nshift\nexec "$@"\n')
(fake_bin / "xcallscreen").write_text('#!/bin/sh\nexit 0\n')
(fake_bin / "sxmo_modemaudio.sh").write_text('#!/bin/sh\nexit 0\n')
(fake_bin / "sxmo_common.sh").write_text('sxmo_log() { :; }\nSXMO_LOGDIR="${SXMO_LOGDIR:-/tmp}"\n')
(fake_bin / "sxmo_notify_user.sh").write_text('#!/bin/sh\nexit 0\n')
(fake_bin / "sxmo_hook_dial.sh").write_text('#!/bin/sh\nexit 0\n')
(fake_bin / "sxmo_hook_statusbar.sh").write_text('#!/bin/sh\nexit 0\n')
(fake_bin / "sxmo_modem.sh").write_text('#!/bin/sh\nexit 0\n')
fake_ctl = fake_bin / "bananarchy-imsctl"
fake_ctl.write_text(f"""#!/bin/sh
echo "imsctl $*" >> "{calls_log}"
echo "OK vowifi:99"
exit 0
""")
for f in fake_bin.iterdir():
f.chmod(0o755)
# Ensure /usr/libexec isn't used and /tmp/sxmo_sim_slots gives single SIM 1
sim_slots = tmp / "sxmo_calls_rt"
(sim_slots / "sxmo_calls").mkdir(parents=True, exist_ok=True)
rt_calls = sim_slots / "sxmo_calls"
# Run sxmo_modemdial.sh with 112 (must hit mmcli, NOT imsctl first!)
env = os.environ.copy()
env.update({
"PATH": f"{fake_bin}:{BASE_DIR}/overlay/rootfs/usr/bin:{env.get('PATH', '')}",
"BANANARCHY_IMS_STATE_PATH": str(st_file),
"BANANARCHY_IMS_CONF_PATH": str(conf),
"BANANARCHY_IMS_CTL": str(fake_ctl),
"SXMO_SIM_SLOT": "1",
"SXMO_LOGDIR": str(tmp / "emerg_logs"),
"XDG_RUNTIME_DIR": str(sim_slots),
})
(tmp / "emerg_logs").mkdir(exist_ok=True)
subprocess.run(["sh", str(DIAL_SH), "112"], env=env, check=True)
clog = calls_log.read_text()
if "mmcli -m any --voice-create-call=number=112" not in clog or "imsctl call-dial 112" in clog:
return fail(f"emergency 112 must prefer cellular over VoWiFi! log={clog}")
# Normal number +46701112233 in wifi_preferred mode MUST hit imsctl call-dial!
calls_log.unlink()
for p in rt_calls.iterdir():
p.unlink()
subprocess.run(["sh", str(DIAL_SH), "+46701112233"], env=env, check=True)
clog2 = calls_log.read_text()
if "imsctl call-dial +46701112233" not in clog2:
return fail(f"normal call with VOWIFI_REGISTERED=1 must route via imsctl! log={clog2}")
print("[ok] emergency 112 cellular-first preference and normal VoWiFi dial routing")
return 0
def main():
with tempfile.TemporaryDirectory(prefix="bananarchy-vowifi-test-") as td:
tmp = Path(td)
test_amr_rtp(tmp)
if test_emergency_cellular_first(tmp) != 0:
return 1
vowifi_bin = tmp / "bananarchy-vowifi"
ctl_bin = tmp / "bananarchy-imsctl"
subprocess.run(
["g++", "-std=c++20", "-O2", "-Wall", "-Wextra", "-Werror",
f"-I{PLUG_DIR}", str(PLUG_DIR / "bananarchy_vowifi.cpp"),
"-lssl", "-lcrypto", "-ldl", "-lpthread", "-o", str(vowifi_bin)],
check=True
)
subprocess.run(
["gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror",
f"-I{DAEMONS_DIR}", str(DAEMONS_DIR / "bananarchy-imsctl.c"), "-o", str(ctl_bin)],
check=True
)
k_bytes = bytes.fromhex("465b5ce8b199b49faa5f0a2ee238a6bc")
op_bytes = bytes(16)
epdg = MockEpdgAndPcscf(k_bytes, op_bytes)
epdg.start()
state_dir = tmp / "ims_state"
state_dir.mkdir()
conf = tmp / "ims.conf"
conf.write_text(
"volte_mode=auto\nvowifi_mode=auto\nepdg_server=127.0.0.1\n"
"ims_apn=ims\nims_sim_slot=1\nwfc_preference=wifi_preferred\n"
)
(state_dir / "state.env").write_text("MCC=240\nMNC=01\n")
sxmo_rt = tmp / "rt"
sxmo_rt.mkdir(parents=True, exist_ok=True)
sxmo_logs = tmp / "smslogs"
sxmo_logs.mkdir(parents=True, exist_ok=True)
sxmo_block = tmp / "block.tsv"
sxmo_block.write_text("+46700000000\tspam\n")
env = os.environ.copy()
env.update({
"BANANARCHY_IMS_CONF_PATH": str(conf),
"BANANARCHY_IMS_STATE_DIR": str(state_dir),
"BANANARCHY_EPDG_PORT": str(epdg.port),
"BANANARCHY_PCSCF_PORT": "5060",
"BANANARCHY_VOWIFI_USERSPACE_TUN": "1",
"BANANARCHY_MOCK_MCC": "240",
"BANANARCHY_MOCK_MNC": "01",
"BANANARCHY_MOCK_AKA_KEY": k_bytes.hex(),
"BANANARCHY_MOCK_AKA_OP": op_bytes.hex(),
"BANANARCHY_MOCK_AUDIO": "1",
"BANANARCHY_NO_X11_LAUNCH": "1",
"BANANARCHY_LOG_SENT_SMS": "1",
"XDG_RUNTIME_DIR": str(sxmo_rt),
"SXMO_LOGDIR": str(sxmo_logs),
"SXMO_BLOCKFILE": str(sxmo_block),
})
proc = subprocess.Popen([str(vowifi_bin), "--mode=vowifi"], env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
deadline = time.monotonic() + 5.0
while time.monotonic() < deadline and not epdg.sip_registered:
time.sleep(0.05)
if not epdg.sip_registered:
st_txt = (state_dir / "state.env").read_text() if (state_dir / "state.env").exists() else ""
return fail(f"bananarchy-vowifi did not complete IKEv2+EAP-AKA+ESP+SIP REGISTER:\n{st_txt}")
if "VOWIFI_REGISTERED=1" not in (state_dir / "state.env").read_text():
return fail("state.env missing VOWIFI_REGISTERED=1")
# Outgoing call: INVITE -> 183 preconditions -> PRACK -> UPDATE -> 200 OK -> ESP RTP -> BYE
subprocess.run([str(ctl_bin), "call-dial", "+46701234567"], env=env, check=True)
deadline = time.monotonic() + 3.0
while time.monotonic() < deadline and len(epdg.rtp_frames_rx) < 2:
time.sleep(0.05)
if not epdg.prack_seen or not epdg.precond_update_seen or len(epdg.rtp_frames_rx) < 1:
return fail(f"call flow incomplete: prack={epdg.prack_seen} update={epdg.precond_update_seen} rtp={len(epdg.rtp_frames_rx)}")
subprocess.run([str(ctl_bin), "call-hangup"], env=env, check=True)
time.sleep(0.2)
if not epdg.bye_seen:
return fail("BYE not observed inside ESP tunnel after call-hangup")
# Incoming call -> ACCEPT -> HANGUP
epdg.inject_incoming_call()
deadline = time.monotonic() + 2.0
ring_marker = sxmo_rt / "sxmo_calls/vowifi_2.ringing-in"
while time.monotonic() < deadline and not ring_marker.exists():
time.sleep(0.05)
if not ring_marker.exists():
return fail("incoming call ringing-in marker missing")
subprocess.run([str(ctl_bin), "call-accept", "vowifi:2"], env=env, check=True)
time.sleep(0.1)
if not (sxmo_rt / "sxmo_calls/vowifi_2.pickedupcall").exists():
return fail("pickedupcall marker missing after call-accept")
subprocess.run([str(ctl_bin), "call-hangup", "vowifi:2"], env=env, check=True)
# SMS-over-IP TX & RX + verify sms.txt format & absence of [SIM n] tag
subprocess.run([str(ctl_bin), "sms-send", "+46709991111", "Hello VoWiFi Test!"], env=env, check=True)
time.sleep(0.2)
if len(epdg.sms_submit_rx) != 1:
return fail(f"expected 1 RP-DATA SMS submit packet, got {len(epdg.sms_submit_rx)}")
epdg.inject_incoming_sms("+46705551234", "Inbound 3GPP SMS")
time.sleep(0.2)
sms_txt = (sxmo_logs / "+46705551234/sms.txt").read_text()
if "Received at " not in sms_txt or "Inbound 3GPP SMS" not in sms_txt or "[SIM " in sms_txt:
return fail(f"sms.txt format violation (or unexpected [SIM n] tag):\n{sms_txt}")
# Blocked number SMS must be ignored
epdg.inject_incoming_sms("+46700000000", "Blocked Spam")
time.sleep(0.15)
if (sxmo_logs / "+46700000000/sms.txt").exists():
return fail("blocked number SMS should not be written")
finally:
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
proc.kill()
epdg.stop()
print("[ok] test-vowifi-swu-ims: SWu IKEv2 + EAP-AKA + ESP + SIP REGISTER/INVITE/PRACK/UPDATE/RTP + SMS-over-IP")
return 0
if __name__ == "__main__":
sys.exit(main())
+591
View File
@@ -0,0 +1,591 @@
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
/* Bananarchy IMS / VoLTE / VoWiFi control utility and MBN profile manager. */
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include "ims_mbn.h"
#include "ims_qrtr.h"
static int ims_is_duress(void) {
const char *p = getenv("BANANARCHY_DURESS_FLAG_PATH");
if (!p || !*p) {
p = "/tmp/bananarchy_duress_mode";
}
return access(p, F_OK) == 0;
}
static int ims_sock_cmd(const char *sock_name, const char *cmd, char *rsp,
size_t rsp_cap, int timeout_ms) {
if (rsp && rsp_cap > 0) {
rsp[0] = '\0';
}
char sock_path[PATH_MAX];
ims_state_file_path(sock_path, sizeof(sock_path), sock_name);
int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (fd < 0) {
return -1;
}
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
if (strlen(sock_path) >= sizeof(addr.sun_path)) {
close(fd);
return -1;
}
memcpy(addr.sun_path, sock_path, strlen(sock_path) + 1);
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
close(fd);
return -1;
}
size_t clen = strlen(cmd);
char *msg = (char *)malloc(clen + 2);
if (!msg) {
close(fd);
return -1;
}
memcpy(msg, cmd, clen);
msg[clen] = '\n';
msg[clen + 1] = '\0';
size_t off = 0;
while (off < clen + 1) {
ssize_t w = write(fd, msg + off, (clen + 1) - off);
if (w < 0) {
if (errno == EINTR) {
continue;
}
free(msg);
close(fd);
return -1;
}
off += (size_t)w;
}
free(msg);
shutdown(fd, SHUT_WR);
if (!rsp || rsp_cap == 0) {
close(fd);
return 0;
}
size_t roff = 0;
while (roff + 1 < rsp_cap) {
struct pollfd pfd;
pfd.fd = fd;
pfd.events = POLLIN;
pfd.revents = 0;
int pr = poll(&pfd, 1, timeout_ms);
if (pr <= 0) {
break;
}
ssize_t r = read(fd, rsp + roff, (rsp_cap - 1) - roff);
if (r < 0) {
if (errno == EINTR) {
continue;
}
break;
}
if (r == 0) {
break;
}
roff += (size_t)r;
}
rsp[roff] = '\0';
close(fd);
return 0;
}
static void print_json_str(const char *s) {
putchar('"');
for (; s && *s; s++) {
unsigned char c = (unsigned char)*s;
if (c == '"' || c == '\\') {
putchar('\\');
putchar((char)c);
} else if (c >= 0x20) {
putchar((char)c);
}
}
putchar('"');
}
static void format_plmns(const struct ims_mbn_info *m, char *out, size_t out_len) {
if (!out || out_len == 0) {
return;
}
out[0] = '\0';
if (!m || m->plmn_count == 0) {
ims_str_copy(out, out_len, "-");
return;
}
size_t off = 0;
for (size_t i = 0; i < m->plmn_count; i++) {
int n = snprintf(out + off, out_len - off, "%s%s-%s",
i == 0 ? "" : ",", m->plmns[i].mcc, m->plmns[i].mnc);
if (n < 0 || off + (size_t)n >= out_len) {
break;
}
off += (size_t)n;
}
}
static int cmd_status(int argc, char **argv) {
int json_mode = 0;
for (int i = 2; i < argc; i++) {
if (strcmp(argv[i], "--json") == 0) {
json_mode = 1;
}
}
struct ims_config cfg;
ims_config_load(&cfg, NULL);
struct ims_runtime_state st;
if (ims_state_read(&st) != 0) {
ims_str_copy(st.volte_mode, sizeof(st.volte_mode), cfg.volte_mode);
ims_str_copy(st.vowifi_mode, sizeof(st.vowifi_mode), cfg.vowifi_mode);
ims_str_copy(st.active_mbn, sizeof(st.active_mbn), cfg.active_mbn);
}
if (json_mode) {
printf("{");
printf("\"volte_mode\":"); print_json_str(cfg.volte_mode);
printf(",\"vowifi_mode\":"); print_json_str(cfg.vowifi_mode);
printf(",\"volte_backend_cfg\":"); print_json_str(cfg.volte_backend);
printf(",\"volte_backend\":"); print_json_str(st.volte_backend);
printf(",\"volte_active\":%d", st.volte_active);
printf(",\"volte_registered\":%d", st.volte_registered);
printf(",\"volte_capable\":%d", st.volte_capable);
printf(",\"network_4g_only\":%d", st.network_4g_only);
printf(",\"access_tech\":"); print_json_str(st.access_tech);
printf(",\"vowifi_active\":%d", st.vowifi_active);
printf(",\"vowifi_registered\":%d", st.vowifi_registered);
printf(",\"vowifi_ipv6_epdg\":%d", st.vowifi_ipv6_epdg);
printf(",\"ims_sim_slot\":%d", cfg.ims_sim_slot);
printf(",\"wfc_preference\":"); print_json_str(cfg.wfc_preference);
printf(",\"vowifi_roaming\":%d", cfg.vowifi_roaming);
printf(",\"vowifi_codec\":"); print_json_str(cfg.vowifi_codec);
printf(",\"ims_apn\":"); print_json_str(cfg.ims_apn);
printf(",\"epdg_server\":"); print_json_str(cfg.epdg_server);
printf(",\"epdg_host\":"); print_json_str(st.epdg_host);
printf(",\"pcscf_addr\":"); print_json_str(st.pcscf_addr);
printf(",\"tun_ip\":"); print_json_str(st.tun_ip);
printf(",\"tun_iface\":"); print_json_str(st.tun_iface);
printf(",\"ims_apn_iface\":"); print_json_str(st.ims_apn_iface);
printf(",\"ims_apn_ip\":"); print_json_str(st.ims_apn_ip);
printf(",\"active_mbn\":"); print_json_str(cfg.active_mbn);
printf(",\"mbn_description\":"); print_json_str(st.mbn_description);
printf(",\"mbn_version\":"); print_json_str(st.mbn_version);
printf(",\"auto_install_mbn\":%d", cfg.auto_install_mbn);
printf(",\"keep_lte_on_screen_off\":%d", cfg.keep_lte_on_screen_off);
printf(",\"mcc\":"); print_json_str(st.mcc);
printf(",\"mnc\":"); print_json_str(st.mnc);
printf(",\"last_error\":"); print_json_str(st.last_error);
printf("}\n");
return 0;
}
printf("VOLTE_MODE=%s\n", cfg.volte_mode);
printf("VOWIFI_MODE=%s\n", cfg.vowifi_mode);
printf("VOLTE_BACKEND=%s\n", st.volte_backend);
printf("VOLTE_ACTIVE=%d\n", st.volte_active);
printf("VOLTE_REGISTERED=%d\n", st.volte_registered);
printf("VOLTE_CAPABLE=%d\n", st.volte_capable);
printf("NETWORK_4G_ONLY=%d\n", st.network_4g_only);
printf("ACCESS_TECH=%s\n", st.access_tech);
printf("VOWIFI_ACTIVE=%d\n", st.vowifi_active);
printf("VOWIFI_REGISTERED=%d\n", st.vowifi_registered);
printf("VOWIFI_IPV6_EPDG=%d\n", st.vowifi_ipv6_epdg);
printf("IMS_SIM_SLOT=%d\n", cfg.ims_sim_slot);
printf("WFC_PREFERENCE=%s\n", cfg.wfc_preference);
printf("VOWIFI_ROAMING=%d\n", cfg.vowifi_roaming);
printf("VOWIFI_CODEC=%s\n", cfg.vowifi_codec);
printf("IMS_APN=%s\n", cfg.ims_apn);
printf("ACTIVE_MBN=%s\n", cfg.active_mbn);
printf("MBN_DESCRIPTION=%s\n", st.mbn_description);
printf("EPDG_HOST=%s\n", st.epdg_host);
printf("PCSCF_ADDR=%s\n", st.pcscf_addr);
printf("TUN_IP=%s\n", st.tun_ip);
printf("IMS_APN_IFACE=%s\n", st.ims_apn_iface);
printf("IMS_APN_IP=%s\n", st.ims_apn_ip);
printf("MCC=%s\n", st.mcc);
printf("MNC=%s\n", st.mnc);
printf("LAST_ERROR=%s\n", st.last_error);
return 0;
}
static int cmd_probe(void) {
struct ims_qrtr_ep ep;
if (ims_qrtr_open(&ep) != 0) {
printf("QRTR_AVAILABLE=0\n");
return 1;
}
struct ims_qrtr_addr a;
int has_nas = (ims_qrtr_lookup(&ep, IMS_QMI_SVC_NAS, 0, 300, &a) == 0);
int has_ims = (ims_qrtr_lookup(&ep, IMS_QMI_SVC_IMS, 0, 250, &a) == 0);
int has_imsa = (ims_qrtr_lookup(&ep, IMS_QMI_SVC_IMSA, 0, 250, &a) == 0);
int has_pdc = (ims_qrtr_lookup(&ep, IMS_QMI_SVC_PDC, 0, 250, &a) == 0);
int has_dsd = (ims_qrtr_lookup(&ep, IMS_QMI_SVC_DSD, 0, 250, &a) == 0);
int has_uim = (ims_qrtr_lookup(&ep, IMS_QMI_SVC_UIM, 0, 250, &a) == 0);
int has_dcm = (ims_qrtr_lookup(&ep, IMS_QMI_SVC_IMSDCM, 0, 150, &a) == 0);
int reg = 0, lte_only = 0, has_cs = 0;
char tech[32] = "unknown", mcc[8] = "", mnc[8] = "";
if (has_nas) {
(void)ims_qmi_nas_get_serving(&ep, 100, &reg, &lte_only, &has_cs,
tech, sizeof(tech), mcc, mnc);
}
int ims_reg = 0, ims_volte = 0, ims_vowifi = 0;
if (has_imsa) {
(void)ims_qmi_imsa_get_status(&ep, 110, &ims_reg, &ims_volte, &ims_vowifi);
}
ims_qrtr_close(&ep);
printf("QRTR_AVAILABLE=1\n");
printf("QMI_NAS=%d\n", has_nas);
printf("QMI_IMS=%d\n", has_ims);
printf("QMI_IMSA=%d\n", has_imsa);
printf("QMI_PDC=%d\n", has_pdc);
printf("QMI_DSD=%d\n", has_dsd);
printf("QMI_UIM=%d\n", has_uim);
printf("QMI_IMSDCM_REGISTERED=%d\n", has_dcm);
printf("SERVING_REG=%d\n", reg);
printf("ACCESS_TECH=%s\n", tech);
printf("NETWORK_4G_ONLY=%d\n", lte_only);
printf("HAS_CS_RAT=%d\n", has_cs);
printf("MCC=%s\n", mcc);
printf("MNC=%s\n", mnc);
printf("IMSA_REGISTERED=%d\n", ims_reg);
printf("IMSA_VOLTE=%d\n", ims_volte);
printf("IMSA_VOWIFI=%d\n", ims_vowifi);
return 0;
}
static int cmd_get(const char *key) {
struct ims_config cfg;
ims_config_load(&cfg, NULL);
if (strcmp(key, "volte_mode") == 0) printf("%s\n", cfg.volte_mode);
else if (strcmp(key, "vowifi_mode") == 0) printf("%s\n", cfg.vowifi_mode);
else if (strcmp(key, "volte_backend") == 0) printf("%s\n", cfg.volte_backend);
else if (strcmp(key, "epdg_server") == 0) printf("%s\n", cfg.epdg_server);
else if (strcmp(key, "ims_apn") == 0) printf("%s\n", cfg.ims_apn);
else if (strcmp(key, "ims_sim_slot") == 0) printf("%d\n", cfg.ims_sim_slot);
else if (strcmp(key, "active_mbn") == 0) printf("%s\n", cfg.active_mbn);
else if (strcmp(key, "auto_install_mbn") == 0) printf("%d\n", cfg.auto_install_mbn);
else if (strcmp(key, "vowifi_roaming") == 0) printf("%d\n", cfg.vowifi_roaming);
else if (strcmp(key, "wfc_preference") == 0) printf("%s\n", cfg.wfc_preference);
else if (strcmp(key, "vowifi_codec") == 0) printf("%s\n", cfg.vowifi_codec);
else if (strcmp(key, "sip_realm") == 0) printf("%s\n", cfg.sip_realm);
else if (strcmp(key, "pcscf_override") == 0) printf("%s\n", cfg.pcscf_override);
else if (strcmp(key, "keep_lte_on_screen_off") == 0) printf("%d\n", cfg.keep_lte_on_screen_off);
else {
fprintf(stderr, "Unknown key: %s\n", key);
return 1;
}
return 0;
}
static int cmd_set(const char *key, const char *val) {
if (ims_is_duress()) {
fprintf(stderr, "Blocked in duress mode\n");
return 1;
}
struct ims_config cfg;
ims_config_load(&cfg, NULL);
if (ims_config_set_kv(&cfg, key, val) != 0) {
fprintf(stderr, "Invalid setting %s=%s\n", key, val);
return 1;
}
if (ims_config_save(&cfg, NULL) != 0) {
fprintf(stderr, "Failed to save %s: %s\n", ims_conf_path(), strerror(errno));
return 1;
}
char rsp[256];
(void)ims_sock_cmd("imsd.sock", "REFRESH", rsp, sizeof(rsp), 1500);
return 0;
}
static int cmd_profile_inspect(const char *path) {
struct ims_mbn_info info;
if (ims_mbn_inspect_file(path, &info) != 0) {
fprintf(stderr, "Invalid MBN %s: %s\n", path, info.err);
return 1;
}
char plmns[512];
format_plmns(&info, plmns, sizeof(plmns));
printf("VALID=1\n");
printf("ID=%s\n", info.id);
printf("CONFIG_TYPE=%s\n", info.is_sw_config ? "SW" : (info.config_type == 0 ? "HW" : "UNKNOWN"));
printf("CONFIG_TYPE_RAW=%u\n", (unsigned)info.config_type);
printf("MCFG_FORMAT=%u\n", (unsigned)info.mcfg_format_ver);
printf("ITEMS=%u\n", (unsigned)info.num_items);
printf("SIZE=%zu\n", info.file_size);
printf("SHA1=%s\n", info.sha1_hex);
printf("VERSION=%s\n", info.version_str);
printf("DESCRIPTION=%s\n", info.description);
printf("IMS_CAPABLE=%d\n", (info.has_ims_efs || info.has_nv_67218) ? 1 : 0);
printf("HAS_NV_67218=%d\n", info.has_nv_67218);
printf("HAS_IMS_EFS=%d\n", info.has_ims_efs);
printf("PLMNS=%s\n", plmns);
return 0;
}
static int cmd_profile(int argc, char **argv) {
if (argc < 3) {
fprintf(stderr, "Usage: bananarchy-imsctl profile <list|inspect|install|select|remove|reset-default>\n");
return 1;
}
const char *sub = argv[2];
struct ims_config cfg;
ims_config_load(&cfg, NULL);
if (strcmp(sub, "list") == 0) {
int tsv = (argc >= 4 && strcmp(argv[3], "--tsv") == 0);
struct ims_mbn_info items[IMS_MAX_PROFILES];
size_t n = ims_profile_list(items, IMS_MAX_PROFILES);
for (size_t i = 0; i < n; i++) {
char plmns[512];
format_plmns(&items[i], plmns, sizeof(plmns));
int active = (cfg.active_mbn[0] && strcmp(cfg.active_mbn, items[i].id) == 0) ? 1 : 0;
if (tsv) {
printf("%s\t%d\t%s\t%d\t%s\t%s\t%s\n",
items[i].id, active, items[i].is_sw_config ? "SW" : "HW",
(items[i].has_ims_efs || items[i].has_nv_67218) ? 1 : 0,
items[i].version_str, plmns, items[i].description);
} else {
printf("%c %-20s %-3s ims=%d v=%-10s plmn=%-14s %s\n",
active ? '*' : ' ', items[i].id, items[i].is_sw_config ? "SW" : "HW",
(items[i].has_ims_efs || items[i].has_nv_67218) ? 1 : 0,
items[i].version_str, plmns, items[i].description);
}
}
return 0;
}
if (strcmp(sub, "inspect") == 0) {
if (argc < 4) {
fprintf(stderr, "Missing MBN path\n");
return 1;
}
return cmd_profile_inspect(argv[3]);
}
if (ims_is_duress()) {
fprintf(stderr, "Blocked in duress mode\n");
return 1;
}
if (strcmp(sub, "install") == 0) {
if (argc < 4) {
fprintf(stderr, "Missing MBN path\n");
return 1;
}
int activate = 0;
for (int i = 4; i < argc; i++) {
if (strcmp(argv[i], "--activate") == 0) {
activate = 1;
}
}
struct ims_mbn_info info;
if (ims_profile_install(argv[3], &info) != 0) {
fprintf(stderr, "Install failed: %s\n", info.err);
return 1;
}
char cmd[64], rsp[256];
snprintf(cmd, sizeof(cmd), "PDC_LOAD %s", info.id);
(void)ims_sock_cmd("imsd.sock", cmd, rsp, sizeof(rsp), 3000);
if (activate) {
ims_str_copy(cfg.active_mbn, sizeof(cfg.active_mbn), info.id);
(void)ims_config_save(&cfg, NULL);
snprintf(cmd, sizeof(cmd), "PDC_SELECT %s", info.id);
(void)ims_sock_cmd("imsd.sock", cmd, rsp, sizeof(rsp), 3000);
}
printf("INSTALLED=%s\nDESCRIPTION=%s\nVERSION=%s\nACTIVATED=%d\n",
info.id, info.description, info.version_str, activate);
return 0;
}
if (strcmp(sub, "select") == 0) {
if (argc < 4 || !ims_is_valid_profile_id(argv[3])) {
fprintf(stderr, "Invalid or missing profile ID\n");
return 1;
}
char p[PATH_MAX];
snprintf(p, sizeof(p), "%s/%s.mbn", ims_profiles_dir(), argv[3]);
struct ims_mbn_info info;
if (ims_mbn_inspect_file(p, &info) != 0 || !info.is_sw_config) {
fprintf(stderr, "Profile not installed or invalid SW MBN: %s\n", argv[3]);
return 1;
}
ims_str_copy(cfg.active_mbn, sizeof(cfg.active_mbn), argv[3]);
if (ims_config_save(&cfg, NULL) != 0) {
fprintf(stderr, "Failed to update config\n");
return 1;
}
char cmd[64], rsp[256];
snprintf(cmd, sizeof(cmd), "PDC_SELECT %s", argv[3]);
(void)ims_sock_cmd("imsd.sock", cmd, rsp, sizeof(rsp), 3000);
printf("SELECTED=%s\n", argv[3]);
return 0;
}
if (strcmp(sub, "remove") == 0) {
if (argc < 4) {
fprintf(stderr, "Missing profile ID\n");
return 1;
}
char err[128];
if (ims_profile_remove(argv[3], err, sizeof(err)) != 0) {
fprintf(stderr, "Remove failed: %s\n", err);
return 1;
}
if (strcmp(cfg.active_mbn, argv[3]) == 0) {
cfg.active_mbn[0] = '\0';
(void)ims_config_save(&cfg, NULL);
}
char cmd[64], rsp[256];
snprintf(cmd, sizeof(cmd), "PDC_DELETE %s", argv[3]);
(void)ims_sock_cmd("imsd.sock", cmd, rsp, sizeof(rsp), 2000);
printf("REMOVED=%s\n", argv[3]);
return 0;
}
if (strcmp(sub, "reset-default") == 0) {
cfg.active_mbn[0] = '\0';
(void)ims_config_save(&cfg, NULL);
char rsp[256];
(void)ims_sock_cmd("imsd.sock", "PDC_RESET", rsp, sizeof(rsp), 2000);
printf("RESET=1\n");
return 0;
}
fprintf(stderr, "Unknown profile subcommand: %s\n", sub);
return 1;
}
static int cmd_auto_match(void) {
if (ims_is_duress()) {
fprintf(stderr, "Blocked in duress mode\n");
return 1;
}
char rsp[512];
if (ims_sock_cmd("imsd.sock", "AUTO_MATCH", rsp, sizeof(rsp), 3000) == 0 && rsp[0]) {
printf("%s", rsp);
return (strncmp(rsp, "OK", 2) == 0) ? 0 : 1;
}
/* Offline / no-daemon fallback via QRTR NAS + profile store match. */
struct ims_qrtr_ep ep;
char mcc[8] = "", mnc[8] = "", tech[32] = "";
if (ims_qrtr_open(&ep) == 0) {
int reg = 0, lte = 0, cs = 0;
(void)ims_qmi_nas_get_serving(&ep, 200, &reg, &lte, &cs, tech, sizeof(tech), mcc, mnc);
ims_qrtr_close(&ep);
}
const char *env_mcc = getenv("BANANARCHY_MOCK_MCC");
const char *env_mnc = getenv("BANANARCHY_MOCK_MNC");
if (!mcc[0] && env_mcc) ims_str_copy(mcc, sizeof(mcc), env_mcc);
if (!mnc[0] && env_mnc) ims_str_copy(mnc, sizeof(mnc), env_mnc);
struct ims_mbn_info match;
if (ims_profile_match_plmn(mcc, mnc, &match)) {
struct ims_config cfg;
ims_config_load(&cfg, NULL);
ims_str_copy(cfg.active_mbn, sizeof(cfg.active_mbn), match.id);
(void)ims_config_save(&cfg, NULL);
printf("OK MATCHED=%s PLMN=%s-%s DESC=%s\n", match.id, mcc, mnc, match.description);
return 0;
}
printf("NO_MATCH PLMN=%s-%s\n", mcc, mnc);
return 1;
}
static int cmd_vowifi_forward(const char *verb, int argc, char **argv, int start_idx) {
char cmd[1024];
size_t off = (size_t)snprintf(cmd, sizeof(cmd), "%s", verb);
for (int i = start_idx; i < argc && off + 2 < sizeof(cmd); i++) {
int n = snprintf(cmd + off, sizeof(cmd) - off, " %s", argv[i]);
if (n < 0 || off + (size_t)n >= sizeof(cmd)) {
break;
}
off += (size_t)n;
}
char rsp[512];
if (ims_sock_cmd("vowifi.sock", cmd, rsp, sizeof(rsp), 4000) != 0 || !rsp[0]) {
fprintf(stderr, "ERR vowifi daemon unavailable\n");
return 1;
}
printf("%s", rsp);
return (strncmp(rsp, "OK", 2) == 0) ? 0 : 1;
}
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr,
"Usage: bananarchy-imsctl <status|probe|get|set|profile|auto-match|notify|"
"call-dial|call-accept|call-hangup|call-mute|call-dtmf|sms-send> ...\n");
return 1;
}
const char *cmd = argv[1];
if (strcmp(cmd, "status") == 0) {
return cmd_status(argc, argv);
}
if (strcmp(cmd, "probe") == 0) {
return cmd_probe();
}
if (strcmp(cmd, "get") == 0 && argc >= 3) {
return cmd_get(argv[2]);
}
if (strcmp(cmd, "set") == 0 && argc >= 4) {
return cmd_set(argv[2], argv[3]);
}
if (strcmp(cmd, "profile") == 0) {
return cmd_profile(argc, argv);
}
if (strcmp(cmd, "auto-match") == 0) {
return cmd_auto_match();
}
if (strcmp(cmd, "notify") == 0) {
char msg[256], rsp[256];
const char *ifn = (argc >= 3) ? argv[2] : "any";
const char *evt = (argc >= 4) ? argv[3] : "change";
snprintf(msg, sizeof(msg), "NET_EVENT %s %s", ifn, evt);
if (ims_sock_cmd("imsd.sock", msg, rsp, sizeof(rsp), 1500) == 0) {
return 0;
}
return 0; /* Non-blocking dispatcher safe */
}
if (strcmp(cmd, "call-dial") == 0 && argc >= 3) {
return cmd_vowifi_forward("DIAL", argc, argv, 2);
}
if (strcmp(cmd, "call-accept") == 0) {
return cmd_vowifi_forward("ACCEPT", argc, argv, 2);
}
if (strcmp(cmd, "call-hangup") == 0) {
return cmd_vowifi_forward("HANGUP", argc, argv, 2);
}
if (strcmp(cmd, "call-mute") == 0 && argc >= 3) {
return cmd_vowifi_forward("MUTE", argc, argv, 2);
}
if (strcmp(cmd, "call-dtmf") == 0 && argc >= 3) {
return cmd_vowifi_forward("DTMF", argc, argv, 2);
}
if (strcmp(cmd, "sms-send") == 0 && argc >= 4) {
return cmd_vowifi_forward("SMS_SEND", argc, argv, 2);
}
fprintf(stderr, "Unknown command: %s\n", cmd);
return 1;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+759
View File
@@ -0,0 +1,759 @@
#ifndef BANANARCHY_IMS_QRTR_H
#define BANANARCHY_IMS_QRTR_H
/* QMI QMUX + AF_QIPCRTR client/server helper with BANANARCHY_QRTR_MOCK_SOCK test support. */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <errno.h>
#include <poll.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#if defined(__has_include) && __has_include(<linux/qrtr.h>)
#include <linux/qrtr.h>
#else
struct sockaddr_qrtr {
sa_family_t sq_family;
uint32_t sq_node;
uint32_t sq_port;
};
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef AF_QIPCRTR
#define AF_QIPCRTR 42
#endif
#ifndef QRTR_PORT_CTRL
#define QRTR_PORT_CTRL 0xfffffffeU
#endif
#ifndef QRTR_TYPE_NEW_SERVER
#define QRTR_TYPE_NEW_SERVER 4U
#define QRTR_TYPE_DEL_SERVER 5U
#define QRTR_TYPE_NEW_LOOKUP 10U
#define QRTR_TYPE_DEL_LOOKUP 11U
#endif
/* QMI Service IDs (verified against rootfs libqmi-glib.so.5). */
#define IMS_QMI_SVC_WDS 0x0001U
#define IMS_QMI_SVC_DMS 0x0002U
#define IMS_QMI_SVC_NAS 0x0003U
#define IMS_QMI_SVC_UIM 0x000BU
#define IMS_QMI_SVC_IMS 0x0012U /* IMSS */
#define IMS_QMI_SVC_IMSA 0x0021U
#define IMS_QMI_SVC_PDC 0x0024U
#define IMS_QMI_SVC_DSD 0x002AU
#define IMS_QMI_SVC_DPM 0x002FU
#define IMS_QMI_SVC_IMSDCM 0x0302U
/* QMI Message IDs (verified against rootfs libqmi-glib.so.5). */
#define IMS_QMI_NAS_INDICATION_REGISTER 0x0003U
#define IMS_QMI_NAS_GET_SERVING_SYSTEM 0x0024U
#define IMS_QMI_NAS_GET_SYS_SEL_PREF 0x0034U
#define IMS_QMI_NAS_BIND_SUBSCRIPTION 0x0045U
#define IMS_QMI_UIM_READ_TRANSPARENT 0x0020U
#define IMS_QMI_UIM_READ_RECORD 0x0021U
#define IMS_QMI_UIM_GET_CARD_STATUS 0x002FU
#define IMS_QMI_UIM_AUTHENTICATE 0x0034U
#define IMS_QMI_UIM_SEND_APDU 0x003BU
#define IMS_QMI_UIM_LOGICAL_CHANNEL 0x003FU
#define IMS_QMI_UIM_OPEN_LOGICAL_CHANNEL 0x0042U
#define IMS_QMI_IMS_SET_POLICY_SETTINGS 0x0047U
#define IMS_QMI_IMS_GET_POLICY_SETTINGS 0x0048U
#define IMS_QMI_IMS_SET_SERVICES_ENABLED 0x008FU
#define IMS_QMI_IMS_GET_SERVICES_ENABLED 0x0090U
#define IMS_QMI_IMS_BIND 0x0098U
#define IMS_QMI_IMSA_GET_REG_STATUS 0x0020U
#define IMS_QMI_IMSA_GET_SVC_STATUS 0x0021U
#define IMS_QMI_IMSA_REGISTER_IND 0x0022U
#define IMS_QMI_IMSA_REG_STATUS_IND 0x0023U
#define IMS_QMI_IMSA_SVC_STATUS_IND 0x0024U
#define IMS_QMI_IMSA_BIND 0x0033U
#define IMS_QMI_IMSA_GET_BIND 0x0034U
#define IMS_QMI_PDC_RESET 0x0020U
#define IMS_QMI_PDC_REGISTER 0x0020U
#define IMS_QMI_PDC_GET_SELECTED_CONFIG 0x0022U
#define IMS_QMI_PDC_SET_SELECTED_CONFIG 0x0023U
#define IMS_QMI_PDC_LIST_CONFIGS 0x0024U
#define IMS_QMI_PDC_DELETE_CONFIG 0x0025U
#define IMS_QMI_PDC_LOAD_CONFIG 0x0026U
#define IMS_QMI_PDC_ACTIVATE_CONFIG 0x0027U
#define IMS_QMI_PDC_GET_CONFIG_INFO 0x0028U
#define IMS_QMI_PDC_DEACTIVATE_CONFIG 0x002BU
#define IMS_QMI_DSD_GET_SYSTEM_STATUS 0x0024U
#define IMS_QMI_DSD_SYSTEM_STATUS_CHANGE 0x0025U
#define IMS_QMI_DSD_GET_APN_INFO 0x0033U
#define IMS_QMI_DSD_SET_APN_TYPE 0x0051U
#define IMS_QMI_IMSDCM_PDP_ACTIVATE 0x0020U
#define IMS_QMI_IMSDCM_PDP_DEACTIVATE 0x0021U
/* QMUX flags */
#define IMS_QMI_FLAG_REQ 0x00U
#define IMS_QMI_FLAG_RSP 0x02U
#define IMS_QMI_FLAG_IND 0x04U
/* Mock QRTR router wire framing when BANANARCHY_QRTR_MOCK_SOCK is set. */
#define IMS_MOCK_MAGIC 0x51525452U /* "QRTR" */
#define IMS_MOCK_MSG_LOOKUP 1U
#define IMS_MOCK_MSG_REGISTER 2U
#define IMS_MOCK_MSG_DATA 3U
struct ims_qrtr_mock_pkt {
uint32_t magic;
uint32_t msg_type;
uint32_t src_node;
uint32_t src_port;
uint32_t dst_node;
uint32_t dst_port;
uint32_t service;
uint32_t instance;
uint32_t payload_len;
uint8_t payload[4096];
};
struct ims_qrtr_ep {
int fd;
int is_mock;
uint32_t local_node;
uint32_t local_port;
};
struct ims_qrtr_addr {
uint32_t node;
uint32_t port;
};
static inline void ims_qmi_put_le16(uint8_t *p, uint16_t v) {
p[0] = (uint8_t)(v & 0xFFU);
p[1] = (uint8_t)((v >> 8) & 0xFFU);
}
static inline void ims_qmi_put_le32(uint8_t *p, uint32_t v) {
p[0] = (uint8_t)(v & 0xFFU);
p[1] = (uint8_t)((v >> 8) & 0xFFU);
p[2] = (uint8_t)((v >> 16) & 0xFFU);
p[3] = (uint8_t)((v >> 24) & 0xFFU);
}
static inline void ims_qmi_put_le64(uint8_t *p, uint64_t v) {
for (int i = 0; i < 8; i++) {
p[i] = (uint8_t)((v >> (i * 8)) & 0xFFU);
}
}
static inline uint16_t ims_qmi_get_le16(const uint8_t *p) {
return (uint16_t)p[0] | ((uint16_t)p[1] << 8);
}
static inline uint32_t ims_qmi_get_le32(const uint8_t *p) {
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
static inline int ims_qmi_tlv_add(uint8_t *buf, size_t cap, size_t *off,
uint8_t type, const void *val, uint16_t len) {
if (!buf || !off || *off + 3U + (size_t)len > cap) {
return -1;
}
buf[*off] = type;
ims_qmi_put_le16(buf + *off + 1, len);
if (len > 0 && val) {
memcpy(buf + *off + 3, val, len);
}
*off += 3U + (size_t)len;
return 0;
}
static inline const uint8_t *ims_qmi_tlv_find(const uint8_t *tlvs, size_t tlvs_len,
uint8_t type, uint16_t *out_len) {
size_t off = 0;
while (off + 3 <= tlvs_len) {
uint8_t t = tlvs[off];
uint16_t l = ims_qmi_get_le16(tlvs + off + 1);
off += 3;
if (off + l > tlvs_len) {
break;
}
if (t == type) {
if (out_len) {
*out_len = l;
}
return tlvs + off;
}
off += l;
}
return NULL;
}
static inline int ims_qmi_check_result(const uint8_t *msg, size_t msg_len, uint16_t *out_err) {
if (!msg || msg_len < 7) {
if (out_err) {
*out_err = 0xFFFFU;
}
return -1;
}
uint16_t tlv_len = ims_qmi_get_le16(msg + 5);
if (7U + (size_t)tlv_len > msg_len) {
if (out_err) {
*out_err = 0xFFFFU;
}
return -1;
}
uint16_t rl = 0;
const uint8_t *rv = ims_qmi_tlv_find(msg + 7, tlv_len, 0x02U, &rl);
if (!rv || rl < 4) {
if (out_err) {
*out_err = 0;
}
return 0;
}
uint16_t res = ims_qmi_get_le16(rv);
uint16_t err = ims_qmi_get_le16(rv + 2);
if (out_err) {
*out_err = err;
}
return (res == 0) ? 0 : -1;
}
static inline size_t ims_qmi_pack_msg(uint8_t *out, size_t cap, uint8_t flags,
uint16_t txn_id, uint16_t msg_id,
const uint8_t *tlvs, size_t tlvs_len) {
if (!out || cap < 7U + tlvs_len || tlvs_len > 65535U) {
return 0;
}
out[0] = flags;
ims_qmi_put_le16(out + 1, txn_id);
ims_qmi_put_le16(out + 3, msg_id);
ims_qmi_put_le16(out + 5, (uint16_t)tlvs_len);
if (tlvs_len > 0 && tlvs) {
memcpy(out + 7, tlvs, tlvs_len);
}
return 7U + tlvs_len;
}
static inline const char *ims_qrtr_mock_path(void) {
const char *p = getenv("BANANARCHY_QRTR_MOCK_SOCK");
return (p && *p) ? p : NULL;
}
static inline int ims_qrtr_open(struct ims_qrtr_ep *ep) {
if (!ep) {
return -1;
}
memset(ep, 0, sizeof(*ep));
ep->fd = -1;
const char *mock = ims_qrtr_mock_path();
if (mock) {
int fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
if (fd < 0) {
fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
if (fd < 0) {
return -1;
}
struct sockaddr_un local_addr;
memset(&local_addr, 0, sizeof(local_addr));
local_addr.sun_family = AF_UNIX;
snprintf(local_addr.sun_path, sizeof(local_addr.sun_path),
"/tmp/.ba_qrtr_%ld_%d", (long)getpid(), fd);
unlink(local_addr.sun_path);
if (bind(fd, (struct sockaddr *)&local_addr, sizeof(local_addr)) != 0) {
close(fd);
return -1;
}
}
struct sockaddr_un remote;
memset(&remote, 0, sizeof(remote));
remote.sun_family = AF_UNIX;
if (strlen(mock) >= sizeof(remote.sun_path)) {
close(fd);
return -1;
}
memcpy(remote.sun_path, mock, strlen(mock) + 1);
if (connect(fd, (struct sockaddr *)&remote, sizeof(remote)) != 0) {
close(fd);
return -1;
}
ep->fd = fd;
ep->is_mock = 1;
ep->local_node = 1;
ep->local_port = (uint32_t)(((getpid() & 0xFFFFU) << 8) ^ (uint32_t)fd);
return 0;
}
int fd = socket(AF_QIPCRTR, SOCK_DGRAM | SOCK_CLOEXEC, 0);
if (fd < 0) {
return -1;
}
struct sockaddr_qrtr sq;
socklen_t slen = sizeof(sq);
memset(&sq, 0, sizeof(sq));
if (getsockname(fd, (struct sockaddr *)&sq, &slen) == 0) {
ep->local_node = sq.sq_node;
ep->local_port = sq.sq_port;
}
ep->fd = fd;
ep->is_mock = 0;
return 0;
}
static inline void ims_qrtr_close(struct ims_qrtr_ep *ep) {
if (!ep) {
return;
}
if (ep->fd >= 0) {
close(ep->fd);
ep->fd = -1;
}
}
static inline int ims_qrtr_lookup(struct ims_qrtr_ep *ep, uint32_t service,
uint32_t instance_mask, int timeout_ms,
struct ims_qrtr_addr *out) {
if (!ep || ep->fd < 0 || !out) {
return -1;
}
if (ep->is_mock) {
struct ims_qrtr_mock_pkt req;
memset(&req, 0, sizeof(req));
req.magic = IMS_MOCK_MAGIC;
req.msg_type = IMS_MOCK_MSG_LOOKUP;
req.src_node = ep->local_node;
req.src_port = ep->local_port;
req.service = service;
req.instance = instance_mask;
if (send(ep->fd, &req, offsetof(struct ims_qrtr_mock_pkt, payload), 0) < 0) {
return -1;
}
struct pollfd pfd;
pfd.fd = ep->fd;
pfd.events = POLLIN;
pfd.revents = 0;
if (poll(&pfd, 1, timeout_ms) <= 0) {
return -1;
}
struct ims_qrtr_mock_pkt rsp;
ssize_t n = recv(ep->fd, &rsp, sizeof(rsp), 0);
if (n < (ssize_t)offsetof(struct ims_qrtr_mock_pkt, payload) ||
rsp.magic != IMS_MOCK_MAGIC || rsp.dst_port == 0) {
return -1;
}
out->node = rsp.dst_node;
out->port = rsp.dst_port;
return 0;
}
/* Live AF_QIPCRTR control lookup. */
uint32_t ctrl[5];
ctrl[0] = QRTR_TYPE_NEW_LOOKUP;
ctrl[1] = service;
ctrl[2] = instance_mask;
ctrl[3] = 0;
ctrl[4] = 0;
struct sockaddr_qrtr csq;
memset(&csq, 0, sizeof(csq));
csq.sq_family = AF_QIPCRTR;
csq.sq_node = ep->local_node;
csq.sq_port = QRTR_PORT_CTRL;
if (sendto(ep->fd, ctrl, sizeof(ctrl), 0, (struct sockaddr *)&csq, sizeof(csq)) < 0) {
return -1;
}
int found = 0;
for (int iter = 0; iter < 16; iter++) {
struct pollfd pfd;
pfd.fd = ep->fd;
pfd.events = POLLIN;
pfd.revents = 0;
int prc = poll(&pfd, 1, iter == 0 ? timeout_ms : 150);
if (prc <= 0) {
break;
}
uint32_t pkt[16];
struct sockaddr_qrtr from;
socklen_t flen = sizeof(from);
ssize_t r = recvfrom(ep->fd, pkt, sizeof(pkt), 0, (struct sockaddr *)&from, &flen);
if (r >= 20 && pkt[0] == QRTR_TYPE_NEW_SERVER && pkt[1] == service) {
if (pkt[3] != 0 || pkt[4] != 0) {
out->node = pkt[3];
out->port = pkt[4];
found = 1;
}
}
}
ctrl[0] = QRTR_TYPE_DEL_LOOKUP;
(void)sendto(ep->fd, ctrl, sizeof(ctrl), 0, (struct sockaddr *)&csq, sizeof(csq));
return found ? 0 : -1;
}
static inline int ims_qrtr_register_server(struct ims_qrtr_ep *ep, uint32_t service,
uint32_t instance) {
if (!ep || ep->fd < 0) {
return -1;
}
if (ep->is_mock) {
struct ims_qrtr_mock_pkt req;
memset(&req, 0, sizeof(req));
req.magic = IMS_MOCK_MAGIC;
req.msg_type = IMS_MOCK_MSG_REGISTER;
req.src_node = ep->local_node;
req.src_port = ep->local_port;
req.service = service;
req.instance = instance;
if (send(ep->fd, &req, offsetof(struct ims_qrtr_mock_pkt, payload), 0) < 0) {
return -1;
}
return 0;
}
uint32_t ctrl[5];
ctrl[0] = QRTR_TYPE_NEW_SERVER;
ctrl[1] = service;
ctrl[2] = instance;
ctrl[3] = ep->local_node;
ctrl[4] = ep->local_port;
struct sockaddr_qrtr csq;
memset(&csq, 0, sizeof(csq));
csq.sq_family = AF_QIPCRTR;
csq.sq_node = ep->local_node;
csq.sq_port = QRTR_PORT_CTRL;
return sendto(ep->fd, ctrl, sizeof(ctrl), 0, (struct sockaddr *)&csq, sizeof(csq)) < 0 ? -1 : 0;
}
static inline int ims_qrtr_send(struct ims_qrtr_ep *ep, const struct ims_qrtr_addr *dst,
const uint8_t *payload, size_t len) {
if (!ep || ep->fd < 0 || !dst || !payload || len == 0 || len > 4096) {
return -1;
}
if (ep->is_mock) {
struct ims_qrtr_mock_pkt pkt;
memset(&pkt, 0, offsetof(struct ims_qrtr_mock_pkt, payload));
pkt.magic = IMS_MOCK_MAGIC;
pkt.msg_type = IMS_MOCK_MSG_DATA;
pkt.src_node = ep->local_node;
pkt.src_port = ep->local_port;
pkt.dst_node = dst->node;
pkt.dst_port = dst->port;
pkt.payload_len = (uint32_t)len;
memcpy(pkt.payload, payload, len);
size_t total = offsetof(struct ims_qrtr_mock_pkt, payload) + len;
return (send(ep->fd, &pkt, total, 0) < 0) ? -1 : 0;
}
struct sockaddr_qrtr dsq;
memset(&dsq, 0, sizeof(dsq));
dsq.sq_family = AF_QIPCRTR;
dsq.sq_node = dst->node;
dsq.sq_port = dst->port;
return (sendto(ep->fd, payload, len, 0, (struct sockaddr *)&dsq, sizeof(dsq)) < 0) ? -1 : 0;
}
static inline ssize_t ims_qrtr_recv(struct ims_qrtr_ep *ep, struct ims_qrtr_addr *src,
uint8_t *buf, size_t cap, int timeout_ms) {
if (!ep || ep->fd < 0 || !buf || cap == 0) {
return -1;
}
struct pollfd pfd;
pfd.fd = ep->fd;
pfd.events = POLLIN;
pfd.revents = 0;
int prc = poll(&pfd, 1, timeout_ms);
if (prc <= 0) {
return (prc == 0) ? 0 : -1;
}
if (ep->is_mock) {
struct ims_qrtr_mock_pkt pkt;
ssize_t n = recv(ep->fd, &pkt, sizeof(pkt), 0);
if (n < (ssize_t)offsetof(struct ims_qrtr_mock_pkt, payload) || pkt.magic != IMS_MOCK_MAGIC) {
return -1;
}
if (pkt.msg_type != IMS_MOCK_MSG_DATA) {
return 0;
}
size_t plen = pkt.payload_len;
if (plen > sizeof(pkt.payload)) {
plen = sizeof(pkt.payload);
}
if (plen > cap) {
plen = cap;
}
memcpy(buf, pkt.payload, plen);
if (src) {
src->node = pkt.src_node;
src->port = pkt.src_port;
}
return (ssize_t)plen;
}
struct sockaddr_qrtr ssq;
socklen_t slen = sizeof(ssq);
memset(&ssq, 0, sizeof(ssq));
ssize_t r = recvfrom(ep->fd, buf, cap, 0, (struct sockaddr *)&ssq, &slen);
if (r > 0 && src) {
src->node = ssq.sq_node;
src->port = ssq.sq_port;
}
return r;
}
static inline int ims_qmi_transact(struct ims_qrtr_ep *ep, const struct ims_qrtr_addr *dst,
uint16_t txn_id, uint16_t msg_id,
const uint8_t *req_tlvs, size_t req_tlvs_len,
int timeout_ms, uint8_t *rsp_buf, size_t rsp_cap,
size_t *out_rsp_len) {
uint8_t req[4096];
size_t req_len = ims_qmi_pack_msg(req, sizeof(req), IMS_QMI_FLAG_REQ, txn_id, msg_id,
req_tlvs, req_tlvs_len);
if (req_len == 0) {
return -1;
}
if (ims_qrtr_send(ep, dst, req, req_len) != 0) {
return -1;
}
for (int tries = 0; tries < 12; tries++) {
struct ims_qrtr_addr from;
ssize_t n = ims_qrtr_recv(ep, &from, rsp_buf, rsp_cap, timeout_ms);
if (n <= 0) {
break;
}
if (n >= 7 && (rsp_buf[0] & 0x06U) == IMS_QMI_FLAG_RSP &&
ims_qmi_get_le16(rsp_buf + 1) == txn_id &&
ims_qmi_get_le16(rsp_buf + 3) == msg_id) {
if (out_rsp_len) {
*out_rsp_len = (size_t)n;
}
return 0;
}
}
return -1;
}
static inline int ims_qmi_nas_get_serving(struct ims_qrtr_ep *ep, uint16_t txn_id,
int *out_reg_state, int *out_lte_only,
int *out_has_cs_rat, char *out_tech, size_t tech_len,
char *out_mcc, char *out_mnc) {
if (out_reg_state) *out_reg_state = 0;
if (out_lte_only) *out_lte_only = 0;
if (out_has_cs_rat) *out_has_cs_rat = 0;
if (out_tech && tech_len) ims_str_copy(out_tech, tech_len, "unknown");
if (out_mcc) out_mcc[0] = '\0';
if (out_mnc) out_mnc[0] = '\0';
struct ims_qrtr_addr nas_addr;
if (ims_qrtr_lookup(ep, IMS_QMI_SVC_NAS, 0, 500, &nas_addr) != 0) {
return -1;
}
uint8_t rsp[1024];
size_t rlen = 0;
if (ims_qmi_transact(ep, &nas_addr, txn_id, IMS_QMI_NAS_GET_SERVING_SYSTEM,
NULL, 0, 800, rsp, sizeof(rsp), &rlen) != 0) {
return -1;
}
if (ims_qmi_check_result(rsp, rlen, NULL) != 0 || rlen < 7) {
return -1;
}
const uint8_t *tlvs = rsp + 7;
size_t tlen = ims_qmi_get_le16(rsp + 5);
if (7U + tlen > rlen) {
tlen = rlen - 7U;
}
int has_lte = 0;
int has_cs = 0;
uint16_t s_len = 0;
const uint8_t *srv = ims_qmi_tlv_find(tlvs, tlen, 0x01U, &s_len);
if (srv && s_len >= 6) {
if (out_reg_state) {
*out_reg_state = srv[0]; /* 1 = REGISTERED */
}
uint8_t n_rad = srv[4];
for (uint8_t i = 0; i < n_rad && (size_t)(5 + i) < s_len; i++) {
uint8_t rad = srv[5 + i];
/* QMI NAS Radio Interface: 0x04=GSM, 0x05=UMTS, 0x08=LTE, 0x09=TD-SCDMA */
if (rad == 0x08U) {
has_lte = 1;
if (out_tech && tech_len) ims_str_copy(out_tech, tech_len, "lte");
} else if (rad == 0x04U || rad == 0x05U || rad == 0x01U || rad == 0x02U || rad == 0x09U) {
has_cs = 1;
if (out_tech && tech_len && !has_lte) {
ims_str_copy(out_tech, tech_len, rad == 0x04U ? "gsm" : "umts");
}
}
}
}
/* Current PLMN TLV 0x12: mcc (u16 LE), mnc (u16 LE), description */
uint16_t p_len = 0;
const uint8_t *plmn = ims_qmi_tlv_find(tlvs, tlen, 0x12U, &p_len);
if (plmn && p_len >= 4) {
uint16_t mcc = ims_qmi_get_le16(plmn);
uint16_t mnc = ims_qmi_get_le16(plmn + 2);
if (out_mcc && mcc > 0 && mcc <= 999) {
snprintf(out_mcc, 8, "%03u", (unsigned)mcc);
}
if (out_mnc && mnc != 0xFFFFU && mnc <= 999) {
/* Check optional TLV 0x29 MNC includes PCS digit if present. */
uint16_t d_len = 0;
const uint8_t *pcs = ims_qmi_tlv_find(tlvs, tlen, 0x29U, &d_len);
int is3 = (pcs && d_len >= 3 && pcs[2] != 0) || mnc >= 100U;
snprintf(out_mnc, 8, is3 ? "%03u" : "%02u", (unsigned)mnc);
}
}
/* Also query System Selection Preference (0x0034) to check mode_pref (LTE-only mask 0x10). */
int pref_lte_only = 0;
size_t plen = 0;
if (ims_qmi_transact(ep, &nas_addr, (uint16_t)(txn_id + 1),
IMS_QMI_NAS_GET_SYS_SEL_PREF, NULL, 0, 600,
rsp, sizeof(rsp), &plen) == 0 &&
ims_qmi_check_result(rsp, plen, NULL) == 0 && plen >= 7) {
uint16_t stlv_len = ims_qmi_get_le16(rsp + 5);
if (7U + stlv_len <= plen) {
uint16_t mpl = 0;
const uint8_t *mp = ims_qmi_tlv_find(rsp + 7, stlv_len, 0x11U, &mpl);
if (mp && mpl >= 2) {
uint16_t mask = ims_qmi_get_le16(mp);
/* QMI_NAS_RAT_MODE_PREFERENCE_LTE = 0x0010 */
if (mask == 0x0010U) {
pref_lte_only = 1;
}
}
}
}
if (out_has_cs_rat) {
*out_has_cs_rat = has_cs;
}
if (out_lte_only) {
/* 4G-only if serving RAT is LTE without CS fallback OR modem mode preference is LTE-only. */
*out_lte_only = ((has_lte && !has_cs) || pref_lte_only) ? 1 : 0;
}
return 0;
}
static inline int ims_qmi_imsa_get_status(struct ims_qrtr_ep *ep, uint16_t txn_id,
int *out_registered, int *out_volte,
int *out_vowifi) {
if (out_registered) *out_registered = 0;
if (out_volte) *out_volte = 0;
if (out_vowifi) *out_vowifi = 0;
struct ims_qrtr_addr imsa_addr;
if (ims_qrtr_lookup(ep, IMS_QMI_SVC_IMSA, 0, 400, &imsa_addr) != 0) {
return -1;
}
uint8_t rsp[512];
size_t rlen = 0;
if (ims_qmi_transact(ep, &imsa_addr, txn_id, IMS_QMI_IMSA_GET_REG_STATUS,
NULL, 0, 500, rsp, sizeof(rsp), &rlen) == 0 &&
ims_qmi_check_result(rsp, rlen, NULL) == 0 && rlen >= 7) {
uint16_t tlen = ims_qmi_get_le16(rsp + 5);
if (7U + tlen <= rlen) {
uint16_t rl = 0;
const uint8_t *rv = ims_qmi_tlv_find(rsp + 7, tlen, 0x10U, &rl);
if (!rv) {
rv = ims_qmi_tlv_find(rsp + 7, tlen, 0x12U, &rl);
}
if (rv && rl >= 1) {
if (out_registered) {
/* QMI_IMSA_REGISTRATION_STATUS_REGISTERED = 2 (older 1) */
*out_registered = (rv[0] == 2 || rv[0] == 1) ? 1 : 0;
}
}
}
}
if (ims_qmi_transact(ep, &imsa_addr, (uint16_t)(txn_id + 1), IMS_QMI_IMSA_GET_SVC_STATUS,
NULL, 0, 500, rsp, sizeof(rsp), &rlen) == 0 &&
ims_qmi_check_result(rsp, rlen, NULL) == 0 && rlen >= 7) {
uint16_t tlen = ims_qmi_get_le16(rsp + 5);
if (7U + tlen <= rlen) {
uint16_t vl = 0;
const uint8_t *voip = ims_qmi_tlv_find(rsp + 7, tlen, 0x11U, &vl);
const uint8_t *rat = ims_qmi_tlv_find(rsp + 7, tlen, 0x15U, &vl);
if (voip && voip[0] == 2) {
if (rat && rat[0] == 1 /* WLAN */) {
if (out_vowifi) *out_vowifi = 1;
} else {
if (out_volte) *out_volte = 1;
}
}
}
}
return 0;
}
static inline int ims_qmi_ims_set_services(struct ims_qrtr_ep *ep, uint16_t txn_id,
int enable_volte, int enable_vowifi,
int enable_sms) {
struct ims_qrtr_addr ims_addr;
if (ims_qrtr_lookup(ep, IMS_QMI_SVC_IMS, 0, 400, &ims_addr) != 0) {
return -1;
}
uint8_t tlvs[64];
size_t off = 0;
uint8_t v_sms = enable_sms ? 1 : 0;
uint8_t v_voip = enable_volte ? 1 : 0;
uint8_t v_wfc = enable_vowifi ? 1 : 0;
(void)ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x10U, &v_sms, 1);
(void)ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x11U, &v_voip, 1);
(void)ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x1CU, &v_wfc, 1);
uint8_t rsp[512];
size_t rlen = 0;
if (ims_qmi_transact(ep, &ims_addr, txn_id, IMS_QMI_IMS_SET_SERVICES_ENABLED,
tlvs, off, 600, rsp, sizeof(rsp), &rlen) != 0) {
return -1;
}
return ims_qmi_check_result(rsp, rlen, NULL);
}
static inline int ims_qmi_dsd_set_ims_apn(struct ims_qrtr_ep *ep, uint16_t txn_id,
const char *apn_name) {
if (!apn_name || !*apn_name) {
apn_name = "ims";
}
struct ims_qrtr_addr dsd_addr;
if (ims_qrtr_lookup(ep, IMS_QMI_SVC_DSD, 0, 400, &dsd_addr) != 0) {
return -1;
}
uint8_t tlvs[256];
size_t off = 0;
size_t alen = strlen(apn_name);
if (alen > 100) {
alen = 100;
}
uint8_t apn_type[128];
apn_type[0] = (uint8_t)alen;
memcpy(apn_type + 1, apn_name, alen);
/* QMI_DSD_APN_TYPE_MASK_IMS = 0x04 */
ims_qmi_put_le64(apn_type + 1 + alen, 0x04ULL);
(void)ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x01U, apn_type, (uint16_t)(1U + alen + 8U));
uint8_t rsp[512];
size_t rlen = 0;
if (ims_qmi_transact(ep, &dsd_addr, txn_id, IMS_QMI_DSD_SET_APN_TYPE,
tlvs, off, 600, rsp, sizeof(rsp), &rlen) != 0) {
return -1;
}
return ims_qmi_check_result(rsp, rlen, NULL);
}
#ifdef __cplusplus
}
#endif
#endif /* BANANARCHY_IMS_QRTR_H */
+199
View File
@@ -0,0 +1,199 @@
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdlib.h>
typedef void (*wds_async_cb_fn)(void *, void *, void *);
typedef void *(*qmi_alloc_finish_fn)(void *, void *, void **);
typedef int (*qmi_get_svc_fn)(void *);
typedef void *(*g_obj_ref_fn)(void *);
typedef void (*g_obj_unref_fn)(void *);
typedef void *(*qmi_wds_bind_inp_new_fn)(void);
typedef int (*qmi_wds_bind_inp_set_fn)(void *, unsigned int, void **);
typedef void (*qmi_wds_bind_inp_unref_fn)(void *);
typedef void *(*qmi_wds_bind_finish_fn)(void *, void *, void **);
typedef void (*qmi_wds_bind_out_unref_fn)(void *);
typedef void (*qmi_wds_bind_fn)(void *, void *, unsigned int, void *,
wds_async_cb_fn, void *);
typedef void (*qmi_wds_port_bind_fn)(void *, void *, unsigned int, void *,
wds_async_cb_fn, void *);
#define QMI_SVC_WDS 1
#define QMI_SUB_PRIMARY 1U
typedef struct {
void *client;
void *cancellable;
void *port_source;
void *orig_res;
wds_async_cb_fn orig_cb;
void *orig_ud;
unsigned int sub_id;
} WdsPortBindCtx;
static void *ref_gobj(void *obj) {
if (!obj) {
return NULL;
}
g_obj_ref_fn fn = (g_obj_ref_fn)dlsym(RTLD_DEFAULT, "g_object_ref");
return fn ? fn(obj) : obj;
}
static void unref_gobj(void *obj) {
if (!obj) {
return;
}
g_obj_unref_fn fn = (g_obj_unref_fn)dlsym(RTLD_DEFAULT, "g_object_unref");
if (fn) {
fn(obj);
}
}
static unsigned int resolve_wds_sub_id(void) {
unsigned int sub_id = QMI_SUB_PRIMARY;
const char *env_sub = getenv("BANANARCHY_WDS_SUBSCRIPTION");
if (env_sub && env_sub[0] != '\0') {
char *end = NULL;
unsigned long val = strtoul(env_sub, &end, 10);
if (end && *end == '\0') {
return (unsigned int)val;
}
}
return sub_id;
}
static void on_wds_bind_done(void *source, void *res, void *user_data) {
(void)user_data;
qmi_wds_bind_finish_fn finish_fn =
(qmi_wds_bind_finish_fn)dlsym(RTLD_DEFAULT, "qmi_client_wds_bind_subscription_finish");
qmi_wds_bind_out_unref_fn unref_fn =
(qmi_wds_bind_out_unref_fn)dlsym(RTLD_DEFAULT, "qmi_message_wds_bind_subscription_output_unref");
if (finish_fn) {
void *out = finish_fn(source, res, NULL);
if (out && unref_fn) {
unref_fn(out);
}
}
}
static int send_wds_bind_sub(void *client, unsigned int sub_id, void *cancellable,
wds_async_cb_fn cb, void *user_data) {
if (!client || sub_id == 0U) {
return 0;
}
qmi_wds_bind_inp_new_fn inp_new =
(qmi_wds_bind_inp_new_fn)dlsym(RTLD_DEFAULT, "qmi_message_wds_bind_subscription_input_new");
qmi_wds_bind_inp_set_fn inp_set =
(qmi_wds_bind_inp_set_fn)dlsym(RTLD_DEFAULT, "qmi_message_wds_bind_subscription_input_set_subscription_id");
qmi_wds_bind_inp_unref_fn inp_unref =
(qmi_wds_bind_inp_unref_fn)dlsym(RTLD_DEFAULT, "qmi_message_wds_bind_subscription_input_unref");
qmi_wds_bind_fn bind_sub =
(qmi_wds_bind_fn)dlsym(RTLD_DEFAULT, "qmi_client_wds_bind_subscription");
if (!inp_new || !inp_set || !inp_unref || !bind_sub) {
return 0;
}
void *inp = inp_new();
if (!inp) {
return 0;
}
int sent = 0;
if (inp_set(inp, sub_id, NULL)) {
bind_sub(client, inp, 3U, cancellable, cb, user_data);
sent = 1;
}
inp_unref(inp);
return sent;
}
static void finish_port_bind_ctx(WdsPortBindCtx *ctx) {
void *cb_source = ctx->port_source ? ctx->port_source : ctx->client;
if (ctx->orig_cb) {
ctx->orig_cb(cb_source, ctx->orig_res, ctx->orig_ud);
}
unref_gobj(ctx->orig_res);
unref_gobj(ctx->port_source);
unref_gobj(ctx->cancellable);
unref_gobj(ctx->client);
free(ctx);
}
static void on_sub_after_port_done(void *source, void *sub_res, void *user_data) {
WdsPortBindCtx *ctx = (WdsPortBindCtx *)user_data;
on_wds_bind_done(source, sub_res, NULL);
finish_port_bind_ctx(ctx);
}
static void on_port_bind_done(void *source, void *res, void *user_data) {
WdsPortBindCtx *ctx = (WdsPortBindCtx *)user_data;
ctx->port_source = ref_gobj(source);
ctx->orig_res = ref_gobj(res);
if (!send_wds_bind_sub(ctx->client, ctx->sub_id, ctx->cancellable,
on_sub_after_port_done, ctx)) {
finish_port_bind_ctx(ctx);
}
}
static void wrap_wds_port_bind(const char *sym_name, void *self, void *input,
unsigned int timeout, void *cancellable,
wds_async_cb_fn callback, void *user_data) {
qmi_wds_port_bind_fn real_fn = (qmi_wds_port_bind_fn)dlsym(RTLD_NEXT, sym_name);
if (!real_fn) {
return;
}
unsigned int sub_id = resolve_wds_sub_id();
if (!self || !callback || sub_id == 0U) {
real_fn(self, input, timeout, cancellable, callback, user_data);
return;
}
WdsPortBindCtx *ctx = (WdsPortBindCtx *)calloc(1, sizeof(*ctx));
if (!ctx) {
real_fn(self, input, timeout, cancellable, callback, user_data);
return;
}
ctx->client = ref_gobj(self);
ctx->cancellable = ref_gobj(cancellable);
ctx->orig_cb = callback;
ctx->orig_ud = user_data;
ctx->sub_id = sub_id;
real_fn(self, input, timeout, cancellable, on_port_bind_done, ctx);
}
void qmi_client_wds_bind_mux_data_port(void *self, void *input, unsigned int timeout,
void *cancellable, wds_async_cb_fn callback,
void *user_data) {
wrap_wds_port_bind("qmi_client_wds_bind_mux_data_port", self, input, timeout,
cancellable, callback, user_data);
}
void qmi_client_wds_bind_data_port(void *self, void *input, unsigned int timeout,
void *cancellable, wds_async_cb_fn callback,
void *user_data) {
wrap_wds_port_bind("qmi_client_wds_bind_data_port", self, input, timeout,
cancellable, callback, user_data);
}
void *qmi_device_allocate_client_finish(void *self, void *res, void **error) {
qmi_alloc_finish_fn real_fn =
(qmi_alloc_finish_fn)dlsym(RTLD_NEXT, "qmi_device_allocate_client_finish");
if (!real_fn) {
return NULL;
}
void *client = real_fn(self, res, error);
if (!client) {
return NULL;
}
unsigned int sub_id = resolve_wds_sub_id();
if (sub_id == 0U) {
return client;
}
qmi_get_svc_fn get_svc =
(qmi_get_svc_fn)dlsym(RTLD_DEFAULT, "qmi_client_get_service");
if (!get_svc || get_svc(client) != QMI_SVC_WDS) {
return client;
}
send_wds_bind_sub(client, sub_id, NULL, on_wds_bind_done, NULL);
return client;
}
+465
View File
@@ -0,0 +1,465 @@
#ifndef BANANARCHY_AMR_RTP_H
#define BANANARCHY_AMR_RTP_H
/* Runtime dlopen AMR-NB / AMR-WB codec bridge + RFC 4867 octet-aligned and
* bandwidth-efficient RTP payload packer/unpacker for VoWiFi, VoLTE, and xsip. */
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstring>
#include <dlfcn.h>
#include <vector>
namespace ba_amr {
/* Core speech bit counts per FT (modes 0..15). -1 = invalid/reserved, 0 = NO_DATA. */
inline int amrNbSpeechBits(uint8_t ft) {
static constexpr int kBits[16] = {
95, 103, 118, 134, 148, 159, 204, 244, 39, -1, -1, -1, -1, -1, -1, 0
};
return (ft < 16) ? kBits[ft] : -1;
}
inline int amrWbSpeechBits(uint8_t ft) {
static constexpr int kBits[16] = {
132, 177, 253, 285, 317, 365, 397, 461, 477, 40, -1, -1, -1, -1, 0, 0
};
return (ft < 16) ? kBits[ft] : -1;
}
inline int amrSpeechBits(bool wideband, uint8_t ft) {
return wideband ? amrWbSpeechBits(ft) : amrNbSpeechBits(ft);
}
struct BitWriter {
std::vector<uint8_t> bytes;
int bitPos = 0;
void writeBit(uint8_t b) {
if ((bitPos & 7) == 0) {
bytes.push_back(0);
}
if (b & 1U) {
bytes[bitPos >> 3] |= static_cast<uint8_t>(0x80U >> (bitPos & 7));
}
bitPos++;
}
void writeBits(uint32_t v, int count) {
for (int i = count - 1; i >= 0; --i) {
writeBit(static_cast<uint8_t>((v >> i) & 1U));
}
}
void writeBytesMsbBits(const uint8_t* src, int numBits) {
for (int i = 0; i < numBits; ++i) {
uint8_t bit = (src[i >> 3] >> (7 - (i & 7))) & 1U;
writeBit(bit);
}
}
void alignByte() {
while ((bitPos & 7) != 0) {
writeBit(0);
}
}
};
struct BitReader {
const uint8_t* data = nullptr;
int totalBits = 0;
int bitPos = 0;
bool hasBits(int count) const { return (bitPos + count) <= totalBits; }
uint32_t readBits(int count) {
uint32_t v = 0;
for (int i = 0; i < count; ++i) {
v <<= 1;
if (bitPos < totalBits) {
uint8_t b = (data[bitPos >> 3] >> (7 - (bitPos & 7))) & 1U;
v |= b;
}
bitPos++;
}
return v;
}
void readToBytesMsb(int numBits, std::vector<uint8_t>& dst, size_t dstOffset) {
int nbytes = (numBits + 7) / 8;
if (dst.size() < dstOffset + static_cast<size_t>(nbytes)) {
dst.resize(dstOffset + static_cast<size_t>(nbytes), 0);
}
for (int i = 0; i < numBits; ++i) {
uint8_t bit = static_cast<uint8_t>(readBits(1));
if (bit) {
dst[dstOffset + static_cast<size_t>(i >> 3)] |=
static_cast<uint8_t>(0x80U >> (i & 7));
}
}
}
};
/* Pack single IF1 encoded frame (byte0=[P FT Q P], followed by speech bytes) into RFC 4867. */
inline std::vector<uint8_t> packRfc4867(bool wideband, bool octetAligned, uint8_t cmr,
const uint8_t* if1, size_t if1Len) {
std::vector<uint8_t> out;
if (!if1 || if1Len < 1) {
return out;
}
uint8_t ft = static_cast<uint8_t>((if1[0] >> 3) & 0x0FU);
uint8_t q = static_cast<uint8_t>((if1[0] >> 2) & 0x01U);
int bits = amrSpeechBits(wideband, ft);
if (bits < 0) {
return out;
}
size_t needSpeechBytes = static_cast<size_t>((bits + 7) / 8);
if (if1Len < 1U + needSpeechBytes) {
return out;
}
if (octetAligned) {
out.reserve(2U + needSpeechBytes);
out.push_back(static_cast<uint8_t>((cmr & 0x0FU) << 4));
out.push_back(static_cast<uint8_t>(((ft & 0x0FU) << 3) | ((q & 0x01U) << 2)));
for (size_t i = 0; i < needSpeechBytes; ++i) {
out.push_back(if1[1U + i]);
}
if (bits > 0 && (bits & 7) != 0) {
uint8_t mask = static_cast<uint8_t>(0xFFU << (8 - (bits & 7)));
out.back() &= mask;
}
return out;
}
BitWriter bw;
bw.writeBits(cmr & 0x0FU, 4);
bw.writeBit(0); /* F = 0 (last frame) */
bw.writeBits(ft & 0x0FU, 4);
bw.writeBit(q & 0x01U);
if (bits > 0) {
bw.writeBytesMsbBits(if1 + 1, bits);
}
return bw.bytes;
}
/* Unpack RFC 4867 RTP payload into IF1 frame(s) ready for opencore decoder. */
inline std::vector<std::vector<uint8_t>> unpackRfc4867(bool wideband, bool octetAligned,
const uint8_t* pkt, size_t pktLen,
uint8_t* outCmr = nullptr) {
std::vector<std::vector<uint8_t>> frames;
if (!pkt || pktLen < 2) {
return frames;
}
struct TocEntry {
uint8_t f;
uint8_t ft;
uint8_t q;
};
std::vector<TocEntry> tocs;
if (octetAligned) {
if (outCmr) {
*outCmr = static_cast<uint8_t>((pkt[0] >> 4) & 0x0FU);
}
size_t pos = 1;
while (pos < pktLen) {
uint8_t b = pkt[pos++];
TocEntry e{};
e.f = static_cast<uint8_t>((b >> 7) & 0x01U);
e.ft = static_cast<uint8_t>((b >> 3) & 0x0FU);
e.q = static_cast<uint8_t>((b >> 2) & 0x01U);
tocs.push_back(e);
if (e.f == 0 || tocs.size() >= 16) {
break;
}
}
for (const auto& e : tocs) {
int bits = amrSpeechBits(wideband, e.ft);
if (bits < 0) {
break;
}
size_t nbytes = static_cast<size_t>((bits + 7) / 8);
if (pos + nbytes > pktLen) {
break;
}
std::vector<uint8_t> if1(1U + nbytes, 0);
if1[0] = static_cast<uint8_t>(((e.ft & 0x0FU) << 3) | ((e.q & 0x01U) << 2));
if (nbytes > 0) {
std::memcpy(if1.data() + 1, pkt + pos, nbytes);
pos += nbytes;
}
frames.push_back(std::move(if1));
}
return frames;
}
/* Bandwidth-efficient mode */
BitReader br;
br.data = pkt;
br.totalBits = static_cast<int>(pktLen) * 8;
uint32_t cmr = br.readBits(4);
if (outCmr) {
*outCmr = static_cast<uint8_t>(cmr & 0x0FU);
}
while (br.hasBits(6)) {
TocEntry e{};
e.f = static_cast<uint8_t>(br.readBits(1));
e.ft = static_cast<uint8_t>(br.readBits(4));
e.q = static_cast<uint8_t>(br.readBits(1));
tocs.push_back(e);
if (e.f == 0 || tocs.size() >= 16) {
break;
}
}
for (const auto& e : tocs) {
int bits = amrSpeechBits(wideband, e.ft);
if (bits < 0 || !br.hasBits(bits)) {
break;
}
size_t nbytes = static_cast<size_t>((bits + 7) / 8);
std::vector<uint8_t> if1(1U + nbytes, 0);
if1[0] = static_cast<uint8_t>(((e.ft & 0x0FU) << 3) | ((e.q & 0x01U) << 2));
if (bits > 0) {
br.readToBytesMsb(bits, if1, 1);
}
frames.push_back(std::move(if1));
}
return frames;
}
class AmrLibraryLoader {
public:
using FnNbEncInit = void* (*)(int);
using FnNbEncExit = void (*)(void*);
using FnNbEncEncode = int (*)(void*, int, const short*, unsigned char*, int);
using FnNbDecInit = void* (*)();
using FnNbDecExit = void (*)(void*);
using FnNbDecDecode = void (*)(void*, const unsigned char*, short*, int);
using FnWbDecInit = void* (*)();
using FnWbDecExit = void (*)(void*);
using FnWbDecDecode = void (*)(void*, const unsigned char*, short*, int);
using FnWbEncInit = void* (*)();
using FnWbEncExit = void (*)(void*);
using FnWbEncEncode = int (*)(void*, int, const short*, unsigned char*, int);
FnNbEncInit nbEncInit = nullptr;
FnNbEncExit nbEncExit = nullptr;
FnNbEncEncode nbEncEncode = nullptr;
FnNbDecInit nbDecInit = nullptr;
FnNbDecExit nbDecExit = nullptr;
FnNbDecDecode nbDecDecode = nullptr;
FnWbDecInit wbDecInit = nullptr;
FnWbDecExit wbDecExit = nullptr;
FnWbDecDecode wbDecDecode = nullptr;
FnWbEncInit wbEncInit = nullptr;
FnWbEncExit wbEncExit = nullptr;
FnWbEncEncode wbEncEncode = nullptr;
static AmrLibraryLoader& instance() {
static AmrLibraryLoader inst;
return inst;
}
bool hasNbEnc() const { return nbEncInit && nbEncExit && nbEncEncode; }
bool hasNbDec() const { return nbDecInit && nbDecExit && nbDecDecode; }
bool hasWbDec() const { return wbDecInit && wbDecExit && wbDecDecode; }
bool hasWbEnc() const { return wbEncInit && wbEncExit && wbEncEncode; }
private:
void* hNb_ = nullptr;
void* hWbDec_ = nullptr;
void* hWbEnc_ = nullptr;
template <typename Fn>
static Fn loadSym(void* h, const char* name) {
return h ? reinterpret_cast<Fn>(dlsym(h, name)) : nullptr;
}
AmrLibraryLoader() {
hNb_ = dlopen("libopencore-amrnb.so.0", RTLD_LAZY | RTLD_LOCAL);
if (!hNb_) {
hNb_ = dlopen("libopencore-amrnb.so", RTLD_LAZY | RTLD_LOCAL);
}
if (hNb_) {
nbEncInit = loadSym<FnNbEncInit>(hNb_, "Encoder_Interface_init");
nbEncExit = loadSym<FnNbEncExit>(hNb_, "Encoder_Interface_exit");
nbEncEncode = loadSym<FnNbEncEncode>(hNb_, "Encoder_Interface_Encode");
nbDecInit = loadSym<FnNbDecInit>(hNb_, "Decoder_Interface_init");
nbDecExit = loadSym<FnNbDecExit>(hNb_, "Decoder_Interface_exit");
nbDecDecode = loadSym<FnNbDecDecode>(hNb_, "Decoder_Interface_Decode");
}
hWbDec_ = dlopen("libopencore-amrwb.so.0", RTLD_LAZY | RTLD_LOCAL);
if (!hWbDec_) {
hWbDec_ = dlopen("libopencore-amrwb.so", RTLD_LAZY | RTLD_LOCAL);
}
if (hWbDec_) {
wbDecInit = loadSym<FnWbDecInit>(hWbDec_, "D_IF_init");
wbDecExit = loadSym<FnWbDecExit>(hWbDec_, "D_IF_exit");
wbDecDecode = loadSym<FnWbDecDecode>(hWbDec_, "D_IF_decode");
}
hWbEnc_ = dlopen("libvo-amrwbenc.so.0", RTLD_LAZY | RTLD_LOCAL);
if (!hWbEnc_) {
hWbEnc_ = dlopen("libvo-amrwbenc.so", RTLD_LAZY | RTLD_LOCAL);
}
if (hWbEnc_) {
wbEncInit = loadSym<FnWbEncInit>(hWbEnc_, "E_IF_init");
wbEncExit = loadSym<FnWbEncExit>(hWbEnc_, "E_IF_exit");
wbEncEncode = loadSym<FnWbEncEncode>(hWbEnc_, "E_IF_encode");
}
}
~AmrLibraryLoader() = default;
};
class AmrCodecSession {
public:
AmrCodecSession() = default;
~AmrCodecSession() { close(); }
AmrCodecSession(const AmrCodecSession&) = delete;
AmrCodecSession& operator=(const AmrCodecSession&) = delete;
bool init(bool wideband) {
close();
wideband_ = wideband;
auto& ldr = AmrLibraryLoader::instance();
if (wideband_) {
if (ldr.hasWbEnc()) {
enc_ = ldr.wbEncInit();
}
if (ldr.hasWbDec()) {
dec_ = ldr.wbDecInit();
}
return (dec_ != nullptr || enc_ != nullptr);
}
if (ldr.hasNbEnc()) {
enc_ = ldr.nbEncInit(0);
}
if (ldr.hasNbDec()) {
dec_ = ldr.nbDecInit();
}
return (enc_ != nullptr && dec_ != nullptr);
}
void close() {
auto& ldr = AmrLibraryLoader::instance();
if (enc_) {
if (wideband_ && ldr.wbEncExit) {
ldr.wbEncExit(enc_);
} else if (!wideband_ && ldr.nbEncExit) {
ldr.nbEncExit(enc_);
}
enc_ = nullptr;
}
if (dec_) {
if (wideband_ && ldr.wbDecExit) {
ldr.wbDecExit(dec_);
} else if (!wideband_ && ldr.nbDecExit) {
ldr.nbDecExit(dec_);
}
dec_ = nullptr;
}
}
bool canEncode() const { return enc_ != nullptr; }
bool canDecode() const { return dec_ != nullptr; }
bool isWideband() const { return wideband_; }
/* Encode 320 samples (AMR-WB 16 kHz) or 160 samples (AMR-NB 8 kHz) into RFC 4867 RTP payload. */
std::vector<uint8_t> encodeRtp(const int16_t* pcm, size_t samples,
bool octetAligned, int mode = -1) {
std::vector<uint8_t> empty;
auto& ldr = AmrLibraryLoader::instance();
if (!enc_ || !pcm) {
return empty;
}
uint8_t if1[128];
int n = 0;
if (wideband_) {
if (samples < 320 || !ldr.wbEncEncode) {
return empty;
}
int m = (mode >= 0 && mode <= 8) ? mode : 8; /* 23.85 kbps default */
n = ldr.wbEncEncode(enc_, m, pcm, if1, 0);
} else {
if (samples < 160 || !ldr.nbEncEncode) {
return empty;
}
int m = (mode >= 0 && mode <= 7) ? mode : 7; /* 12.2 kbps MR122 default */
n = ldr.nbEncEncode(enc_, m, pcm, if1, 0);
}
if (n <= 0) {
return empty;
}
return packRfc4867(wideband_, octetAligned, 15, if1, static_cast<size_t>(n));
}
/* Decode RFC 4867 RTP payload into PCM samples (320/frame for WB, 160/frame for NB). */
std::vector<int16_t> decodeRtp(const uint8_t* rtpPayload, size_t len, bool octetAligned) {
std::vector<int16_t> pcm;
auto& ldr = AmrLibraryLoader::instance();
if (!dec_ || !rtpPayload || len < 2) {
return pcm;
}
auto frames = unpackRfc4867(wideband_, octetAligned, rtpPayload, len);
const size_t frameSamples = wideband_ ? 320U : 160U;
for (const auto& f : frames) {
if (f.empty()) {
continue;
}
uint8_t ft = static_cast<uint8_t>((f[0] >> 3) & 0x0FU);
if ((wideband_ && ft == 15) || (!wideband_ && ft == 15)) {
pcm.resize(pcm.size() + frameSamples, 0);
continue;
}
size_t cur = pcm.size();
pcm.resize(cur + frameSamples, 0);
if (wideband_ && ldr.wbDecDecode) {
ldr.wbDecDecode(dec_, f.data(), pcm.data() + cur, 0);
} else if (!wideband_ && ldr.nbDecDecode) {
ldr.nbDecDecode(dec_, f.data(), pcm.data() + cur, 0);
}
}
return pcm;
}
private:
bool wideband_ = false;
void* enc_ = nullptr;
void* dec_ = nullptr;
};
/* Linear 8k <-> 16k PCM helpers matching CallScreen/PulseAudio 16 kHz pipe. */
inline void resample8to16(const int16_t* in, size_t n8, std::vector<int16_t>& out) {
out.resize(n8 * 2);
for (size_t i = 0; i < n8; ++i) {
int16_t s0 = in[i];
int16_t s1 = (i + 1 < n8) ? in[i + 1] : s0;
out[i * 2] = s0;
out[i * 2 + 1] = static_cast<int16_t>((static_cast<int32_t>(s0) + s1) / 2);
}
}
inline void resample16to8(const int16_t* in, size_t n16, std::vector<int16_t>& out) {
size_t n8 = n16 / 2;
out.resize(n8);
for (size_t i = 0; i < n8; ++i) {
int32_t sum = static_cast<int32_t>(in[i * 2]) + static_cast<int32_t>(in[i * 2 + 1]);
out[i] = static_cast<int16_t>(sum / 2);
}
}
} // namespace ba_amr
#endif /* BANANARCHY_AMR_RTP_H */
File diff suppressed because it is too large. Load diff
+120 -1
View File
@@ -573,6 +573,9 @@ int callscreen_run_main(int argc, char** argv) {
std::string recordFileName; std::string recordFileName;
int lastRecordedSec = 0; int lastRecordedSec = 0;
int recordedClipCount = 0; int recordedClipCount = 0;
std::string imsCallTech;
pid_t ringbackPid = -1;
int64_t nextRingbackMs = 0;
bool visible = false; bool visible = false;
int64_t openStartMs = 0; int64_t openStartMs = 0;
@@ -622,12 +625,94 @@ int callscreen_run_main(int argc, char** argv) {
} }
runAsyncCmd(mute ? "pactl set-source-mute @DEFAULT_SOURCE@ 1 >/dev/null 2>&1" runAsyncCmd(mute ? "pactl set-source-mute @DEFAULT_SOURCE@ 1 >/dev/null 2>&1"
: "pactl set-source-mute @DEFAULT_SOURCE@ 0 >/dev/null 2>&1"); : "pactl set-source-mute @DEFAULT_SOURCE@ 0 >/dev/null 2>&1");
if (callId.rfind("vowifi:", 0) == 0 || callId.rfind("ims:", 0) == 0 ||
callId.rfind("vowifi_", 0) == 0 || callId.rfind("ims_", 0) == 0) {
char mcmd[128];
std::snprintf(mcmd, sizeof(mcmd),
"/usr/bin/bananarchy-imsctl call-mute %d >/dev/null 2>&1",
mute ? 1 : 0);
runAsyncCmd(mcmd);
}
statusNotice = mute ? "Microphone muted" : "Microphone unmuted"; statusNotice = mute ? "Microphone muted" : "Microphone unmuted";
statusNoticeUntilMs = nowMs() + 2000; statusNoticeUntilMs = nowMs() + 2000;
}; };
auto isImsUserspaceCall = [](const std::string& cid) -> bool {
return cid.rfind("vowifi:", 0) == 0 || cid.rfind("ims:", 0) == 0 ||
cid.rfind("vowifi_", 0) == 0 || cid.rfind("ims_", 0) == 0;
};
auto isImsStateActiveFlag = [](const char* key) -> bool {
const char* stPath = std::getenv("BANANARCHY_IMS_STATE_PATH");
std::ifstream in((stPath && stPath[0]) ? stPath : "/run/bananarchy/ims/state.env");
if (!in.is_open()) return false;
std::string line;
std::string prefix = std::string(key) + "=1";
while (std::getline(in, line)) {
if (line == prefix) return true;
}
return false;
};
auto stopComfortRingback = [&]() {
if (ringbackPid > 0) {
::kill(ringbackPid, SIGTERM);
::waitpid(ringbackPid, nullptr, WNOHANG);
ringbackPid = -1;
}
nextRingbackMs = 0;
};
auto tickComfortRingback = [&]() {
if (callState != CallState::Outgoing) {
if (ringbackPid > 0 || nextRingbackMs > 0) stopComfortRingback();
return;
}
bool needRingback = isImsUserspaceCall(callId) || isImsStateActiveFlag("VOLTE_ACTIVE");
if (!needRingback) return;
if (ringbackPid > 0) {
int st = 0;
pid_t w = ::waitpid(ringbackPid, &st, WNOHANG);
if (w == 0) return;
ringbackPid = -1;
}
int64_t now = nowMs();
if (nextRingbackMs > now) return;
nextRingbackMs = now + 4000;
int pfd[2] = {-1, -1};
if (::pipe(pfd) != 0) return;
pid_t pid = ::fork();
if (pid == 0) {
::close(pfd[1]);
::dup2(pfd[0], STDIN_FILENO);
::close(pfd[0]);
int dn = ::open("/dev/null", O_RDWR);
if (dn >= 0) {
::dup2(dn, STDOUT_FILENO);
::dup2(dn, STDERR_FILENO);
if (dn > 2) ::close(dn);
}
::execlp("aplay", "aplay", "-q", "-f", "S16_LE", "-r", "8000", "-c", "1", "-t", "raw",
static_cast<char*>(nullptr));
::_exit(0);
}
::close(pfd[0]);
if (pid > 0) {
ringbackPid = pid;
int16_t tone[8000];
for (int i = 0; i < 8000; ++i) {
double phase = 2.0 * 3.14159265358979 * 425.0 * static_cast<double>(i) / 8000.0;
tone[i] = static_cast<int16_t>(3800.0 * std::sin(phase));
}
ssize_t w = ::write(pfd[1], tone, sizeof(tone));
(void)w;
}
::close(pfd[1]);
};
auto isVoipCallId = [&](const std::string& cid) -> bool { auto isVoipCallId = [&](const std::string& cid) -> bool {
return cid.rfind("sip:", 0) == 0 || cid.rfind("tox:", 0) == 0 || return cid.rfind("sip:", 0) == 0 || cid.rfind("tox:", 0) == 0 ||
isImsUserspaceCall(cid) ||
activeSimSlot == 3 || activeSimSlot == 4; activeSimSlot == 3 || activeSimSlot == 4;
}; };
@@ -988,6 +1073,9 @@ int callscreen_run_main(int argc, char** argv) {
simTag = sipZrtpSas.empty() ? " [SIP]" : (" [ZRTP:" + sipZrtpSas + "]"); simTag = sipZrtpSas.empty() ? " [SIP]" : (" [ZRTP:" + sipZrtpSas + "]");
} else if (activeSimSlot == 4 || callId.rfind("tox:", 0) == 0) { } else if (activeSimSlot == 4 || callId.rfind("tox:", 0) == 0) {
simTag = " [TOX]"; simTag = " [TOX]";
} else if (!imsCallTech.empty()) {
int dispSim = (activeSimSlot == 1 || activeSimSlot == 2) ? activeSimSlot : 1;
simTag = " [SIM " + std::to_string(dispSim) + " " + imsCallTech + "]";
} else if (activeSimSlot == 1 || activeSimSlot == 2) { } else if (activeSimSlot == 1 || activeSimSlot == 2) {
simTag = " [SIM " + std::to_string(activeSimSlot) + "]"; simTag = " [SIM " + std::to_string(activeSimSlot) + "]";
} }
@@ -1448,6 +1536,7 @@ int callscreen_run_main(int argc, char** argv) {
}; };
auto stopRingingJobs = [&]() { auto stopRingingJobs = [&]() {
stopComfortRingback();
::unlink("/tmp/sxmo_call_ringing"); ::unlink("/tmp/sxmo_call_ringing");
runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; "
"killall -q -TERM bananarchy-melody pw-play mpv sxmo_vibrate >/dev/null 2>&1; " "killall -q -TERM bananarchy-melody pw-play mpv sxmo_vibrate >/dev/null 2>&1; "
@@ -1479,6 +1568,8 @@ int callscreen_run_main(int argc, char** argv) {
sendPluginCommand("sip", "CALL_ACCEPT " + cid); sendPluginCommand("sip", "CALL_ACCEPT " + cid);
} else if (cid.rfind("tox:", 0) == 0) { } else if (cid.rfind("tox:", 0) == 0) {
sendPluginCommand("tox", "CALL_ACCEPT " + cid); sendPluginCommand("tox", "CALL_ACCEPT " + cid);
} else if (isImsUserspaceCall(cid)) {
runAsyncArgv("/usr/bin/bananarchy-imsctl", "call-accept", cid.c_str());
} else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { } else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") {
runAsyncArgv("sxmo_modemcall.sh", "pickup", cid.c_str()); runAsyncArgv("sxmo_modemcall.sh", "pickup", cid.c_str());
} }
@@ -1496,7 +1587,8 @@ int callscreen_run_main(int argc, char** argv) {
sendPluginCommand("sip", "CALL_MUTE_RING " + cid); sendPluginCommand("sip", "CALL_MUTE_RING " + cid);
} else if (cid.rfind("tox:", 0) == 0) { } else if (cid.rfind("tox:", 0) == 0) {
sendPluginCommand("tox", "CALL_MUTE_RING " + cid); sendPluginCommand("tox", "CALL_MUTE_RING " + cid);
} else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { } else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test" &&
!isImsUserspaceCall(cid)) {
runAsyncArgv("sxmo_modemcall.sh", "mute", cid.c_str()); runAsyncArgv("sxmo_modemcall.sh", "mute", cid.c_str());
} }
statusNotice = "Ringtone silenced"; statusNotice = "Ringtone silenced";
@@ -1506,6 +1598,7 @@ int callscreen_run_main(int argc, char** argv) {
auto transitionToEnded = [&](const std::string& reason) { auto transitionToEnded = [&](const std::string& reason) {
bool wasIncoming = (callState == CallState::Incoming); bool wasIncoming = (callState == CallState::Incoming);
stopComfortRingback();
stopRecording(); stopRecording();
if (micMuted) { if (micMuted) {
setMicMuted(false); setMicMuted(false);
@@ -1734,6 +1827,9 @@ int callscreen_run_main(int argc, char** argv) {
sendPluginCommand("sip", "CALL_HANGUP " + cid); sendPluginCommand("sip", "CALL_HANGUP " + cid);
} else if (cid.rfind("tox:", 0) == 0 || activeSimSlot == 4) { } else if (cid.rfind("tox:", 0) == 0 || activeSimSlot == 4) {
sendPluginCommand("tox", "CALL_HANGUP " + cid); sendPluginCommand("tox", "CALL_HANGUP " + cid);
} else if (isImsUserspaceCall(cid)) {
runAsyncArgv("/usr/bin/bananarchy-imsctl", "call-hangup", cid.c_str());
runAsyncArgv("sxmo_modemcall.sh", "hangup", cid.c_str());
} else { } else {
hangupQmiVoiceCallsNow(); hangupQmiVoiceCallsNow();
std::string callsDir = getRuntimeFile("sxmo_calls"); std::string callsDir = getRuntimeFile("sxmo_calls");
@@ -1781,6 +1877,9 @@ int callscreen_run_main(int argc, char** argv) {
std::string cid = resolveActiveModemCallId(); std::string cid = resolveActiveModemCallId();
if (cid.rfind("sip:", 0) == 0) { if (cid.rfind("sip:", 0) == 0) {
sendPluginCommand("sip", std::string("CALL_DTMF ") + ch); sendPluginCommand("sip", std::string("CALL_DTMF ") + ch);
} else if (isImsUserspaceCall(cid)) {
char chStr[2] = {ch, '\0'};
runAsyncArgv("/usr/bin/bananarchy-imsctl", "call-dtmf", chStr, cid.c_str());
} else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test" && } else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test" &&
cid.rfind("tox:", 0) != 0) { cid.rfind("tox:", 0) != 0) {
if (cid.rfind("sub", 0) == 0) { if (cid.rfind("sub", 0) == 0) {
@@ -2282,6 +2381,7 @@ int callscreen_run_main(int argc, char** argv) {
} }
auto parseSimTag = [&](const std::string& cidStr, const std::string& tagStr) { auto parseSimTag = [&](const std::string& cidStr, const std::string& tagStr) {
imsCallTech.clear();
if (tagStr == "SIP" || tagStr.rfind("SIP:", 0) == 0 || if (tagStr == "SIP" || tagStr.rfind("SIP:", 0) == 0 ||
tagStr.rfind("SIP/", 0) == 0 || cidStr.rfind("sip:", 0) == 0) { tagStr.rfind("SIP/", 0) == 0 || cidStr.rfind("sip:", 0) == 0) {
activeSimSlot = 3; activeSimSlot = 3;
@@ -2298,6 +2398,23 @@ int callscreen_run_main(int argc, char** argv) {
activeSimSlot = 4; activeSimSlot = 4;
return; return;
} }
if (tagStr.rfind("VOWIFI", 0) == 0) {
imsCallTech = "VoWiFi";
activeSimSlot = (tagStr.size() > 6 && tagStr[6] == '2') ? 2 : 1;
return;
}
if (tagStr.rfind("VOLTE", 0) == 0) {
imsCallTech = "VoLTE";
activeSimSlot = (tagStr.size() > 5 && tagStr[5] == '2') ? 2 : 1;
return;
}
if (cidStr.rfind("vowifi:", 0) == 0 || cidStr.rfind("vowifi_", 0) == 0) {
imsCallTech = "VoWiFi";
} else if (cidStr.rfind("ims:", 0) == 0 || cidStr.rfind("ims_", 0) == 0) {
imsCallTech = "VoLTE";
} else if (isImsStateActiveFlag("VOLTE_REGISTERED")) {
imsCallTech = "VoLTE";
}
if (!simInfo.slot1Present && !simInfo.slot2Present) { if (!simInfo.slot1Present && !simInfo.slot2Present) {
simInfo = queryDualSimInfo(); simInfo = queryDualSimInfo();
} }
@@ -2427,6 +2544,7 @@ int callscreen_run_main(int argc, char** argv) {
} }
ringMuted = false; ringMuted = false;
selectedRow = 0; selectedRow = 0;
stopComfortRingback();
setSpeakerRoute(speakerOn, btAudioOn); setSpeakerRoute(speakerOn, btAudioOn);
statusNotice.clear(); statusNotice.clear();
statusNoticeUntilMs = 0; statusNoticeUntilMs = 0;
@@ -2801,6 +2919,7 @@ int callscreen_run_main(int argc, char** argv) {
} }
static int64_t lastTimerRenderMs = 0; static int64_t lastTimerRenderMs = 0;
tickComfortRingback();
bool hasLiveTimer = (callState == CallState::Outgoing || bool hasLiveTimer = (callState == CallState::Outgoing ||
callState == CallState::Active || callState == CallState::Active ||
checkRecordingAlive()); checkRecordingAlive());
+47
View File
@@ -265,6 +265,10 @@ bool isYabasicExt(const std::string& ext) {
return ext == "yab"; return ext == "yab";
} }
bool isMbnExt(const std::string& ext) {
return ext == "mbn";
}
bool isLikelyTextFile(const std::string& path, off_t size) { bool isLikelyTextFile(const std::string& path, off_t size) {
if (size == 0) return true; if (size == 0) return true;
if (size > 256 * 1024) return false; if (size > 256 * 1024) return false;
@@ -1083,6 +1087,9 @@ int runFilesApp(int argc, char** argv) {
} else if (isYabasicExt(ext) && !duress) { } else if (isYabasicExt(ext) && !duress) {
actionsList.push_back({1, kIconTerm, "Run in Yabasic (Terminal)"}); actionsList.push_back({1, kIconTerm, "Run in Yabasic (Terminal)"});
actionsList.push_back({17, kIconEye, "View Text"}); actionsList.push_back({17, kIconEye, "View Text"});
} else if (isMbnExt(ext) && !duress) {
actionsList.push_back({26, kIconSim, "Install IMS Profile (.mbn)"});
actionsList.push_back({27, kIconInfo, "Inspect IMS Profile"});
} else { } else {
actionsList.push_back({1, kIconEye, "Open / View"}); actionsList.push_back({1, kIconEye, "Open / View"});
} }
@@ -1205,6 +1212,10 @@ int runFilesApp(int argc, char** argv) {
} else if (isYabasicExt(ext)) { } else if (isYabasicExt(ext)) {
runYabasicInTerminal(item.fullPath); runYabasicInTerminal(item.fullPath);
return; return;
} else if (isMbnExt(ext) && !isDuressMode()) {
buildActionsList();
mode = ViewMode::Actions;
return;
} else if (isMediaExt(ext)) { } else if (isMediaExt(ext)) {
hideWindow(); hideWindow();
runAsyncArgv("sxmo_open.sh", item.fullPath.c_str()); runAsyncArgv("sxmo_open.sh", item.fullPath.c_str());
@@ -1321,6 +1332,9 @@ int runFilesApp(int argc, char** argv) {
} else if (isGameBoyExt(ext) || isJ2meExt(ext)) { } else if (isGameBoyExt(ext) || isJ2meExt(ext)) {
ic = kIconGamepad; ic = kIconGamepad;
icCol = &colYellow; icCol = &colYellow;
} else if (isMbnExt(ext)) {
ic = kIconSim;
icCol = &colGreen;
} else if (isYabasicExt(ext) || it.isExec || ext == "sh") { } else if (isYabasicExt(ext) || it.isExec || ext == "sh") {
ic = kIconTerm; ic = kIconTerm;
icCol = &colOrange; icCol = &colOrange;
@@ -2275,6 +2289,39 @@ int runFilesApp(int argc, char** argv) {
btTargets = queryBtSendTargets(false); btTargets = queryBtSendTargets(false);
btTargetSel = 0; btTargetSel = 0;
mode = ViewMode::BtSendModal; mode = ViewMode::BtSendModal;
} else if (actId == 26 && !filteredItems.empty() && !isDuressMode()) {
const auto& item = filteredItems[selected];
int rc = -1;
std::string out = trimStr(runCaptureCmd(
"doas -n /usr/bin/bananarchy-imsctl profile install " +
shellQuote(item.fullPath) + " --activate 2>&1", &rc));
statusBanner = (rc == 0) ? ("IMS profile installed: " + item.name)
: ("MBN install failed" + (out.empty() ? "" : (": " + out)));
statusBannerUntilMs = nowMs() + 2600;
mode = ViewMode::Browser;
} else if (actId == 27 && !filteredItems.empty() && !isDuressMode()) {
const auto& item = filteredItems[selected];
int rc = 0;
std::string out = runCaptureCmd(
"/usr/bin/bananarchy-imsctl profile inspect " +
shellQuote(item.fullPath) + " 2>&1", &rc);
viewingFilePath = item.fullPath;
viewingFileName = item.name;
textLines.clear();
textScrollLine = 0;
std::istringstream iss(out.empty() ? "Unable to inspect MBN." : out);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.empty()) {
textLines.push_back("");
} else {
for (size_t pos = 0; pos < line.size(); pos += 30) {
textLines.push_back(line.substr(pos, 30));
}
}
}
mode = ViewMode::TextView;
} }
}; };
+440 -9
View File
@@ -29,8 +29,9 @@ void handleSignal(int) {
enum class TabId { enum class TabId {
SimCards = 0, SimCards = 0,
RadioInfo = 1, RadioInfo = 1,
AtConsole = 2, ImsSettings = 2,
ModemLog = 3, AtConsole = 3,
ModemLog = 4,
}; };
enum class ModalMode { enum class ModalMode {
@@ -41,8 +42,98 @@ enum class ModalMode {
TogglePinLock = 4, TogglePinLock = 4,
ChangePin = 5, ChangePin = 5,
UssdDialog = 6, UssdDialog = 6,
ImsProfiles = 7,
ImsEpdg = 8,
}; };
struct ImsProfileEntry {
std::string id;
bool active = false;
bool isSw = true;
bool imsCapable = false;
std::string version;
std::string plmns;
std::string description;
};
struct ImsUiState {
std::string volteMode = "auto";
std::string vowifiMode = "auto";
std::string volteBackend = "none";
bool volteActive = false;
bool volteRegistered = false;
bool network4gOnly = false;
std::string accessTech = "unknown";
bool vowifiActive = false;
bool vowifiRegistered = false;
int imsSimSlot = 1;
std::string wfcPreference = "cellular_preferred";
bool vowifiRoaming = false;
std::string imsApn = "ims";
std::string activeMbn;
std::string mbnDescription;
std::string epdgHost;
std::string lastError;
std::vector<ImsProfileEntry> profiles;
};
ImsUiState queryImsUiState() {
ImsUiState st;
if (isDuressMode()) {
return st;
}
int rc = 0;
std::string out = runCaptureCmd("/usr/bin/bananarchy-imsctl status 2>/dev/null", &rc);
std::istringstream iss(out);
std::string line;
while (std::getline(iss, line)) {
line = trimStr(line);
size_t eq = line.find('=');
if (eq == std::string::npos) continue;
std::string k = line.substr(0, eq);
std::string v = line.substr(eq + 1);
if (k == "VOLTE_MODE") st.volteMode = v;
else if (k == "VOWIFI_MODE") st.vowifiMode = v;
else if (k == "VOLTE_BACKEND") st.volteBackend = v;
else if (k == "VOLTE_ACTIVE") st.volteActive = (v == "1");
else if (k == "VOLTE_REGISTERED") st.volteRegistered = (v == "1");
else if (k == "NETWORK_4G_ONLY") st.network4gOnly = (v == "1");
else if (k == "ACCESS_TECH") st.accessTech = v;
else if (k == "VOWIFI_ACTIVE") st.vowifiActive = (v == "1");
else if (k == "VOWIFI_REGISTERED") st.vowifiRegistered = (v == "1");
else if (k == "IMS_SIM_SLOT") st.imsSimSlot = std::max(1, std::atoi(v.c_str()));
else if (k == "WFC_PREFERENCE") st.wfcPreference = v;
else if (k == "VOWIFI_ROAMING") st.vowifiRoaming = (v == "1");
else if (k == "IMS_APN" && !v.empty()) st.imsApn = v;
else if (k == "ACTIVE_MBN") st.activeMbn = v;
else if (k == "MBN_DESCRIPTION") st.mbnDescription = v;
else if (k == "EPDG_HOST") st.epdgHost = v;
else if (k == "LAST_ERROR") st.lastError = v;
}
std::string plist = runCaptureCmd("/usr/bin/bananarchy-imsctl profile list --tsv 2>/dev/null", &rc);
std::istringstream piss(plist);
while (std::getline(piss, line)) {
line = trimStr(line);
if (line.empty()) continue;
std::vector<std::string> cols;
std::stringstream ss(line);
std::string col;
while (std::getline(ss, col, '\t')) cols.push_back(col);
if (cols.size() >= 7) {
ImsProfileEntry e;
e.id = cols[0];
e.active = (cols[1] == "1");
e.isSw = (cols[2] == "SW");
e.imsCapable = (cols[3] == "1");
e.version = cols[4];
e.plmns = cols[5];
e.description = cols[6];
st.profiles.push_back(std::move(e));
}
}
return st;
}
struct SimSlotInfo { struct SimSlotInfo {
int slotNum = 1; int slotNum = 1;
std::string state = "absent"; // present, absent, error std::string state = "absent"; // present, absent, error
@@ -553,6 +644,7 @@ int runModemApp(int argc, char** argv) {
ContactBook book; ContactBook book;
ModemStatusData status; ModemStatusData status;
ImsUiState imsState;
std::vector<ModemLogRow> logRows; std::vector<ModemLogRow> logRows;
TabId activeTab = TabId::SimCards; TabId activeTab = TabId::SimCards;
@@ -560,6 +652,11 @@ int runModemApp(int argc, char** argv) {
int simRowSel = 0; // 0 = SIM 1, 1 = SIM 2, 2 = Switch Active, 3 = Unlock PIN/PUK, 4 = PIN Lock Toggle, 5 = Change PIN int simRowSel = 0; // 0 = SIM 1, 1 = SIM 2, 2 = Switch Active, 3 = Unlock PIN/PUK, 4 = PIN Lock Toggle, 5 = Change PIN
int radioRowSel = 0; // 0 = Network Mode, 1 = USSD, 2 = Modem Power, 3 = Restart MM, 4 = Refresh int radioRowSel = 0; // 0 = Network Mode, 1 = USSD, 2 = Modem Power, 3 = Restart MM, 4 = Refresh
int imsRowSel = 0;
int imsProfSel = 0;
int imsEpdgField = 0; // 0 = ePDG server, 1 = IMS APN
std::string imsEpdgInput;
std::string imsApnInput = "ims";
int logRowSel = 0; int logRowSel = 0;
int actionSel = 0; int actionSel = 0;
int targetSlot = 1; int targetSlot = 1;
@@ -613,6 +710,7 @@ int runModemApp(int argc, char** argv) {
auto refreshData = [&](bool reloadLog = false) { auto refreshData = [&](bool reloadLog = false) {
status = queryModemAndSimStatus(); status = queryModemAndSimStatus();
imsState = queryImsUiState();
int64_t now = nowMs(); int64_t now = nowMs();
if (lastUnlockSuccessMs > 0 && (now - lastUnlockSuccessMs) < 30000) { if (lastUnlockSuccessMs > 0 && (now - lastUnlockSuccessMs) < 30000) {
for (int i = 0; i < 2; ++i) { for (int i = 0; i < 2; ++i) {
@@ -707,6 +805,8 @@ int runModemApp(int argc, char** argv) {
activeTab = TabId::ModemLog; activeTab = TabId::ModemLog;
book.load(); book.load();
logRows = loadRecentModemLog(book); logRows = loadRecentModemLog(book);
} else if (a == "ims" || a == "volte" || a == "vowifi") {
activeTab = TabId::ImsSettings;
} else if (a == "at" || a == "atcmd") { } else if (a == "at" || a == "atcmd") {
activeTab = TabId::AtConsole; activeTab = TabId::AtConsole;
} else if (a == "ussd") { } else if (a == "ussd") {
@@ -764,9 +864,9 @@ int runModemApp(int argc, char** argv) {
XSetForeground(dpy, gc, pt.spec.border); XSetForeground(dpy, gc, pt.spec.border);
XDrawLine(dpy, pix, gc, 0, 29, kWinWidth, 29); XDrawLine(dpy, pix, gc, 0, 29, kWinWidth, 29);
const char* tabLabels[4] = {"1:SIMs", "2:Radio", "3:AT", "4:Log"}; const char* tabLabels[5] = {"1:SIM", "2:Rad", "3:IMS", "4:AT", "5:Log"};
int tabW = kWinWidth / 4; int tabW = kWinWidth / 5;
for (int t = 0; t < 4; ++t) { for (int t = 0; t < 5; ++t) {
bool isSel = (static_cast<int>(activeTab) == t); bool isSel = (static_cast<int>(activeTab) == t);
if (isSel) { if (isSel) {
XSetForeground(dpy, gc, pt.spec.selBg); XSetForeground(dpy, gc, pt.spec.selBg);
@@ -996,6 +1096,59 @@ int runModemApp(int argc, char** argv) {
} }
drawSoftkeyBar("Refresh", "Apply", "Close"); drawSoftkeyBar("Refresh", "Apply", "Close");
} else if (activeTab == TabId::ImsSettings) {
XSetForeground(dpy, gc, pt.spec.bgAltEven);
XFillRectangle(dpy, pix, gc, 4, contentY, kWinWidth - 8, 66);
XSetForeground(dpy, gc, pt.spec.border);
XDrawRectangle(dpy, pix, gc, 4, contentY, kWinWidth - 9, 65);
std::string vSt = imsState.volteRegistered ? "REG" : (imsState.volteActive ? "ACT" : "IDLE");
std::string wSt = imsState.vowifiRegistered ? "REG" : (imsState.vowifiActive ? "TUN" : "IDLE");
XftColor* imsCol = (imsState.vowifiRegistered || imsState.volteRegistered)
? &colGreen
: ((imsState.vowifiActive || imsState.volteActive) ? &colYellow : &colMuted);
drawPango(layoutSmall, imsCol, 10, contentY + 2, 18,
"VoLTE: " + vSt + " | VoWiFi: " + wSt, 220);
std::string netLine = "Tech: " + imsState.accessTech +
" | 4G-only: " + (imsState.network4gOnly ? "YES" : "NO");
drawPango(layoutSmall, &colLight, 10, contentY + 22, 18, netLine, 220);
std::string mbnStr = imsState.mbnDescription.empty()
? (imsState.activeMbn.empty() ? "Default (None)" : imsState.activeMbn)
: imsState.mbnDescription;
drawPango(layoutSmall, &colMuted, 10, contentY + 42, 18,
"MBN: " + mbnStr + " | SIM " + std::to_string(imsState.imsSimSlot), 220);
auto fmtMode = [](const std::string& m) -> std::string {
if (m == "auto") return "Auto (4G-only)";
if (m == "on") return "Always ON";
return "Disabled (OFF)";
};
std::string imsRows[8] = {
std::string(kIconSignal) + " VoLTE: " + fmtMode(imsState.volteMode),
std::string(kIconWifi) + " VoWiFi: " + fmtMode(imsState.vowifiMode),
std::string(kIconSliders) + " Backend: " + imsState.volteBackend,
std::string(kIconPhone) + " WFC Pref: " + imsState.wfcPreference,
std::string(kIconSim) + " IMS SIM Slot: SIM " + std::to_string(imsState.imsSimSlot),
std::string(kIconShield) + " VoWiFi Roam: " + (imsState.vowifiRoaming ? "ON" : "OFF"),
std::string(kIconInfo) + " MBN Profiles (" + std::to_string(imsState.profiles.size()) + ")...",
std::string(kIconRefresh) + " ePDG / APN Settings...",
};
const int rowH = 26;
const int maxVis = 6;
int startIdx = std::clamp(imsRowSel - maxVis / 2, 0, 8 - maxVis);
int baseY = contentY + 70;
for (int i = 0; i < maxVis && (startIdx + i) < 8; ++i) {
int r = startIdx + i;
int ry = baseY + i * rowH;
bool isSel = (imsRowSel == r);
XSetForeground(dpy, gc, isSel ? pt.spec.selBg : ((r % 2 == 0) ? pt.spec.bgAltEven : pt.spec.bgAltOdd));
XFillRectangle(dpy, pix, gc, 4, ry, kWinWidth - 8, rowH - 1);
drawPango(layoutSmall, isSel ? &colWhite : &colLight,
10, ry, rowH - 1, imsRows[r], kWinWidth - 20);
}
drawSoftkeyBar("Refresh", "Toggle", "Close");
} else if (activeTab == TabId::AtConsole) { } else if (activeTab == TabId::AtConsole) {
const char* modeBadge = "[ABC]"; const char* modeBadge = "[ABC]";
if (atTextMode == AtTextMode::Lower) modeBadge = "[abc]"; if (atTextMode == AtTextMode::Lower) modeBadge = "[abc]";
@@ -1279,6 +1432,63 @@ int runModemApp(int argc, char** argv) {
pango_layout_set_width(layoutSmall, -1); pango_layout_set_width(layoutSmall, -1);
drawSoftkeyBar("Send", "Send", "Close"); drawSoftkeyBar("Send", "Send", "Close");
} else if (modal == ModalMode::ImsProfiles) {
XSetForeground(dpy, gc, pt.spec.bgOverlay);
XFillRectangle(dpy, pix, gc, 8, 34, kWinWidth - 16, 224);
XSetForeground(dpy, gc, pt.spec.accent);
XDrawRectangle(dpy, pix, gc, 8, 34, kWinWidth - 17, 223);
drawPango(layoutMain, &colYellow, 14, 38, 22, "IMS Carrier MBN Profiles", kWinWidth - 28);
int totalRows = 2 + static_cast<int>(imsState.profiles.size());
int maxVis = 6;
int startIdx = std::clamp(imsProfSel - maxVis / 2, 0, std::max(0, totalRows - maxVis));
for (int i = 0; i < maxVis && (startIdx + i) < totalRows; ++i) {
int r = startIdx + i;
int ry = 64 + i * 29;
bool isSel = (imsProfSel == r);
XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgButton);
XFillRectangle(dpy, pix, gc, 14, ry, kWinWidth - 28, 26);
std::string txt;
XftColor* tc = isSel ? &colWhite : &colLight;
if (r == 0) {
txt = "Auto-Match Carrier PLMN";
} else if (r == 1) {
txt = std::string(imsState.activeMbn.empty() ? "* " : " ") + "Default (No MBN)";
} else {
const auto& pe = imsState.profiles[static_cast<size_t>(r - 2)];
txt = std::string(pe.active ? "* " : " ") +
(pe.description.empty() ? pe.id : pe.description) +
" (" + pe.plmns + ")";
if (pe.active) tc = &colGreen;
}
drawPango(layoutSmall, tc, 18, ry, 26, txt, kWinWidth - 36);
}
drawSoftkeyBar(imsProfSel >= 2 ? "Remove" : "Apply", "Select", "Back");
} else if (modal == ModalMode::ImsEpdg) {
XSetForeground(dpy, gc, pt.spec.bgOverlay);
XFillRectangle(dpy, pix, gc, 12, 42, kWinWidth - 24, 198);
XSetForeground(dpy, gc, pt.spec.accent);
XDrawRectangle(dpy, pix, gc, 12, 42, kWinWidth - 25, 197);
drawPango(layoutMain, &colYellow, 18, 46, 22, "ePDG Server & IMS APN", kWinWidth - 36);
drawPango(layoutSmall, &colMuted, 18, 74, 18, "ePDG Host (blank = auto):", kWinWidth - 36);
XSetForeground(dpy, gc, pt.spec.bgInput);
XFillRectangle(dpy, pix, gc, 18, 94, kWinWidth - 36, 26);
XSetForeground(dpy, gc, imsEpdgField == 0 ? pt.spec.accent : pt.spec.border);
XDrawRectangle(dpy, pix, gc, 18, 94, kWinWidth - 37, 25);
drawPango(layoutSmall, &colWhite, 22, 94, 26,
imsEpdgInput + (imsEpdgField == 0 ? "_" : ""), kWinWidth - 44);
drawPango(layoutSmall, &colMuted, 18, 128, 18, "IMS APN (default: ims):", kWinWidth - 36);
XSetForeground(dpy, gc, pt.spec.bgInput);
XFillRectangle(dpy, pix, gc, 18, 148, kWinWidth - 36, 26);
XSetForeground(dpy, gc, imsEpdgField == 1 ? pt.spec.accent : pt.spec.border);
XDrawRectangle(dpy, pix, gc, 18, 148, kWinWidth - 37, 25);
drawPango(layoutSmall, &colWhite, 22, 148, 26,
imsApnInput + (imsEpdgField == 1 ? "_" : ""), kWinWidth - 44);
drawPango(layoutSmall, &colMuted, 18, 184, 34,
"Install new .mbn files from Files Manager (xfiles).", kWinWidth - 36);
drawSoftkeyBar("Save", "Next", "Back");
} }
// Status Toast Banner // Status Toast Banner
@@ -1590,6 +1800,76 @@ int runModemApp(int argc, char** argv) {
XRaiseWindow(dpy, win); XRaiseWindow(dpy, win);
grabKeys(); grabKeys();
} }
} else if (modal == ModalMode::ImsEpdg) {
if (isDuressMode()) {
modal = ModalMode::None;
setBanner("Disabled in duress mode");
return;
}
int rc = 0;
std::string apnVal = trimStr(imsApnInput).empty() ? "ims" : trimStr(imsApnInput);
runCaptureCmd("doas -n /usr/bin/bananarchy-imsctl set epdg_server " +
shellQuote(trimStr(imsEpdgInput)) + " >/dev/null 2>&1", &rc);
runCaptureCmd("doas -n /usr/bin/bananarchy-imsctl set ims_apn " +
shellQuote(apnVal) + " >/dev/null 2>&1", &rc);
modal = ModalMode::None;
imsState = queryImsUiState();
setBanner(rc == 0 ? "IMS server settings saved" : "Failed saving IMS settings");
}
};
auto triggerImsRowAction = [&](int row) {
if (isDuressMode()) {
setBanner("Disabled in duress mode");
return;
}
auto runImsSet = [&](const std::string& key, const std::string& val,
const std::string& msg) {
int rc = -1;
runCaptureCmd("doas -n /usr/bin/bananarchy-imsctl set " +
shellQuote(key) + " " + shellQuote(val) + " >/dev/null 2>&1", &rc);
imsState = queryImsUiState();
setBanner(rc == 0 ? msg : "IMS update failed");
};
if (row == 0) {
std::string next = (imsState.volteMode == "auto")
? "on"
: ((imsState.volteMode == "on") ? "off" : "auto");
runImsSet("volte_mode", next, "VoLTE: " + next);
} else if (row == 1) {
std::string next = (imsState.vowifiMode == "auto")
? "on"
: ((imsState.vowifiMode == "on") ? "off" : "auto");
runImsSet("vowifi_mode", next, "VoWiFi: " + next);
} else if (row == 2) {
std::string next = (imsState.volteBackend == "baseband")
? "userspace"
: ((imsState.volteBackend == "userspace") ? "auto" : "baseband");
runImsSet("volte_backend", next, "Backend: " + next);
} else if (row == 3) {
std::string next = (imsState.wfcPreference == "cellular_preferred")
? "wifi_preferred"
: ((imsState.wfcPreference == "wifi_preferred")
? "wifi_only"
: "cellular_preferred");
runImsSet("wfc_preference", next, "WFC: " + next);
} else if (row == 4) {
std::string next = (imsState.imsSimSlot == 1) ? "2" : "1";
runImsSet("ims_sim_slot", next, "IMS SIM: Slot " + next);
} else if (row == 5) {
std::string next = imsState.vowifiRoaming ? "0" : "1";
runImsSet("vowifi_roaming", next,
std::string("VoWiFi Roaming: ") + (next == "1" ? "ON" : "OFF"));
} else if (row == 6) {
imsState = queryImsUiState();
imsProfSel = 0;
modal = ModalMode::ImsProfiles;
} else if (row == 7) {
int rc = 0;
imsEpdgInput = trimStr(runCaptureCmd("/usr/bin/bananarchy-imsctl get epdg_server 2>/dev/null", &rc));
imsApnInput = imsState.imsApn.empty() ? "ims" : imsState.imsApn;
imsEpdgField = 0;
modal = ModalMode::ImsEpdg;
} }
}; };
@@ -1607,6 +1887,10 @@ int runModemApp(int argc, char** argv) {
cmd += " >/dev/null 2>&1"; cmd += " >/dev/null 2>&1";
int rc = 0; int rc = 0;
runCaptureCmd(cmd, &rc); runCaptureCmd(cmd, &rc);
if (std::strstr(p.allowed, "4g") != nullptr ||
std::strstr(p.allowed, "3g") != nullptr) {
runCaptureCmd("doas -n /usr/libexec/msm-modem-uim-selection ensure-ps-domain >/dev/null 2>&1");
}
refreshData(false); refreshData(false);
setBanner(rc == 0 ? (std::string("Mode: ") + p.label) : "Mode change failed"); setBanner(rc == 0 ? (std::string("Mode: ") + p.label) : "Mode change failed");
}; };
@@ -1692,6 +1976,31 @@ int runModemApp(int argc, char** argv) {
setBanner("AT response received"); setBanner("AT response received");
}; };
auto applyImsProfileRow = [&]() {
if (isDuressMode()) {
modal = ModalMode::None;
setBanner("Disabled in duress mode");
return;
}
int rc = -1;
if (imsProfSel == 0) {
runCaptureCmd("doas -n /usr/bin/bananarchy-imsctl auto-match >/dev/null 2>&1", &rc);
imsState = queryImsUiState();
setBanner(rc == 0 ? "Matched carrier MBN" : "No carrier MBN match");
} else if (imsProfSel == 1) {
runCaptureCmd("doas -n /usr/bin/bananarchy-imsctl profile reset-default >/dev/null 2>&1", &rc);
imsState = queryImsUiState();
setBanner(rc == 0 ? "Reset to baseband default" : "Reset failed");
} else if (imsProfSel >= 2 &&
imsProfSel < 2 + static_cast<int>(imsState.profiles.size())) {
const auto& pe = imsState.profiles[static_cast<size_t>(imsProfSel - 2)];
runCaptureCmd("doas -n /usr/bin/bananarchy-imsctl profile select " +
shellQuote(pe.id) + " >/dev/null 2>&1", &rc);
imsState = queryImsUiState();
setBanner(rc == 0 ? ("Activated: " + pe.description) : "Activation failed");
}
};
auto handleLeftSoftkey = [&]() { auto handleLeftSoftkey = [&]() {
if (modal == ModalMode::SimActions) { if (modal == ModalMode::SimActions) {
int act = actionSel; int act = actionSel;
@@ -1731,6 +2040,26 @@ int runModemApp(int argc, char** argv) {
} }
return; return;
} }
if (modal == ModalMode::ImsProfiles) {
if (isDuressMode()) {
modal = ModalMode::None;
setBanner("Disabled in duress mode");
return;
}
int rc = -1;
if (imsProfSel >= 2 && imsProfSel < 2 + static_cast<int>(imsState.profiles.size())) {
const auto& pe = imsState.profiles[static_cast<size_t>(imsProfSel - 2)];
runCaptureCmd("doas -n /usr/bin/bananarchy-imsctl profile remove " +
shellQuote(pe.id) + " >/dev/null 2>&1", &rc);
imsState = queryImsUiState();
int maxIdx = 1 + static_cast<int>(imsState.profiles.size());
imsProfSel = std::min(imsProfSel, std::max(0, maxIdx));
setBanner(rc == 0 ? "Removed MBN profile" : "Remove failed");
} else {
applyImsProfileRow();
}
return;
}
if (modal != ModalMode::None) { if (modal != ModalMode::None) {
submitModalInput(); submitModalInput();
return; return;
@@ -1748,6 +2077,9 @@ int runModemApp(int argc, char** argv) {
} else if (activeTab == TabId::RadioInfo) { } else if (activeTab == TabId::RadioInfo) {
refreshData(false); refreshData(false);
setBanner("Modem status refreshed"); setBanner("Modem status refreshed");
} else if (activeTab == TabId::ImsSettings) {
refreshData(false);
setBanner("IMS status refreshed");
} else if (activeTab == TabId::AtConsole) { } else if (activeTab == TabId::AtConsole) {
executeAtCommand(); executeAtCommand();
} else if (activeTab == TabId::ModemLog) { } else if (activeTab == TabId::ModemLog) {
@@ -1775,12 +2107,22 @@ int runModemApp(int argc, char** argv) {
handleLeftSoftkey(); handleLeftSoftkey();
return; return;
} }
if (modal == ModalMode::ImsProfiles) {
applyImsProfileRow();
return;
}
if (modal == ModalMode::ImsEpdg) {
imsEpdgField = (imsEpdgField + 1) % 2;
return;
}
if (modal != ModalMode::None) { if (modal != ModalMode::None) {
submitModalInput(); submitModalInput();
return; return;
} }
if (activeTab == TabId::SimCards) { if (activeTab == TabId::SimCards) {
triggerSimRowAction(simRowSel); triggerSimRowAction(simRowSel);
} else if (activeTab == TabId::ImsSettings) {
triggerImsRowAction(imsRowSel);
} else if (activeTab == TabId::RadioInfo) { } else if (activeTab == TabId::RadioInfo) {
if (radioRowSel == 0) { if (radioRowSel == 0) {
applyRadioModePreset(status.modePresetIdx + 1); applyRadioModePreset(status.modePresetIdx + 1);
@@ -2089,7 +2431,85 @@ int runModemApp(int argc, char** argv) {
} }
} }
// Main View Navigation (4 tabs: 1:SIMs, 2:Radio, 3:AT, 4:Log) if (modal == ModalMode::ImsProfiles) {
int total = 2 + static_cast<int>(imsState.profiles.size());
if (sym == XK_Up || sym == XK_KP_Up) {
imsProfSel = (imsProfSel + total - 1) % std::max(1, total);
render();
} else if (sym == XK_Down || sym == XK_KP_Down) {
imsProfSel = (imsProfSel + 1) % std::max(1, total);
render();
} else if (sym == XK_Return || sym == XK_KP_Enter) {
handleEnterKey();
render();
}
continue;
}
if (modal == ModalMode::ImsEpdg) {
std::string& fld = (imsEpdgField == 0) ? imsEpdgInput : imsApnInput;
if (sym == XK_Up || sym == XK_KP_Up || sym == XK_Down || sym == XK_KP_Down) {
imsEpdgField = (imsEpdgField + 1) % 2;
atLastTapKey = -1;
render();
continue;
} else if (sym == XK_BackSpace || sym == XK_Delete) {
if (!fld.empty()) fld.pop_back();
atLastTapKey = -1;
render();
continue;
} else if (sym == XK_Return || sym == XK_KP_Enter) {
handleEnterKey();
render();
continue;
}
char kbuf[16]{};
int klen = XLookupString(&ev.xkey, kbuf, sizeof(kbuf) - 1, nullptr, nullptr);
if (klen == 1 && kbuf[0] >= 0x20 && kbuf[0] < 0x7f &&
!(kbuf[0] >= '0' && kbuf[0] <= '9')) {
if (fld.size() < 96) fld.push_back(kbuf[0]);
atLastTapKey = -1;
render();
continue;
}
char dchE = mapDialKey(sym, kc, ev.xkey.state);
if (dchE == '#') {
atTextMode = (atTextMode == AtTextMode::Num) ? AtTextMode::Lower : AtTextMode::Num;
atLastTapKey = -1;
render();
continue;
}
if (dchE == '*') {
if (fld.size() < 96) fld.push_back('.');
atLastTapKey = -1;
render();
continue;
}
if (dchE >= '0' && dchE <= '9') {
int digit = dchE - '0';
if (atTextMode == AtTextMode::Num) {
if (fld.size() < 96) fld.push_back(dchE);
atLastTapKey = -1;
} else {
const char* seq = kAtTapMap[digit];
int len = static_cast<int>(std::strlen(seq));
if (atLastTapKey == digit && (now - atLastTapMs) < 850 && !fld.empty()) {
atLastTapIdx = (atLastTapIdx + 1) % len;
fld.back() = static_cast<char>(std::tolower(static_cast<unsigned char>(seq[atLastTapIdx])));
} else if (fld.size() < 96) {
atLastTapKey = digit;
atLastTapIdx = 0;
fld.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(seq[0]))));
}
atLastTapMs = now;
}
render();
continue;
}
continue;
}
// Main View Navigation (5 tabs: 1:SIM, 2:Rad, 3:IMS, 4:AT, 5:Log)
if (dch == '1') { if (dch == '1') {
activeTab = TabId::SimCards; activeTab = TabId::SimCards;
render(); render();
@@ -2099,10 +2519,15 @@ int runModemApp(int argc, char** argv) {
render(); render();
continue; continue;
} else if (dch == '3') { } else if (dch == '3') {
activeTab = TabId::AtConsole; activeTab = TabId::ImsSettings;
imsState = queryImsUiState();
render(); render();
continue; continue;
} else if (dch == '4') { } else if (dch == '4') {
activeTab = TabId::AtConsole;
render();
continue;
} else if (dch == '5') {
activeTab = TabId::ModemLog; activeTab = TabId::ModemLog;
refreshData(true); refreshData(true);
render(); render();
@@ -2120,7 +2545,8 @@ int runModemApp(int argc, char** argv) {
atPresetIdx = (atPresetIdx + kNumAtPresets - 1) % kNumAtPresets; atPresetIdx = (atPresetIdx + kNumAtPresets - 1) % kNumAtPresets;
atInput = kAtPresets[atPresetIdx]; atInput = kAtPresets[atPresetIdx];
} else { } else {
activeTab = static_cast<TabId>((static_cast<int>(activeTab) + 3) % 4); activeTab = static_cast<TabId>((static_cast<int>(activeTab) + 4) % 5);
if (activeTab == TabId::ImsSettings) imsState = queryImsUiState();
if (activeTab == TabId::ModemLog) refreshData(true); if (activeTab == TabId::ModemLog) refreshData(true);
} }
render(); render();
@@ -2131,7 +2557,8 @@ int runModemApp(int argc, char** argv) {
atPresetIdx = (atPresetIdx + 1) % kNumAtPresets; atPresetIdx = (atPresetIdx + 1) % kNumAtPresets;
atInput = kAtPresets[atPresetIdx]; atInput = kAtPresets[atPresetIdx];
} else { } else {
activeTab = static_cast<TabId>((static_cast<int>(activeTab) + 1) % 4); activeTab = static_cast<TabId>((static_cast<int>(activeTab) + 1) % 5);
if (activeTab == TabId::ImsSettings) imsState = queryImsUiState();
if (activeTab == TabId::ModemLog) refreshData(true); if (activeTab == TabId::ModemLog) refreshData(true);
} }
render(); render();
@@ -2140,6 +2567,8 @@ int runModemApp(int argc, char** argv) {
simRowSel = (simRowSel + 6) % 7; simRowSel = (simRowSel + 6) % 7;
} else if (activeTab == TabId::RadioInfo) { } else if (activeTab == TabId::RadioInfo) {
radioRowSel = (radioRowSel + 4) % 5; radioRowSel = (radioRowSel + 4) % 5;
} else if (activeTab == TabId::ImsSettings) {
imsRowSel = (imsRowSel + 7) % 8;
} else if (activeTab == TabId::AtConsole) { } else if (activeTab == TabId::AtConsole) {
if (atFocusRow == 2 && atScrollLine > 0) { if (atFocusRow == 2 && atScrollLine > 0) {
--atScrollLine; --atScrollLine;
@@ -2155,6 +2584,8 @@ int runModemApp(int argc, char** argv) {
simRowSel = (simRowSel + 1) % 7; simRowSel = (simRowSel + 1) % 7;
} else if (activeTab == TabId::RadioInfo) { } else if (activeTab == TabId::RadioInfo) {
radioRowSel = (radioRowSel + 1) % 5; radioRowSel = (radioRowSel + 1) % 5;
} else if (activeTab == TabId::ImsSettings) {
imsRowSel = (imsRowSel + 1) % 8;
} else if (activeTab == TabId::AtConsole) { } else if (activeTab == TabId::AtConsole) {
if (atFocusRow == 2) { if (atFocusRow == 2) {
++atScrollLine; ++atScrollLine;
+40 -10
View File
@@ -2376,25 +2376,44 @@ int runNetworksApp(int argc, char** argv) {
modal = NetModal::None; modal = NetModal::None;
setBanner("Saving APN " + cleanApn + "..."); setBanner("Saving APN " + cleanApn + "...");
render(); render();
XFlush(dpy);
if (cellInfo.gsmConfigured && !cellInfo.gsmConName.empty()) { if (cellInfo.gsmConfigured && !cellInfo.gsmConName.empty()) {
runCaptureCmd("nmcli connection delete " + runCaptureCmd("nmcli connection delete " +
shellQuote(cellInfo.gsmConName) + " >/dev/null 2>&1"); shellQuote(cellInfo.gsmConName) + " >/dev/null 2>&1");
} }
std::string cmd = "nmcli connection add type gsm con-name " + std::string addCmd = "nmcli connection add type gsm con-name " +
shellQuote(cleanApn) + " ifname '*' apn " + shellQuote(cleanApn) + " ifname '*' apn " +
shellQuote(cleanApn) + shellQuote(cleanApn) +
" ipv4.method auto ipv6.method ignore" " ipv4.method auto ipv6.method ignore"
" connection.autoconnect yes"; " connection.autoconnect no";
if (!trimStr(apnUser).empty()) { if (!trimStr(apnUser).empty()) {
cmd += " gsm.username " + shellQuote(trimStr(apnUser)); addCmd += " gsm.username " + shellQuote(trimStr(apnUser));
} }
if (!trimStr(apnPass).empty()) { if (!trimStr(apnPass).empty()) {
cmd += " gsm.password " + shellQuote(trimStr(apnPass)); addCmd += " gsm.password " + shellQuote(trimStr(apnPass));
} }
cmd += " >/dev/null 2>&1 && nmcli connection up " + addCmd += " >/dev/null 2>&1";
shellQuote(cleanApn) + " >/dev/null 2>&1"; int addRc = 0;
runCaptureCmd(addCmd, &addRc);
setBanner("Connecting APN " + cleanApn + "...");
render();
XFlush(dpy);
std::string prepCmd = "doas -n /usr/libexec/msm-modem-uim-selection mobile-data-prep " +
shellQuote(cleanApn) + " " + shellQuote(trimStr(apnUser)) + " " +
shellQuote(trimStr(apnPass)) + " >/dev/null 2>&1";
runCaptureCmd(prepCmd);
int rc = 0; int rc = 0;
runCaptureCmd(cmd, &rc); if (addRc == 0) {
runCaptureCmd("nmcli --wait 30 connection up " +
shellQuote(cleanApn) + " >/dev/null 2>&1", &rc);
} else {
rc = addRc;
}
if (rc != 0) {
runCaptureCmd("doas -n /usr/libexec/msm-modem-uim-selection restore-dsds >/dev/null 2>&1");
}
refreshCurrentTab(false); refreshCurrentTab(false);
runAsyncCmd("sxmo_hook_statusbar.sh modem >/dev/null 2>&1"); runAsyncCmd("sxmo_hook_statusbar.sh modem >/dev/null 2>&1");
setBanner(rc == 0 ? ("Connected APN: " + cleanApn) : ("Saved APN: " + cleanApn)); setBanner(rc == 0 ? ("Connected APN: " + cleanApn) : ("Saved APN: " + cleanApn));
@@ -2675,15 +2694,26 @@ int runNetworksApp(int argc, char** argv) {
bool turnOn = !cellInfo.gsmActive; bool turnOn = !cellInfo.gsmActive;
setBanner(turnOn ? "Enabling Mobile Data..." : "Disabling Mobile Data..."); setBanner(turnOn ? "Enabling Mobile Data..." : "Disabling Mobile Data...");
render(); render();
XFlush(dpy);
if (turnOn) { if (turnOn) {
runCaptureCmd("nmcli connection modify " + runCaptureCmd("nmcli connection modify " +
shellQuote(cellInfo.gsmConName) + shellQuote(cellInfo.gsmConName) +
" ipv4.method auto ipv6.method ignore >/dev/null 2>&1"); " connection.autoconnect no ipv4.method auto ipv6.method ignore >/dev/null 2>&1");
runCaptureCmd("doas -n /usr/libexec/msm-modem-uim-selection mobile-data-prep " +
shellQuote(cellInfo.apn) + " " + shellQuote(cellInfo.username) +
" >/dev/null 2>&1");
}
int rc = 0;
runCaptureCmd(std::string("nmcli --wait 30 connection ") +
(turnOn ? "up " : "down ") +
shellQuote(cellInfo.gsmConName) + " >/dev/null 2>&1", &rc);
if (turnOn && rc != 0) {
runCaptureCmd("doas -n /usr/libexec/msm-modem-uim-selection restore-dsds >/dev/null 2>&1");
} }
runCaptureCmd("nmcli connection " + std::string(turnOn ? "up " : "down ") +
shellQuote(cellInfo.gsmConName) + " >/dev/null 2>&1");
refreshCurrentTab(false); refreshCurrentTab(false);
runAsyncCmd("sxmo_hook_statusbar.sh modem >/dev/null 2>&1"); runAsyncCmd("sxmo_hook_statusbar.sh modem >/dev/null 2>&1");
setBanner(turnOn ? (rc == 0 ? "Mobile Data connected" : "Mobile Data failed")
: "Mobile Data disabled");
} }
} else if (cellRowSel == 1) { } else if (cellRowSel == 1) {
apnName = cellInfo.apn; apnName = cellInfo.apn;
+77 -5
View File
@@ -11,6 +11,7 @@
// - NeoUI 3-tab interface: Dialer, Accounts, and Call History // - NeoUI 3-tab interface: Dialer, Accounts, and Call History
#include "../sxmo-dwm/dwm_plugin.h" #include "../sxmo-dwm/dwm_plugin.h"
#include "amr_rtp.h"
#include "net_tls.h" #include "net_tls.h"
#include "pjsip_media.h" #include "pjsip_media.h"
@@ -60,7 +61,9 @@ enum class SipCodecId {
Dvi4_8k = 6, // PT 5: IMA ADPCM (DVI4) 8 kHz (32 kbps + 4-byte state hdr) Dvi4_8k = 6, // PT 5: IMA ADPCM (DVI4) 8 kHz (32 kbps + 4-byte state hdr)
Dvi4_16k = 7, // PT 6: IMA ADPCM (DVI4) 16 kHz (64 kbps + 4-byte state hdr) Dvi4_16k = 7, // PT 6: IMA ADPCM (DVI4) 16 kHz (64 kbps + 4-byte state hdr)
L16_8k = 8, // PT 100: Uncompressed 16-bit big-endian PCM 8 kHz (128 kbps) L16_8k = 8, // PT 100: Uncompressed 16-bit big-endian PCM 8 kHz (128 kbps)
L16_16k = 9 // PT 102: Uncompressed 16-bit big-endian PCM 16 kHz (256 kbps) L16_16k = 9, // PT 102: Uncompressed 16-bit big-endian PCM 16 kHz (256 kbps)
AmrWb = 10, // PT 96: 3GPP AMR-WB 16 kHz wideband (RFC 4867)
AmrNb = 11 // PT 97: 3GPP AMR-NB 8 kHz (RFC 4867)
}; };
const char* codecShortName(SipCodecId id) { const char* codecShortName(SipCodecId id) {
@@ -75,6 +78,8 @@ const char* codecShortName(SipCodecId id) {
case SipCodecId::Dvi4_16k: return "DVI4-16K"; case SipCodecId::Dvi4_16k: return "DVI4-16K";
case SipCodecId::L16_8k: return "L16"; case SipCodecId::L16_8k: return "L16";
case SipCodecId::L16_16k: return "L16-16K"; case SipCodecId::L16_16k: return "L16-16K";
case SipCodecId::AmrWb: return "AMR-WB";
case SipCodecId::AmrNb: return "AMR";
} }
return "PCMU"; return "PCMU";
} }
@@ -87,6 +92,8 @@ int codecDefaultPt(SipCodecId id) {
case SipCodecId::Dvi4_16k: return 6; case SipCodecId::Dvi4_16k: return 6;
case SipCodecId::Pcma: return 8; case SipCodecId::Pcma: return 8;
case SipCodecId::G722: return 9; case SipCodecId::G722: return 9;
case SipCodecId::AmrWb: return 96;
case SipCodecId::AmrNb: return 97;
case SipCodecId::L16_8k: return 100; case SipCodecId::L16_8k: return 100;
case SipCodecId::L16_16k: return 102; case SipCodecId::L16_16k: return 102;
case SipCodecId::Opus: return 111; case SipCodecId::Opus: return 111;
@@ -101,6 +108,7 @@ int codecAudioSampleRate(SipCodecId id) {
case SipCodecId::G722: case SipCodecId::G722:
case SipCodecId::Dvi4_16k: case SipCodecId::Dvi4_16k:
case SipCodecId::L16_16k: case SipCodecId::L16_16k:
case SipCodecId::AmrWb:
return 16000; return 16000;
default: default:
return 8000; return 8000;
@@ -113,6 +121,7 @@ uint32_t codecRtpTimestampStep20ms(SipCodecId id) {
return 960; // RFC 7587: 48 kHz RTP clock -> 960 ticks per 20 ms return 960; // RFC 7587: 48 kHz RTP clock -> 960 ticks per 20 ms
case SipCodecId::Dvi4_16k: case SipCodecId::Dvi4_16k:
case SipCodecId::L16_16k: case SipCodecId::L16_16k:
case SipCodecId::AmrWb:
return 320; // 16 kHz RTP clock -> 320 ticks per 20 ms return 320; // 16 kHz RTP clock -> 320 ticks per 20 ms
case SipCodecId::G722: case SipCodecId::G722:
return 160; // RFC 3551 Section 4.5.2: G.722 uses 8 kHz RTP clock -> 160 ticks per 20 ms return 160; // RFC 3551 Section 4.5.2: G.722 uses 8 kHz RTP clock -> 160 ticks per 20 ms
@@ -133,7 +142,8 @@ std::string toUpperStr(std::string s) {
std::string normalizePreferredCodec(const std::string& raw) { std::string normalizePreferredCodec(const std::string& raw) {
std::string up = toUpperStr(trimStr(raw)); std::string up = toUpperStr(trimStr(raw));
if (up == "OPUS" || up == "G722" || up == "PCMU" || up == "PCMA" || if (up == "OPUS" || up == "G722" || up == "PCMU" || up == "PCMA" ||
up == "GSM" || up == "G726-32" || up == "DVI4" || up == "L16") { up == "GSM" || up == "G726-32" || up == "DVI4" || up == "L16" ||
up == "AMR-WB" || up == "AMR") {
return up; return up;
} }
return "AUTO"; return "AUTO";
@@ -141,7 +151,7 @@ std::string normalizePreferredCodec(const std::string& raw) {
std::string cyclePreferredCodec(const std::string& cur) { std::string cyclePreferredCodec(const std::string& cur) {
static const char* kList[] = { static const char* kList[] = {
"AUTO", "PCMU", "PCMA", "GSM", "OPUS", "G722", "G726-32", "DVI4", "L16" "AUTO", "PCMU", "PCMA", "GSM", "OPUS", "G722", "AMR-WB", "AMR", "G726-32", "DVI4", "L16"
}; };
std::string norm = normalizePreferredCodec(cur); std::string norm = normalizePreferredCodec(cur);
for (size_t i = 0; i < sizeof(kList) / sizeof(kList[0]); ++i) { for (size_t i = 0; i < sizeof(kList) / sizeof(kList[0]); ++i) {
@@ -1136,6 +1146,8 @@ bool codecMatchesPreference(SipCodecId id, const std::string& pref) {
std::string up = normalizePreferredCodec(pref); std::string up = normalizePreferredCodec(pref);
if (up == "OPUS") return id == SipCodecId::Opus; if (up == "OPUS") return id == SipCodecId::Opus;
if (up == "G722") return id == SipCodecId::G722; if (up == "G722") return id == SipCodecId::G722;
if (up == "AMR-WB") return id == SipCodecId::AmrWb;
if (up == "AMR") return id == SipCodecId::AmrNb;
if (up == "PCMU") return id == SipCodecId::Pcmu; if (up == "PCMU") return id == SipCodecId::Pcmu;
if (up == "PCMA") return id == SipCodecId::Pcma; if (up == "PCMA") return id == SipCodecId::Pcma;
if (up == "GSM") return id == SipCodecId::Gsm; if (up == "GSM") return id == SipCodecId::Gsm;
@@ -1149,6 +1161,8 @@ std::vector<SipCodecId> orderedCodecsForPreference(const std::string& pref) {
static const SipCodecId kDefaultOrder[] = { static const SipCodecId kDefaultOrder[] = {
SipCodecId::G722, SipCodecId::G722,
SipCodecId::Opus, SipCodecId::Opus,
SipCodecId::AmrWb,
SipCodecId::AmrNb,
SipCodecId::Pcmu, SipCodecId::Pcmu,
SipCodecId::Pcma, SipCodecId::Pcma,
SipCodecId::Gsm, SipCodecId::Gsm,
@@ -1159,13 +1173,19 @@ std::vector<SipCodecId> orderedCodecsForPreference(const std::string& pref) {
SipCodecId::L16_16k SipCodecId::L16_16k
}; };
std::vector<SipCodecId> out; std::vector<SipCodecId> out;
auto codecAvailable = [](SipCodecId c) {
auto& ldr = ba_amr::AmrLibraryLoader::instance();
if (c == SipCodecId::AmrWb) return ldr.hasWbDec() && ldr.hasWbEnc();
if (c == SipCodecId::AmrNb) return ldr.hasNbDec() && ldr.hasNbEnc();
return true;
};
for (SipCodecId c : kDefaultOrder) { for (SipCodecId c : kDefaultOrder) {
if (codecMatchesPreference(c, pref)) { if (codecAvailable(c) && codecMatchesPreference(c, pref)) {
out.push_back(c); out.push_back(c);
} }
} }
for (SipCodecId c : kDefaultOrder) { for (SipCodecId c : kDefaultOrder) {
if (!codecMatchesPreference(c, pref)) { if (codecAvailable(c) && !codecMatchesPreference(c, pref)) {
out.push_back(c); out.push_back(c);
} }
} }
@@ -1209,6 +1229,14 @@ std::string codecRtpmapLine(int pt, SipCodecId id) {
case SipCodecId::L16_16k: case SipCodecId::L16_16k:
oss << "L16/16000\r\n"; oss << "L16/16000\r\n";
break; break;
case SipCodecId::AmrWb:
oss << "AMR-WB/16000\r\n"
<< "a=fmtp:" << pt << " mode-set=0,1,2,3,4,5,6,7,8; octet-align=1\r\n";
break;
case SipCodecId::AmrNb:
oss << "AMR/8000\r\n"
<< "a=fmtp:" << pt << " octet-align=1\r\n";
break;
} }
return oss.str(); return oss.str();
} }
@@ -1303,6 +1331,10 @@ void parseSdpMedia(const std::string& msg, const std::string& preferredCodec,
outPtMap[pt] = SipCodecId::L16_16k; outPtMap[pt] = SipCodecId::L16_16k;
} else if (spec.rfind("L16/8000", 0) == 0) { } else if (spec.rfind("L16/8000", 0) == 0) {
outPtMap[pt] = SipCodecId::L16_8k; outPtMap[pt] = SipCodecId::L16_8k;
} else if (spec.rfind("AMR-WB/", 0) == 0) {
outPtMap[pt] = SipCodecId::AmrWb;
} else if (spec.rfind("AMR/", 0) == 0) {
outPtMap[pt] = SipCodecId::AmrNb;
} else { } else {
// Unknown dynamic codec on this PT: remove default assumption if dynamic // Unknown dynamic codec on this PT: remove default assumption if dynamic
if (pt >= 96) { if (pt >= 96) {
@@ -2187,6 +2219,10 @@ class RtpAudioSession {
G726_32State g726Dec; G726_32State g726Dec;
ImaAdpcmState dvi4Enc; ImaAdpcmState dvi4Enc;
ImaAdpcmState dvi4Dec; ImaAdpcmState dvi4Dec;
ba_amr::AmrCodecSession amrWbSession;
ba_amr::AmrCodecSession amrNbSession;
amrWbSession.init(true);
amrNbSession.init(false);
uint16_t seq = static_cast<uint16_t>(nowMs() & 0xffff); uint16_t seq = static_cast<uint16_t>(nowMs() & 0xffff);
uint32_t ts = static_cast<uint32_t>(nowMs() * 8); uint32_t ts = static_cast<uint32_t>(nowMs() * 8);
@@ -2310,6 +2346,24 @@ class RtpAudioSession {
pcmDecoded[decodedSamples++] = static_cast<int16_t>(be); pcmDecoded[decodedSamples++] = static_cast<int16_t>(be);
} }
break; break;
case SipCodecId::AmrWb:
if (amrWbSession.canDecode()) {
auto pcm = amrWbSession.decodeRtp(payload, payLen, true);
decodedSamples = std::min<size_t>(pcm.size(), 1920);
if (decodedSamples > 0) {
std::memcpy(pcmDecoded, pcm.data(), decodedSamples * sizeof(int16_t));
}
}
break;
case SipCodecId::AmrNb:
if (amrNbSession.canDecode()) {
auto pcm = amrNbSession.decodeRtp(payload, payLen, true);
decodedSamples = std::min<size_t>(pcm.size(), 1920);
if (decodedSamples > 0) {
std::memcpy(pcmDecoded, pcm.data(), decodedSamples * sizeof(int16_t));
}
}
break;
} }
if (decodedSamples > 0) { if (decodedSamples > 0) {
@@ -2480,6 +2534,24 @@ class RtpAudioSession {
} }
encBytes = frameSamples * 2; encBytes = frameSamples * 2;
break; break;
case SipCodecId::AmrWb:
if (amrWbSession.canEncode()) {
auto pl = amrWbSession.encodeRtp(pcmIn, frameSamples, true);
if (!pl.empty() && pl.size() <= 512) {
std::memcpy(pkt + 12, pl.data(), pl.size());
encBytes = pl.size();
}
}
break;
case SipCodecId::AmrNb:
if (amrNbSession.canEncode()) {
auto pl = amrNbSession.encodeRtp(pcmIn, frameSamples, true);
if (!pl.empty() && pl.size() <= 512) {
std::memcpy(pkt + 12, pl.data(), pl.size());
encBytes = pl.size();
}
}
break;
} }
if (encBytes > 0) { if (encBytes > 0) {
+519
View File
@@ -0,0 +1,519 @@
#ifndef BANANARCHY_VOWIFI_AKA_H
#define BANANARCHY_VOWIFI_AKA_H
/* 3GPP USIM/ISIM AKA authentication via QMI_UIM (serialized by uim_apdu.lock)
* plus standard AES-128 Milenage software engine for offline verification. */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <openssl/evp.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <string>
#include <sys/file.h>
#include <unistd.h>
#include <vector>
#include "../bananarchy-daemons/ims_mbn.h"
#include "../bananarchy-daemons/ims_qrtr.h"
namespace ba_vowifi {
struct SimIdentity {
std::string imsi;
std::string impi;
std::string impu;
std::string homeDomain;
std::string mcc;
std::string mnc;
};
struct AkaResult {
bool ok = false;
bool syncFailure = false;
std::vector<uint8_t> res;
std::vector<uint8_t> ck;
std::vector<uint8_t> ik;
std::vector<uint8_t> auts;
std::string error;
};
class ScopedUimLock {
public:
explicit ScopedUimLock(const std::string& stateDir) {
ims_mkdir_p(stateDir.c_str(), 0755);
std::string lockPath = stateDir + "/uim_apdu.lock";
fd_ = ::open(lockPath.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
if (fd_ >= 0) {
::flock(fd_, LOCK_EX);
}
}
~ScopedUimLock() {
if (fd_ >= 0) {
::flock(fd_, LOCK_UN);
::close(fd_);
}
}
ScopedUimLock(const ScopedUimLock&) = delete;
ScopedUimLock& operator=(const ScopedUimLock&) = delete;
private:
int fd_ = -1;
};
inline bool hexToBytes(const std::string& hex, std::vector<uint8_t>& out) {
out.clear();
if (hex.size() % 2 != 0) {
return false;
}
out.reserve(hex.size() / 2);
for (size_t i = 0; i < hex.size(); i += 2) {
unsigned int b = 0;
if (std::sscanf(hex.c_str() + i, "%2x", &b) != 1) {
return false;
}
out.push_back(static_cast<uint8_t>(b));
}
return true;
}
inline std::string bytesToHex(const uint8_t* p, size_t n) {
static constexpr char kHex[] = "0123456789abcdef";
std::string out;
out.reserve(n * 2);
for (size_t i = 0; i < n; ++i) {
out.push_back(kHex[(p[i] >> 4) & 0x0FU]);
out.push_back(kHex[p[i] & 0x0FU]);
}
return out;
}
inline bool aes128EcbBlock(const uint8_t key[16], const uint8_t in[16], uint8_t out[16]) {
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) {
return false;
}
int outl = 0, finl = 0;
bool ok = EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), nullptr, key, nullptr) == 1 &&
EVP_CIPHER_CTX_set_padding(ctx, 0) == 1 &&
EVP_EncryptUpdate(ctx, out, &outl, in, 16) == 1 &&
EVP_EncryptFinal_ex(ctx, out + outl, &finl) == 1;
EVP_CIPHER_CTX_free(ctx);
return ok;
}
/* 3GPP TS 35.206 Milenage core (compute OPc from K and OP if OP provided, else OP=0). */
inline void milenageComputeOpc(const uint8_t k[16], const uint8_t op[16], uint8_t opc[16]) {
uint8_t enc[16]{};
aes128EcbBlock(k, op, enc);
for (int i = 0; i < 16; ++i) {
opc[i] = enc[i] ^ op[i];
}
}
inline void milenageRotateXor(const uint8_t in[16], uint8_t rotBits, uint8_t cByte,
uint8_t out[16]) {
uint8_t rbytes = rotBits / 8;
for (int i = 0; i < 16; ++i) {
out[i] = in[(i + rbytes) & 15];
}
out[15] ^= cByte;
}
inline bool milenageAuthenticate(const uint8_t k[16], const uint8_t opc[16],
const uint8_t rand[16], const uint8_t autn[16],
uint64_t& sqnTracker, AkaResult& res) {
uint8_t temp[16]{};
uint8_t xbuf[16]{};
for (int i = 0; i < 16; ++i) xbuf[i] = rand[i] ^ opc[i];
if (!aes128EcbBlock(k, xbuf, temp)) {
res.error = "AES failed";
return false;
}
auto runRound = [&](uint8_t rotBits, uint8_t cByte, uint8_t out[16]) {
uint8_t shifted[16]{};
uint8_t tx[16]{};
for (int i = 0; i < 16; ++i) tx[i] = temp[i] ^ opc[i];
milenageRotateXor(tx, rotBits, cByte, shifted);
uint8_t enc[16]{};
aes128EcbBlock(k, shifted, enc);
for (int i = 0; i < 16; ++i) out[i] = enc[i] ^ opc[i];
};
uint8_t out2[16]{}, out3[16]{}, out4[16]{}, out5[16]{};
runRound(0, 1, out2); /* f2: RES [8..15], f5: AK [0..5] */
runRound(32, 2, out3); /* f3: CK [0..15] */
runRound(64, 4, out4); /* f4: IK [0..15] */
runRound(96, 8, out5); /* f5*: AK* [0..5] */
(void)out5;
uint8_t sqn[6]{};
for (int i = 0; i < 6; ++i) {
sqn[i] = autn[i] ^ out2[i];
}
uint8_t amf[2] = {autn[6], autn[7]};
uint8_t in1[16]{};
std::memcpy(in1, sqn, 6);
std::memcpy(in1 + 6, amf, 2);
std::memcpy(in1 + 8, sqn, 6);
std::memcpy(in1 + 14, amf, 2);
uint8_t in1Rot[16]{};
for (int i = 0; i < 16; ++i) xbuf[i] = in1[i] ^ opc[i];
milenageRotateXor(xbuf, 64, 0, in1Rot);
uint8_t out1[16]{};
for (int i = 0; i < 16; ++i) xbuf[i] = temp[i] ^ in1Rot[i];
aes128EcbBlock(k, xbuf, out1);
for (int i = 0; i < 16; ++i) out1[i] ^= opc[i];
/* Verify XMAC == AUTN[8..15] */
if (std::memcmp(out1, autn + 8, 8) != 0) {
res.error = "MAC verification failed";
return false;
}
/* Verify SQN freshness; if below tracker, return TS 33.102 AUTS */
uint64_t rxSqn = 0;
for (int i = 0; i < 6; ++i) {
rxSqn = (rxSqn << 8) | sqn[i];
}
if (rxSqn <= sqnTracker) {
/* Generate AUTS = (SQN_MS XOR AK*) || MAC-S */
uint8_t sqnMs[6]{};
uint64_t nextSqn = sqnTracker;
for (int i = 5; i >= 0; --i) {
sqnMs[i] = static_cast<uint8_t>(nextSqn & 0xFFU);
nextSqn >>= 8;
}
uint8_t amfZero[2] = {0, 0};
std::memcpy(in1, sqnMs, 6);
std::memcpy(in1 + 6, amfZero, 2);
std::memcpy(in1 + 8, sqnMs, 6);
std::memcpy(in1 + 14, amfZero, 2);
for (int i = 0; i < 16; ++i) xbuf[i] = in1[i] ^ opc[i];
milenageRotateXor(xbuf, 64, 0, in1Rot);
for (int i = 0; i < 16; ++i) xbuf[i] = temp[i] ^ in1Rot[i];
aes128EcbBlock(k, xbuf, out1);
for (int i = 0; i < 16; ++i) out1[i] ^= opc[i];
res.auts.resize(14);
for (int i = 0; i < 6; ++i) {
res.auts[i] = sqnMs[i] ^ out5[i];
}
std::memcpy(res.auts.data() + 6, out1 + 8, 8);
res.syncFailure = true;
res.ok = true;
return true;
}
sqnTracker = rxSqn;
res.res.assign(out2 + 8, out2 + 16);
res.ck.assign(out3, out3 + 16);
res.ik.assign(out4, out4 + 16);
res.ok = true;
return true;
}
class SimAkaClient {
public:
SimAkaClient(int simSlot, std::string stateDir)
: simSlot_(simSlot), stateDir_(std::move(stateDir)) {}
SimIdentity readIdentity(const ims_runtime_state& st, const ims_config& cfg) {
SimIdentity id;
const char* mMcc = std::getenv("BANANARCHY_MOCK_MCC");
const char* mMnc = std::getenv("BANANARCHY_MOCK_MNC");
const char* mImsi = std::getenv("BANANARCHY_MOCK_IMSI");
const char* mImpi = std::getenv("BANANARCHY_MOCK_IMPI");
const char* mImpu = std::getenv("BANANARCHY_MOCK_IMPU");
id.mcc = (mMcc && *mMcc) ? mMcc : (st.mcc[0] ? st.mcc : "240");
id.mnc = (mMnc && *mMnc) ? mMnc : (st.mnc[0] ? st.mnc : "01");
while (id.mcc.size() < 3) id.mcc = "0" + id.mcc;
std::string mnc3 = id.mnc;
while (mnc3.size() < 3) mnc3 = "0" + mnc3;
if (cfg.sip_realm[0]) {
id.homeDomain = cfg.sip_realm;
} else {
id.homeDomain = "ims.mnc" + mnc3 + ".mcc" + id.mcc + ".3gppnetwork.org";
}
id.imsi = (mImsi && *mImsi) ? mImsi : (id.mcc + id.mnc + "0000000001");
/* Attempt QMI_UIM EF_DOMAIN / EF_IMPI read on live hardware when not mocked. */
if (!mImpi && !std::getenv("BANANARCHY_MOCK_AKA_KEY")) {
tryReadIsimQrtr(id);
}
if (mImpi && *mImpi) {
id.impi = mImpi;
} else if (id.impi.empty()) {
id.impi = id.imsi + "@" + id.homeDomain;
}
if (mImpu && *mImpu) {
id.impu = mImpu;
} else if (id.impu.empty()) {
id.impu = "sip:" + id.imsi + "@" + id.homeDomain;
}
return id;
}
AkaResult authenticate(const uint8_t rand[16], const uint8_t autn[16]) {
AkaResult out;
const char* mockKeyHex = std::getenv("BANANARCHY_MOCK_AKA_KEY");
if (mockKeyHex && *mockKeyHex) {
std::vector<uint8_t> kBytes;
if (!hexToBytes(mockKeyHex, kBytes) || kBytes.size() != 16) {
out.error = "Invalid BANANARCHY_MOCK_AKA_KEY";
return out;
}
uint8_t opc[16]{};
const char* mockOpcHex = std::getenv("BANANARCHY_MOCK_AKA_OPC");
if (mockOpcHex && *mockOpcHex) {
std::vector<uint8_t> v;
if (hexToBytes(mockOpcHex, v) && v.size() == 16) {
std::memcpy(opc, v.data(), 16);
}
} else {
uint8_t op[16]{};
const char* mockOpHex = std::getenv("BANANARCHY_MOCK_AKA_OP");
if (mockOpHex && *mockOpHex) {
std::vector<uint8_t> v;
if (hexToBytes(mockOpHex, v) && v.size() == 16) {
std::memcpy(op, v.data(), 16);
}
}
milenageComputeOpc(kBytes.data(), op, opc);
}
milenageAuthenticate(kBytes.data(), opc, rand, autn, mockSqn_, out);
return out;
}
ScopedUimLock lock(stateDir_);
return authenticateQrtrUim(rand, autn);
}
void resetMockSqn(uint64_t v) { mockSqn_ = v; }
private:
int simSlot_ = 1;
std::string stateDir_;
uint64_t mockSqn_ = 0;
void tryReadIsimQrtr(SimIdentity& id) {
struct ims_qrtr_ep ep{};
if (ims_qrtr_open(&ep) != 0) {
return;
}
struct ims_qrtr_addr uimAddr{};
if (ims_qrtr_lookup(&ep, IMS_QMI_SVC_UIM, 0, 300, &uimAddr) != 0) {
ims_qrtr_close(&ep);
return;
}
/* Send QMI_UIM_READ_TRANSPARENT on session for EF_DOMAIN (0x6F03) / EF_IMPI (0x6F02). */
auto readEf = [&](uint16_t fileId) -> std::string {
uint8_t tlvs[64];
size_t off = 0;
uint8_t sess[2] = {static_cast<uint8_t>(simSlot_ == 2 ? 2 : 0), 0};
ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x01U, sess, 2);
uint8_t fpath[7] = {static_cast<uint8_t>(fileId & 0xFFU),
static_cast<uint8_t>((fileId >> 8) & 0xFFU),
4, 0x00, 0x3F, 0xFF, 0x7F};
ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x02U, fpath, 7);
uint8_t rr[4] = {0, 0, 0, 0};
ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x03U, rr, 4);
uint8_t rsp[512];
size_t rlen = 0;
if (ims_qmi_transact(&ep, &uimAddr, 300, IMS_QMI_UIM_READ_TRANSPARENT,
tlvs, off, 500, rsp, sizeof(rsp), &rlen) != 0 ||
ims_qmi_check_result(rsp, rlen, nullptr) != 0 || rlen < 7) {
return "";
}
uint16_t tlen = ims_qmi_get_le16(rsp + 5);
if (7U + tlen > rlen) return "";
uint16_t fl = 0;
const uint8_t* val = ims_qmi_tlv_find(rsp + 7, tlen, 0x10U, &fl);
if (!val || fl < 4) return "";
uint16_t clen = ims_qmi_get_le16(val);
if (2U + clen > fl || clen < 3 || val[2] != 0x80U) return "";
size_t slen = val[3];
if (4U + slen > fl) return "";
return std::string(reinterpret_cast<const char*>(val + 4), slen);
};
std::string dom = readEf(0x6F03U);
if (!dom.empty()) id.homeDomain = dom;
std::string impi = readEf(0x6F02U);
if (!impi.empty()) id.impi = impi;
ims_qrtr_close(&ep);
}
AkaResult authenticateQrtrUim(const uint8_t rand[16], const uint8_t autn[16]) {
AkaResult res;
struct ims_qrtr_ep ep{};
if (ims_qrtr_open(&ep) != 0) {
res.error = "QRTR unavailable";
return res;
}
struct ims_qrtr_addr uimAddr{};
if (ims_qrtr_lookup(&ep, IMS_QMI_SVC_UIM, 0, 400, &uimAddr) != 0) {
ims_qrtr_close(&ep);
res.error = "QMI_UIM service not found";
return res;
}
uint16_t txn = 400;
uint8_t slot = static_cast<uint8_t>(simSlot_ == 2 ? 2 : 1);
uint8_t channel = 0;
/* Try opening ISIM AID first, then USIM AID. */
static constexpr uint8_t kIsimAid[7] = {0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x04};
static constexpr uint8_t kUsimAid[7] = {0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02};
for (int tryAid = 0; tryAid < 2 && channel == 0; ++tryAid) {
uint8_t tlvs[32];
size_t off = 0;
ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x01U, &slot, 1);
uint8_t aidVal[8];
aidVal[0] = 7;
std::memcpy(aidVal + 1, tryAid == 0 ? kIsimAid : kUsimAid, 7);
ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x10U, aidVal, 8);
uint8_t rsp[512];
size_t rlen = 0;
if (ims_qmi_transact(&ep, &uimAddr, txn++, IMS_QMI_UIM_OPEN_LOGICAL_CHANNEL,
tlvs, off, 800, rsp, sizeof(rsp), &rlen) == 0 &&
ims_qmi_check_result(rsp, rlen, nullptr) == 0 && rlen >= 7) {
uint16_t tlen = ims_qmi_get_le16(rsp + 5);
uint16_t cl = 0;
const uint8_t* ch = ims_qmi_tlv_find(rsp + 7, tlen, 0x10U, &cl);
if (ch && cl >= 1 && ch[0] != 0) {
channel = ch[0];
}
}
}
if (channel == 0) {
ims_qrtr_close(&ep);
res.error = "Failed opening ISIM/USIM logical channel";
return res;
}
auto sendApdu = [&](const uint8_t* apdu, size_t apduLen,
std::vector<uint8_t>& outData) -> bool {
uint8_t tlvs[256];
size_t off = 0;
ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x01U, &slot, 1);
uint8_t abuf[160];
ims_qmi_put_le16(abuf, static_cast<uint16_t>(apduLen));
std::memcpy(abuf + 2, apdu, apduLen);
ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x02U, abuf,
static_cast<uint16_t>(2 + apduLen));
ims_qmi_tlv_add(tlvs, sizeof(tlvs), &off, 0x10U, &channel, 1);
uint8_t rsp[1024];
size_t rlen = 0;
if (ims_qmi_transact(&ep, &uimAddr, txn++, IMS_QMI_UIM_SEND_APDU,
tlvs, off, 1200, rsp, sizeof(rsp), &rlen) != 0 ||
ims_qmi_check_result(rsp, rlen, nullptr) != 0 || rlen < 7) {
return false;
}
uint16_t tlen = ims_qmi_get_le16(rsp + 5);
uint16_t al = 0;
const uint8_t* ar = ims_qmi_tlv_find(rsp + 7, tlen, 0x10U, &al);
if (!ar || al < 4) return false;
uint16_t len = ims_qmi_get_le16(ar);
if (2U + len > al) return false;
outData.assign(ar + 2, ar + 2 + len);
return true;
};
uint8_t authApdu[40]{};
authApdu[0] = static_cast<uint8_t>(channel & 0x03U);
authApdu[1] = 0x88U;
authApdu[2] = 0x00U;
authApdu[3] = 0x81U; /* 3G Security Context */
authApdu[4] = 0x22U;
authApdu[5] = 0x10U;
std::memcpy(authApdu + 6, rand, 16);
authApdu[22] = 0x10U;
std::memcpy(authApdu + 23, autn, 16);
authApdu[39] = 0x00U;
std::vector<uint8_t> apduOut;
if (sendApdu(authApdu, sizeof(authApdu), apduOut)) {
/* Handle SW 61 XX GET RESPONSE chaining if needed. */
if (apduOut.size() == 2 && apduOut[0] == 0x61U) {
uint8_t getRsp[5] = {static_cast<uint8_t>(channel & 0x03U),
0xC0U, 0x00U, 0x00U, apduOut[1]};
sendApdu(getRsp, sizeof(getRsp), apduOut);
}
if (apduOut.size() >= 3) {
size_t bodyLen = apduOut.size() - 2;
uint8_t sw1 = apduOut[bodyLen];
uint8_t sw2 = apduOut[bodyLen + 1];
if (sw1 == 0x90U && sw2 == 0x00U) {
if (apduOut[0] == 0xDBU) {
size_t p = 1;
if (p < bodyLen) {
size_t rl = apduOut[p++];
if (p + rl <= bodyLen) {
res.res.assign(apduOut.begin() + static_cast<long>(p),
apduOut.begin() + static_cast<long>(p + rl));
p += rl;
}
}
if (p < bodyLen) {
size_t cl = apduOut[p++];
if (p + cl <= bodyLen) {
res.ck.assign(apduOut.begin() + static_cast<long>(p),
apduOut.begin() + static_cast<long>(p + cl));
p += cl;
}
}
if (p < bodyLen) {
size_t il = apduOut[p++];
if (p + il <= bodyLen) {
res.ik.assign(apduOut.begin() + static_cast<long>(p),
apduOut.begin() + static_cast<long>(p + il));
}
}
if (!res.res.empty() && res.ck.size() == 16 && res.ik.size() == 16) {
res.ok = true;
}
} else if (apduOut[0] == 0xDCU && bodyLen >= 2) {
size_t alen = apduOut[1];
if (2U + alen <= bodyLen) {
res.auts.assign(apduOut.begin() + 2, apduOut.begin() + 2 + static_cast<long>(alen));
res.syncFailure = true;
res.ok = true;
}
}
} else {
res.error = "UIM auth APDU SW error";
}
}
} else {
res.error = "QMI_UIM_SEND_APDU failed";
}
/* Close logical channel. */
uint8_t clTlvs[16];
size_t coff = 0;
ims_qmi_tlv_add(clTlvs, sizeof(clTlvs), &coff, 0x01U, &slot, 1);
ims_qmi_tlv_add(clTlvs, sizeof(clTlvs), &coff, 0x10U, &channel, 1);
uint8_t crsp[256];
size_t crlen = 0;
(void)ims_qmi_transact(&ep, &uimAddr, txn++, IMS_QMI_UIM_LOGICAL_CHANNEL,
clTlvs, coff, 400, crsp, sizeof(crsp), &crlen);
ims_qrtr_close(&ep);
return res;
}
};
} // namespace ba_vowifi
#endif /* BANANARCHY_VOWIFI_AKA_H */
File diff suppressed because it is too large. Load diff