diff --git a/AGENTS.md b/AGENTS.md index 371e934..5f8d098 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,20 +44,24 @@ Keep this file short. Full details live in `README.md`, `MANUAL.md`, `SDK.md`, ` ## Critical invariants -- Bluetooth requires `ControllerMode = dual` and `Class = 0x5a020c` (`btmgmt -i hci0 class 2 3`) in `etc/bluetooth/main.conf` - and `bananarchy-bt-le-enable.sh`; BlueZ 5.87 rejects LE-only HOGP in `bredr` mode, and `a2dp_source` must stay out - of `50-bluetooth.conf` so paired Android phones recognize Object Push rather than an audio sink. Keep `UserspaceHID=true`, - `LEAutoSecurity=true`, `ClassicBondedOnly=false`, and `IdleTimeout=0` in `input.conf`. `bananarchy-bt-obex` must power on, - enable LE, select the LE bearer (`PreferredBearer = "le"`) for HID-over-GATT devices, select the BR/EDR bearer - (`PreferredBearer = "bredr"`, public address preference, `ConnectProfile` fallback) for Classic Audio / dual-mode - BT 5.x/6.x headsets, pair unbonded devices, forward `(AVRCP)` media keys to `xmusic`, handle both L2CAP `SOCK_SEQPACKET` - and RFCOMM via `ObexPacketReader` with `xnetworks` incoming confirmation / target folder (`~/.config/sxmo/bt_obex_dir`) IPC, - and keep discoverability hidden-by-default with a 60 s timeout (`bt_discoverable=0`, never `discoverable-timeout 0`). - Keep all four `50-bluetooth.conf` copies synced with `bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ]`, - `bluez5.enable-msbc = false`, `bluez5.enable-lc3-a127 = false`, `bluez5.dummy-avrcp-player = true`, and - `bluez5.a2dp.ldac.quality = "auto"` (no `a2dp_source`, `bap_*`, `hsp_ag`, `hfp_ag`, or `lc3` — WCN3620 SCO routes internally - at 8 kHz CVSD to QDSP6 `INTERNAL_BT_SCO_RX`/`TX`). `util-linux-misc` and `bluez-btmgmt` support the live PTY scan wrapper; - guard `scripts/test-bluetooth-{hid,scan,live-scan,headset,obex}.py`. +- Bluetooth requires `ControllerMode = dual`, `PairableTimeout = 0`, and `Class = 0x5a020c` (`btmgmt -i hci0 class 2 3`, + `bredr on`, `ssp on`, `linksec on`, `bondable on`, `advertising off`, `le on`) in `etc/bluetooth/main.conf` and + `bananarchy-bt-le-enable.sh`; BlueZ 5.87 rejects LE-only HOGP in `bredr` mode, and `a2dp_source` must stay out of + `50-bluetooth.conf` so paired Android phones recognize Object Push rather than an audio sink. Keep `UserspaceHID=true`, + `LEAutoSecurity=true`, `ClassicBondedOnly=false`, and `IdleTimeout=0` in `input.conf`. `bananarchy-bt-obex` must register + a persistent `"KeyboardDisplay"` `Agent1` (never `"NoInputNoOutput"`) with `/run/bananarchy/bt-obex/pair_{prompt,decision}.tsv` + and `xnetworks` `BtPairingPrompt` UI (auto-confirming Classic Audio headsets, prompting user confirmation/PIN/passkey + for phones/keyboards, `50 s` `Pair` timeout, `--async-ui` non-blocking operations, phone `is_phone_or_computer_props` vs + audio separation), power on, enable LE/SSP, select the LE bearer (`PreferredBearer = "le"`) for HID-over-GATT devices, + select the BR/EDR bearer (`PreferredBearer = "bredr"`, public address preference, `ConnectProfile` fallback) for + Classic Audio / dual-mode BT 5.x/6.x headsets, pair unbonded devices, forward `(AVRCP)` media keys to `xmusic`, + handle both L2CAP `SOCK_SEQPACKET` and RFCOMM via `ObexPacketReader` with `xnetworks` incoming confirmation / target + folder (`~/.config/sxmo/bt_obex_dir`) IPC, and keep discoverability hidden-by-default with a 60 s timeout + (`bt_discoverable=0`, never `discoverable-timeout 0`). Keep all four `50-bluetooth.conf` copies synced with + `bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ]`, `bluez5.enable-msbc = false`, `bluez5.enable-lc3-a127 = false`, + `bluez5.dummy-avrcp-player = true`, and `bluez5.a2dp.ldac.quality = "auto"` (no `a2dp_source`, `bap_*`, `hsp_ag`, + `hfp_ag`, or `lc3` — WCN3620 SCO routes internally at 8 kHz CVSD to QDSP6 `INTERNAL_BT_SCO_RX`/`TX`). + `util-linux-misc` and `bluez-btmgmt` support the live PTY scan wrapper; guard `scripts/test-bluetooth-{hid,scan,live-scan,headset,obex}.py`. - WebKit requires explicit `glib` and `gsettings-desktop-schemas` packages. Because apk uses `--no-scripts`, `apply-bananarchy-overlay.sh` must run `compile-gsettings-schemas.sh`; without `gschemas.compiled`, the WebKit network process aborts. Keep the Webarchy renderer fallback. diff --git a/CHANGELOG.md b/CHANGELOG.md index c8226c3..60d194e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ Upcoming release build (`a1120` / `cocojamboo` via `scripts/version.sh`) targeti ### Bluetooth 5.x/6.x headset support (`A2DP` + `HSP/HFP`), Android OBEX file transfer, AVRCP controls, and power safeguards across all targets +- **Android SSP/PIN/Passkey pairing agent & NeoUI confirmation popup (`etc/bluetooth/main.conf`, `bananarchy-bt-le-enable.sh`, `sxmo_bluetoothtoggle.sh`, `sxmo_hook_start.sh`, `bananarchy-bt-obex`, `networks_plugin.cpp`)**: switched the persistent `Agent1` capability from dummy `"NoInputNoOutput"` (which replied `"0000"` / `0` with zero prompt and tripped BlueZ/WCNSS `"incorrect PIN or passkey"`) to `"KeyboardDisplay"` backed by `/run/bananarchy/bt-obex/{pair_prompt,pair_decision,op_done}.tsv` IPC and `NetModal::BtPairingPrompt` (`CONFIRM` 6-digit passkey match, keypad `PIN` / `PASSKEY` entry, `DISPLAY` keyboard code, and `Cancel`/`Close` rejection, while auto-confirming screenless Classic Audio headsets); enabled `bredr on`, `ssp on`, `linksec on`, `bondable on`, and `advertising off` alongside `class 2 3` and `le on` in `bananarchy-bt-le-enable.sh` (`PairableTimeout = 0` in `main.conf` while keeping `DiscoverableTimeout = 60` hidden by default); fixed root/`user` daemon UID collisions and sticky-`/tmp` PID/status writes (`errno != EPERM` + `doas -n bananarchy-bt-obex start` + boot hook restart when BT is enabled); made `networks_plugin.cpp` `Connect`/`Pair` non-blocking (`--async-ui`), prevented `cli_agent` hijacking and 8 s `Pair` aborts (`50 s` timeout), and fixed phone `Icon: phone`/`computer` (`OBEX/PAN`) vs Classic Audio classification across `queryBtDevices()` and `is_phone_or_computer_props()`. - **Android OBEX (`0x1105`) recognition, L2CAP `SOCK_SEQPACKET`, and incoming file Accept/Reject + Target Folder UI (`etc/bluetooth/main.conf`, `50-bluetooth.conf`, `bananarchy-bt-le-enable.sh`, `sxmo_bluetoothtoggle.sh`, `bananarchy-bt-obex`, `networks_plugin.cpp`)**: added `Class = 0x5a020c` (`Phone / Smartphone` with `Object Transfer`) in `main.conf`, set `btmgmt -i hci0 class 2 3` at power-on/LE-enable, and removed `a2dp_source` from `50-bluetooth.conf` (`bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ]`) so paired Android phones recognize Bananarchy as a phone supporting OBEX Object Push rather than a Bluetooth audio sink; replaced `recv(3)` with `ObexPacketReader` handling full L2CAP `SOCK_SEQPACKET` (GOEP 2.0) datagrams alongside RFCOMM `SOCK_STREAM`; registered BlueZ `OPP_UUID` (`0x1105`) with retries before falling back to raw RFCOMM channel 9 bind; added `/run/bananarchy/bt-obex/{prompt,decision}.tsv` IPC with an interactive `networks.so` prompt (`Accept & Save File`, `Dir: ... [Set]`, `Reject Transfer` returning OBEX `0xC3` Forbidden) and interactive `ObexDirPicker` / `ObexActions` directory chooser (`~/.config/sxmo/bt_obex_dir`, supporting `/media/sdcard`, custom folders, and duress confinement); verified via `scripts/test-bluetooth-obex.py`. - **Dual-bearer BR/EDR audio selection & PipeWire role/codec fixes (`bananarchy-bt-obex`, all four `50-bluetooth.conf` copies)**: kept `ControllerMode = dual` and `PreferredBearer = "le"` for HOGP (`00001812-`) while adding Classic Audio (`0000110b-`/`0000111e-`/`00001108-`/`audio-*`) detection (`set_audio_preferred_bearer()` -> `PreferredBearer = "bredr"`), `public` BR/EDR ranking over `random` BLE beacons in `find_matching_device()`/`scan_for_device()`, and `ConnectProfile` fallback so dual-mode Bluetooth 5.x/6.x earbuds do not stop on a GATT-only BLE link; updated `50-bluetooth.conf` across `/etc/`, `/usr/share/`, `/home/user/`, and `/etc/skel/` to restrict roles to `[ a2dp_sink hsp_hs hfp_hf ]` (removing `a2dp_source`, `bap_sink`/`bap_source`, and `hsp_ag`/`hfp_ag`), disable `msbc` and `lc3-a127`/`lc3` so HFP locks to 8 kHz `cvsd` for QDSP6 `INTERNAL_BT_SCO`, fix `opus_05_dup` -> `opus_05_duplex`, set `bluez5.dummy-avrcp-player = true`, and enable `bluez5.a2dp.ldac.quality = "auto"` (ABR) + `aac.bitratemode = 0` for 2.4 GHz Wi-Fi coexistence. - **SCO keepalive race, missing `pkill` leak, headset `ATA` call pickup, AVRCP media keys, and `nokia-sparkler` haptic guard (`sxmo_audio.sh`, `sxmo_modemaudio.sh`, `callscreen_plugin.cpp`, `networks_plugin.cpp`, `music_plugin.cpp`, `sxmo_vibrate.c`)**: replaced missing `pkill` in `stop_bt_sco_keepalive()` with `/proc` + `ps` teardown and stopped keepalive unconditionally when switching off Bluetooth HFP (even mid-call); added bounded (`25 x 0.1 s` / `15 x 0.1 s`) sink readiness waits and direct `$bt_sink` volume/mute mirroring (`+VGS`/AVRCP); synced `/tmp/sxmo_in_call` and `.pickedupcall` in `callscreen_plugin.cpp` when calls transition active via headset `ATA` so hangup restores A2DP and avoids false Missed Call logs; forwarded BlueZ `(AVRCP)` input keys to `music.so` (`PLAYPAUSE`/`PLAY`/`PAUSE`/`STOP`/`NEXT`/`PREV`) via the 0%-CPU `select()` bridge in `bananarchy-bt-obex` and handled `XF86XK_AudioPlay`/`Pause`/`Stop`/`Next`/`Prev` in `music_plugin.cpp`; refreshed stale `targetBt` after `Pair`/`Connect` in `networks_plugin.cpp` with a 24-device `info` batch cap; added `/tmp/sxmo_bt_sco_mm_active` suppression in `sxmo_vibrate.c` so 157 Hz haptic audio cannot leak over non-call BT SCO on `nokia-sparkler`; and changed `bt_discoverable` defaults across `sxmo_bluetoothtoggle.sh`, `bananarchy-bt-obex`, and `networks_plugin.cpp` to hidden-by-default with a 60 s discoverable timeout. Verified via `scripts/test-bluetooth-headset.py` alongside `test-bluetooth-{hid,scan,live-scan}.py` and `scripts/check-rebuild.sh`. @@ -72,10 +73,10 @@ Upcoming release build (`a1120` / `cocojamboo` via `scripts/version.sh`) targeti ### Image persistence and upcoming `a1120` (`cocojamboo`) release archives - **Verified `a1120` / `cocojamboo` image set (`--mkinitfs`) and packaged archives**: - - `images/bananarchy-nokia-argon.img`: SHA-256 `92b23d34180c157861c492e7c2ea848ea4580857f3c1674020ae6b9f6fbdd39f` (packaged in `bananarchy-nokia-argon-a1120-cocojamboo.zip`, SHA-256 `f3680c940ba95f063822e033c60fc18faa3fd20faab4dcec558445d6d1d828f0`, alongside `bootloader/lk2nd-msm8909.img`). - - `images/bananarchy-nokia-beatles.img`: SHA-256 `5c284c314a378d09fda37e56ebe745ab557d45c77499206440e8c362c709e7a7`, `images/boot-bananarchy-nokia-beatles.img`: SHA-256 `80485ccf2af4f1d6107965ecde43d888c66ec19006e6feabc7fb63b6a7852391`, and `images/boot-lk2nd-nokia-beatles-display.img`: SHA-256 `b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d` (packaged in `bananarchy-nokia-beatles-a1120-cocojamboo.zip`, SHA-256 `1d2849c73dcf3d0bf8d0e2417778366bd726442556567ab9180e314951a5b993`). - - `images/bananarchy-nokia-coconut.img`: SHA-256 `4e1d4799d42f56423f9cba8e175adf3b1f6c7fcd89965a7bc0b84a4f03ebc6e5`, `images/boot-bananarchy-nokia-coconut.img`: SHA-256 `1e22879fc0533f419dc98c88a1700d75101fda85669837d1457bb15b9ab4ed9c`, and `images/boot-lk2nd-nokia-coconut-display.img`: SHA-256 `e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a` (packaged in `bananarchy-nokia-coconut-a1120-cocojamboo.zip`, SHA-256 `af06ab7bbb3933732f644d24acb03d04ef066d59aae0c2009d0c9cf367bec4d1`). - - `images/bananarchy-nokia-sparkler.img`: SHA-256 `6b40db4674821bdde80d6f7619acc5a6414df684201d3e4e2e7cc3ac6c25dcfd`, `images/boot-bananarchy-nokia-sparkler.img`: SHA-256 `8f41328f0197f5debba92eaffa9df46c530721719309024a4d9cd7bf79a722c7`, and `images/boot-lk2nd-nokia-sparkler-display.img`: SHA-256 `bc41c2ddd1079246a7e91a40222fcafb82b0b52965c8ee8081872767d006748f` (packaged in `bananarchy-nokia-sparkler-a1120-cocojamboo.zip`, SHA-256 `0ca08f7a58e517fce283028548ba6d7657c419e823782fe188c75b0fbd93d378`). + - `images/bananarchy-nokia-argon.img`: SHA-256 `09c46d21b140b486e21ebed39740b57808f8f1f0045f1801af2a7f8eba72bb4d` (packaged in `bananarchy-nokia-argon-a1120-cocojamboo.zip`, SHA-256 `5a290c236aa85828fb0b8a9bf6e2a7afa8ebe10c9d2819617661e8c0cb53d3ff`, alongside `bootloader/lk2nd-msm8909.img`). + - `images/bananarchy-nokia-beatles.img`: SHA-256 `5d8c50f89e257dbadd9050479d56c46b1902cb38707f6f692e3508b44aa4fd10`, `images/boot-bananarchy-nokia-beatles.img`: SHA-256 `f6c897f8e5fac17df38ac3d3222279f229b84c53ea73c323d06de5c40b26ccc0`, and `images/boot-lk2nd-nokia-beatles-display.img`: SHA-256 `b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d` (packaged in `bananarchy-nokia-beatles-a1120-cocojamboo.zip`, SHA-256 `a49d0d905af1ea5350bc1197e7970f59296359a913e3a09afc46c06aaf80d891`). + - `images/bananarchy-nokia-coconut.img`: SHA-256 `836331fb3034d0527f8c03eb90aae25bc8c87a84cc56baf24459d2e81e7a28d1`, `images/boot-bananarchy-nokia-coconut.img`: SHA-256 `6e2fefec812594dc7b4dc322c68b1ab4c10b1c93abee4a0fbd11dfbf2dc59a0b`, and `images/boot-lk2nd-nokia-coconut-display.img`: SHA-256 `e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a` (packaged in `bananarchy-nokia-coconut-a1120-cocojamboo.zip`, SHA-256 `68af7997cbe1227d49e5238cabbbfcb44dcb728e8456b0fd0d416477307074b2`). + - `images/bananarchy-nokia-sparkler.img`: SHA-256 `61a068ca432f064812a96356b0dc49f1a38102a717c8dccd31768f0cbd1d7639`, `images/boot-bananarchy-nokia-sparkler.img`: SHA-256 `4357d48ac069104495629f1f35e220a01cde3412950e73e3e47e5372649fb6a2`, and `images/boot-lk2nd-nokia-sparkler-display.img`: SHA-256 `bc41c2ddd1079246a7e91a40222fcafb82b0b52965c8ee8081872767d006748f` (packaged in `bananarchy-nokia-sparkler-a1120-cocojamboo.zip`, SHA-256 `73951ce01b3ff8f782488333767101d8e83701ae3822b1c7a0bef6ab8e96d1dc`). --- diff --git a/MANUAL.md b/MANUAL.md index da3b143..d6ef03c 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -220,7 +220,7 @@ All twenty-five phone applications are compiled as shared-object plugins (`/usr/ - **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). - **`2:Cell/APN`**: toggle **Mobile Data** (configuring the QMI `bam-dmux` `wwan0` static IPv4 bearer, default route, and DNS automatically), inspect `wwan0` IPv4 status, edit **APN Configuration**, and toggle **USB Tethering**. - - **`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: [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: [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. 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 ` 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` before discovery because this WCNSS controller otherwise starts with LE disabled and only performs BR/EDR inquiry. 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** power the adapter on, enable LE, 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, 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: [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: [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 ` 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`)**: - **Open**: select **Ringtones** from the System, Config, or Audio menu, select **Notification Sound** from the **Notifications (`Notifs`)** menu, or run `xringtones [--notif] [file]`. diff --git a/README.md b/README.md index 01c9f83..eb9e557 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs - **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_.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. - **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. -- **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` (and sets Smartphone controller class `2 3`) before each scan because the WCNSS controller otherwise powers up with LE disabled and only performs BR/EDR inquiry. BlueZ runs in `dual` controller mode because `bredr` mode rejects the LE-only HOGP profile, leaving BLE keyboards and mice connected but without a usable input node. Pair/connect actions power the adapter on, enable LE, 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. - **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.`) 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/]` / `[SIP/:]`), 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. diff --git a/overlay/rootfs/etc/bluetooth/main.conf b/overlay/rootfs/etc/bluetooth/main.conf index fefce67..0bbb747 100644 --- a/overlay/rootfs/etc/bluetooth/main.conf +++ b/overlay/rootfs/etc/bluetooth/main.conf @@ -2,7 +2,7 @@ # U5: BT is off by default (rfkill soft-block, daemon not started). When a # user enables it, do not leave the controller permanently discoverable. DiscoverableTimeout = 60 -PairableTimeout = 60 +PairableTimeout = 0 ControllerMode = dual Class = 0x5a020c MultiProfile = multiple diff --git a/overlay/rootfs/etc/skel/.config/sxmo/hooks/sxmo_hook_start.sh b/overlay/rootfs/etc/skel/.config/sxmo/hooks/sxmo_hook_start.sh index a99c23d..a5a6377 100755 --- a/overlay/rootfs/etc/skel/.config/sxmo/hooks/sxmo_hook_start.sh +++ b/overlay/rootfs/etc/skel/.config/sxmo/hooks/sxmo_hook_start.sh @@ -145,5 +145,8 @@ superctl start sxmo_notificationmonitor ( sxmo_hook_apps.sh >/dev/null 2>&1 || true sxmo_hook_scripts.sh >/dev/null 2>&1 || true + if [ "$(/usr/bin/sxmo_bluetoothtoggle.sh status 2>/dev/null)" = "on" ]; then + SXMO_OS=alpine doas -n /usr/bin/sxmo_bluetoothtoggle.sh on >/dev/null 2>&1 || true + fi ) & ) diff --git a/overlay/rootfs/home/user/.config/sxmo/hooks/sxmo_hook_start.sh b/overlay/rootfs/home/user/.config/sxmo/hooks/sxmo_hook_start.sh index b13d1b5..30d3577 100755 --- a/overlay/rootfs/home/user/.config/sxmo/hooks/sxmo_hook_start.sh +++ b/overlay/rootfs/home/user/.config/sxmo/hooks/sxmo_hook_start.sh @@ -144,5 +144,8 @@ superctl start sxmo_notificationmonitor ( sxmo_hook_apps.sh >/dev/null 2>&1 || true sxmo_hook_scripts.sh >/dev/null 2>&1 || true + if [ "$(/usr/bin/sxmo_bluetoothtoggle.sh status 2>/dev/null)" = "on" ]; then + SXMO_OS=alpine doas -n /usr/bin/sxmo_bluetoothtoggle.sh on >/dev/null 2>&1 || true + fi ) & ) diff --git a/overlay/rootfs/usr/bin/bananarchy-bt-le-enable.sh b/overlay/rootfs/usr/bin/bananarchy-bt-le-enable.sh index dee6113..79cdfc6 100755 --- a/overlay/rootfs/usr/bin/bananarchy-bt-le-enable.sh +++ b/overlay/rootfs/usr/bin/bananarchy-bt-le-enable.sh @@ -1,12 +1,17 @@ #!/bin/sh -# Enable the WCNSS controller's LE setting before BlueZ discovery. -# The kernel management socket requires root for this write. +# Enable BR/EDR + SSP + bondable + link security + Smartphone CoD + LE Central +# (disable LE peripheral advertising so phones pair via BR/EDR SSP, not CTKD). set -eu if [ "$(id -u)" -ne 0 ]; then - echo "Error: bananarchy-bt-le-enable.sh must run as root" >&2 + echo "bananarchy-bt-le-enable.sh must run as root" >&2 exit 1 fi +/usr/bin/btmgmt -i hci0 bredr on >/dev/null 2>&1 || true +/usr/bin/btmgmt -i hci0 ssp on >/dev/null 2>&1 || true +/usr/bin/btmgmt -i hci0 linksec on >/dev/null 2>&1 || true +/usr/bin/btmgmt -i hci0 bondable on >/dev/null 2>&1 || true +/usr/bin/btmgmt -i hci0 advertising off >/dev/null 2>&1 || true /usr/bin/btmgmt -i hci0 class 2 3 >/dev/null 2>&1 || true exec /usr/bin/btmgmt -i hci0 le on diff --git a/overlay/rootfs/usr/bin/bananarchy-bt-obex b/overlay/rootfs/usr/bin/bananarchy-bt-obex index f567ad6..86ee484 100755 --- a/overlay/rootfs/usr/bin/bananarchy-bt-obex +++ b/overlay/rootfs/usr/bin/bananarchy-bt-obex @@ -22,7 +22,14 @@ OBEX_CFG_FILE = "/home/user/.config/sxmo/bt_obex_dir" OBEX_IPC_DIR = "/run/bananarchy/bt-obex" OBEX_PROMPT_FILE = "/run/bananarchy/bt-obex/prompt.tsv" OBEX_DECISION_FILE = "/run/bananarchy/bt-obex/decision.tsv" +PAIR_PROMPT_FILE = "/run/bananarchy/bt-obex/pair_prompt.tsv" +PAIR_DECISION_FILE = "/run/bananarchy/bt-obex/pair_decision.tsv" +OP_DONE_FILE = "/run/bananarchy/bt-obex/op_done.tsv" +AGENT_READY_FILE = "/run/bananarchy/bt-obex/agent_ready" OBEX_PROMPT_LOCK = threading.Lock() +PAIR_PROMPT_LOCK = threading.Lock() +PAIR_CANCEL_EVENT = threading.Event() +DBUS_SEND_LOCK = threading.Lock() def is_duress_mode(): @@ -76,6 +83,13 @@ def get_downloads_dir(): def ensure_obex_ipc_dir(): + parent = os.path.dirname(OBEX_IPC_DIR) + if parent: + try: + os.makedirs(parent, mode=0o755, exist_ok=True) + os.chmod(parent, 0o755) + except OSError: + pass os.makedirs(OBEX_IPC_DIR, mode=0o755, exist_ok=True) try: os.chmod(OBEX_IPC_DIR, 0o755) @@ -85,14 +99,29 @@ def ensure_obex_ipc_dir(): def write_status(path, text): + tmp = f"{path}.{os.getpid()}.tmp" try: - tmp = path + ".tmp" with open(tmp, "w", encoding="utf-8") as f: f.write(text.strip() + "\n") os.chmod(tmp, 0o644) - os.replace(tmp, path) + try: + os.chown(tmp, 10000, 10000) + except OSError: + pass + try: + os.replace(tmp, path) + except PermissionError: + try: + os.unlink(path) + except OSError: + pass + os.replace(tmp, path) except OSError: - pass + try: + if os.path.exists(tmp): + os.unlink(tmp) + except OSError: + pass def notify_networks_ui(msg="REFRESH_BT\n"): @@ -108,6 +137,49 @@ def notify_networks_ui(msg="REFRESH_BT\n"): return False +def wake_and_alert_ui(fifo_cmd, fallback_arg): + if os.environ.get("BANANARCHY_OBEX_NO_UI") == "1": + notify_networks_ui(fifo_cmd) + return + try: + if os.path.exists("/usr/bin/bananarchy-lid-gate.sh"): + subprocess.Popen( + ["/usr/bin/bananarchy-lid-gate.sh", "wake"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + except Exception: + pass + if not os.path.exists("/home/user/.config/sxmo/.novibrate"): + try: + if os.geteuid() == 0: + subprocess.Popen( + ["su", "-", "user", "-c", "sxmo_vibrate 180"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + else: + subprocess.Popen( + ["sxmo_vibrate", "180"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + except Exception: + pass + if not notify_networks_ui(fifo_cmd): + try: + if os.geteuid() == 0: + subprocess.Popen( + ["su", "-", "user", "-c", + f"DISPLAY=:0 /usr/bin/dwm-plugin networks {fallback_arg}"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + else: + subprocess.Popen( + ["/usr/bin/dwm-plugin", "networks", fallback_arg], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + except Exception: + pass + + def notify_user(title, body): try: bus_addr = "unix:path=/run/user/10000/bus" @@ -270,46 +342,7 @@ def request_user_obex_confirmation(sock, sender_name, sender_mac, file_name, sz_label = format_size(total_len) if total_len and total_len > 0 else "Unknown size" write_status(RX_STATUS_FILE, f"PENDING\t{f_label}\t{s_label}\t{sz_label}") - ui_disabled = (os.environ.get("BANANARCHY_OBEX_NO_UI") == "1") - if not ui_disabled: - try: - if os.path.exists("/usr/bin/bananarchy-lid-gate.sh"): - subprocess.Popen( - ["/usr/bin/bananarchy-lid-gate.sh", "wake"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL - ) - except Exception: - pass - if not os.path.exists("/home/user/.config/sxmo/.novibrate"): - try: - if os.geteuid() == 0: - subprocess.Popen( - ["su", "-", "user", "-c", "sxmo_vibrate 180"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL - ) - else: - subprocess.Popen( - ["sxmo_vibrate", "180"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL - ) - except Exception: - pass - if not notify_networks_ui(f"OBEX_PROMPT {req_id}\n"): - try: - if os.geteuid() == 0: - subprocess.Popen( - ["su", "-", "user", "-c", "DISPLAY=:0 /usr/bin/dwm-plugin networks obex-prompt"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL - ) - else: - subprocess.Popen( - ["/usr/bin/dwm-plugin", "networks", "obex-prompt"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL - ) - except Exception: - pass - else: - notify_networks_ui(f"OBEX_PROMPT {req_id}\n") + wake_and_alert_ui(f"OBEX_PROMPT {req_id}\n", "obex-prompt") deadline = time.monotonic() + timeout_sec try: @@ -563,16 +596,23 @@ def open_input_inotify_fd(): CLASSIC_AUDIO_UUID_PREFIXES = ( "00001108-", # Headset (HSP) - "0000110a-", # Audio Source "0000110b-", # Audio Sink (A2DP) - "0000110c-", # A/V Remote Control Target - "0000110e-", # A/V Remote Control - "00001112-", # Headset Audio Gateway "0000111e-", # Handsfree (HFP) - "0000111f-", # Handsfree Audio Gateway ) +def is_phone_or_computer_props(props): + if not isinstance(props, dict): + return False + icon = str(props.get("Icon") or "").strip().lower() + if icon.startswith("phone") or icon.startswith("computer"): + return True + cod = props.get("Class") + if isinstance(cod, int) and (cod & 0x1F00) in (0x0100, 0x0200): + return True + return False + + def is_hog_device_props(props): if not isinstance(props, dict): return False @@ -581,7 +621,7 @@ def is_hog_device_props(props): def is_classic_audio_props(props): - if not isinstance(props, dict) or is_hog_device_props(props): + if not isinstance(props, dict) or is_hog_device_props(props) or is_phone_or_computer_props(props): return False uuids = [str(v).lower() for v in (props.get("UUIDs") or [])] if any(any(u.startswith(p) for p in CLASSIC_AUDIO_UUID_PREFIXES) for u in uuids): @@ -951,6 +991,16 @@ def run_gamepad_uinput_bridge(is_running, wake_r=-1): pass +def dbus_send_safe(conn, msg, serial=None): + if conn is None: + return + with DBUS_SEND_LOCK: + if serial is None: + conn.send(msg) + else: + conn.send(msg, serial=serial) + + def trust_device_path(conn, dev_path): if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"): return @@ -958,8 +1008,8 @@ def trust_device_path(conn, dev_path): from jeepney import DBusAddress, new_method_call prop_addr = DBusAddress(dev_path, bus_name="org.bluez", interface="org.freedesktop.DBus.Properties") - conn.send(new_method_call(prop_addr, "Set", "ssv", - ("org.bluez.Device1", "Trusted", ("b", True)))) + dbus_send_safe(conn, new_method_call(prop_addr, "Set", "ssv", + ("org.bluez.Device1", "Trusted", ("b", True)))) except Exception: pass @@ -977,9 +1027,9 @@ def set_hog_preferred_bearer(conn, dev_path, props=None): from jeepney import DBusAddress, new_method_call prop_addr = DBusAddress(dev_path, bus_name="org.bluez", interface="org.freedesktop.DBus.Properties") - conn.send(new_method_call(prop_addr, "Set", "ssv", - ("org.bluez.Device1", "PreferredBearer", - ("s", "le")))) + dbus_send_safe(conn, new_method_call(prop_addr, "Set", "ssv", + ("org.bluez.Device1", "PreferredBearer", + ("s", "le")))) except Exception: pass @@ -994,15 +1044,204 @@ def set_audio_preferred_bearer(conn, dev_path, props=None): from jeepney import DBusAddress, new_method_call prop_addr = DBusAddress(dev_path, bus_name="org.bluez", interface="org.freedesktop.DBus.Properties") - conn.send(new_method_call(prop_addr, "Set", "ssv", - ("org.bluez.Device1", "PreferredBearer", - ("s", "bredr")))) + dbus_send_safe(conn, new_method_call(prop_addr, "Set", "ssv", + ("org.bluez.Device1", "PreferredBearer", + ("s", "bredr")))) except Exception: pass -def handle_agent_method_call(conn, msg, agent_path): - from jeepney import new_method_return, MessageType +def set_preferred_bearer_for_device(conn, dev_path, props=None): + """Prefer BR/EDR for phones, computers, audio headsets, and public BR/EDR devices.""" + if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"): + return + if is_hog_device_props(props): + return + addr_type = str((props or {}).get("AddressType") or "").strip().lower() + if not (is_phone_or_computer_props(props) or is_classic_audio_props(props) or addr_type == "public"): + return + try: + from jeepney import DBusAddress, new_method_call + prop_addr = DBusAddress(dev_path, bus_name="org.bluez", + interface="org.freedesktop.DBus.Properties") + dbus_send_safe(conn, new_method_call(prop_addr, "Set", "ssv", + ("org.bluez.Device1", "PreferredBearer", + ("s", "bredr")))) + except Exception: + pass + + +def _extract_dev_mac_from_path(dev_path): + if isinstance(dev_path, str) and "dev_" in dev_path: + return dev_path.split("dev_")[-1].replace("_", ":").upper() + return "" + + +def read_cached_bt_device_info(dev_path, bt_root="/var/lib/bluetooth"): + mac = _extract_dev_mac_from_path(dev_path) + if not mac or not os.path.isdir(bt_root): + return {} + out = {} + try: + adapters = os.listdir(bt_root) + except OSError: + return out + for adapter in adapters: + for rel in (os.path.join(adapter, mac, "info"), + os.path.join(adapter, "cache", mac)): + info_path = os.path.join(bt_root, rel) + if not os.path.isfile(info_path): + continue + try: + in_general = False + with open(info_path, "r", encoding="utf-8", errors="replace") as f: + for ln in f: + s = ln.strip() + if not s or s.startswith("#"): + continue + if s.startswith("[") and s.endswith("]"): + in_general = (s.lower() == "[general]") + continue + if not in_general or "=" not in s: + continue + k, v = s.split("=", 1) + k = k.strip() + v = v.strip() + if k in ("Name", "Alias", "Icon") and v and k not in out: + out[k] = v + elif k == "Class" and v and "Class" not in out: + try: + out["Class"] = int(v, 0) + except ValueError: + pass + elif k == "Services" and v and "UUIDs" not in out: + out["UUIDs"] = [u.strip() for u in v.split(";") if u.strip()] + except OSError: + pass + return out + + +def query_dev_props_fresh(dev_path, timeout=0.6): + if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"): + return {} + if not os.environ.get("DBUS_SYSTEM_BUS_ADDRESS") and not os.path.exists("/run/dbus/system_bus_socket"): + return {} + c = None + try: + from jeepney import DBusAddress, MessageType, new_method_call + from jeepney.io.blocking import open_dbus_connection + c = open_dbus_connection(bus="SYSTEM") + prop_addr = DBusAddress(dev_path, bus_name="org.bluez", + interface="org.freedesktop.DBus.Properties") + rep = c.send_and_get_reply( + new_method_call(prop_addr, "GetAll", "s", ("org.bluez.Device1",)), + timeout=timeout + ) + if rep is not None and rep.header.message_type == MessageType.method_return and rep.body: + raw = rep.body[0] + if isinstance(raw, dict): + return { + k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v) + for k, v in raw.items() + } + except Exception: + pass + finally: + if c is not None: + try: + c.close() + except Exception: + pass + return {} + + +def lookup_agent_device_info(dev_path, dev_props_cache=None): + mac = _extract_dev_mac_from_path(dev_path) + info = {} + if isinstance(dev_props_cache, dict) and dev_path in dev_props_cache: + cached = dev_props_cache.get(dev_path) + if isinstance(cached, dict): + info.update(cached) + disk = read_cached_bt_device_info(dev_path) + for k, v in disk.items(): + info.setdefault(k, v) + if not info.get("Name") and not info.get("UUIDs"): + fresh = query_dev_props_fresh(dev_path) + if fresh: + info.update(fresh) + if isinstance(dev_props_cache, dict) and dev_path: + dev_props_cache[dev_path] = dict(info) + name = str(info.get("Alias") or info.get("Name") or mac or "Bluetooth Device").strip() + return name, mac, info + + +def clear_pair_prompt_files(notify_cancel=False): + for p in (PAIR_PROMPT_FILE, PAIR_DECISION_FILE): + try: + if os.path.exists(p): + os.unlink(p) + except OSError: + pass + if notify_cancel: + notify_networks_ui("PAIR_CANCEL\n") + + +def write_pair_prompt_tsv(req_id, mode, dev_name, dev_mac, code="", entered=0): + ensure_obex_ipc_dir() + s_label = str(dev_name or dev_mac or "Bluetooth Device").replace("\t", " ").replace("\n", " ").strip() + s_mac = str(dev_mac or "").replace("\t", " ").replace("\n", " ").strip() + s_code = str(code or "").replace("\t", " ").replace("\n", " ").strip() + tmp_prompt = f"{PAIR_PROMPT_FILE}.{os.getpid()}.tmp" + with open(tmp_prompt, "w", encoding="utf-8") as pf: + pf.write(f"{req_id}\t{mode}\t{s_label}\t{s_mac}\t{s_code}\t{int(entered or 0)}\n") + try: + os.chmod(tmp_prompt, 0o644) + os.chown(tmp_prompt, 10000, 10000) + except OSError: + pass + os.replace(tmp_prompt, PAIR_PROMPT_FILE) + + +def write_display_pair_prompt(dev_name, dev_mac, code, entered=0): + s_mac = str(dev_mac or "unknown").replace(":", "").strip() + req_id = f"display_{s_mac}_{code}" + write_pair_prompt_tsv(req_id, "DISPLAY", dev_name, dev_mac, code, entered) + wake_and_alert_ui(f"PAIR_PROMPT {req_id}\n", "pair-prompt") + + +def request_user_pairing_interaction(mode, dev_name, dev_mac, code="", timeout_sec=50.0): + with PAIR_PROMPT_LOCK: + PAIR_CANCEL_EVENT.clear() + clear_pair_prompt_files(notify_cancel=False) + req_id = f"{os.getpid()}_{int(time.monotonic() * 1000)}" + write_pair_prompt_tsv(req_id, mode, dev_name, dev_mac, code, 0) + wake_and_alert_ui(f"PAIR_PROMPT {req_id}\n", "pair-prompt") + + deadline = time.monotonic() + timeout_sec + try: + while time.monotonic() < deadline: + if PAIR_CANCEL_EVENT.is_set(): + return False, "", True + if os.path.exists(PAIR_DECISION_FILE): + try: + with open(PAIR_DECISION_FILE, "r", encoding="utf-8", errors="replace") as df: + line = df.readline().rstrip("\r\n") + parts = line.split("\t") + if len(parts) >= 2 and parts[0] == req_id: + accepted = (parts[1].strip().upper() == "ACCEPT") + val = parts[2].strip() if len(parts) >= 3 else "" + return accepted, val, False + except OSError: + pass + PAIR_CANCEL_EVENT.wait(0.08) + return False, "", False + finally: + clear_pair_prompt_files(notify_cancel=False) + notify_networks_ui() + + +def handle_agent_method_call(conn, msg, agent_path, dev_props_cache=None): + from jeepney import new_method_return, new_error, MessageType if msg is None or msg.header.message_type != MessageType.method_call: return False path = msg.header.fields.get(1) @@ -1010,37 +1249,89 @@ def handle_agent_method_call(conn, msg, agent_path): if path != agent_path: return False dev_path = msg.body[0] if (msg.body and len(msg.body) > 0) else None - if member in ("RequestConfirmation", "RequestAuthorization", "AuthorizeService"): - conn.send(new_method_return(msg)) - trust_device_path(conn, dev_path) - notify_networks_ui() - return True - if member == "RequestPinCode": - conn.send(new_method_return(msg, "s", ("0000",))) - trust_device_path(conn, dev_path) - notify_networks_ui() - return True - if member == "RequestPasskey": - conn.send(new_method_return(msg, "u", (0,))) + if member in ("RequestAuthorization", "AuthorizeService"): + dbus_send_safe(conn, new_method_return(msg)) trust_device_path(conn, dev_path) notify_networks_ui() return True if member in ("DisplayPinCode", "DisplayPasskey"): - conn.send(new_method_return(msg)) + dbus_send_safe(conn, new_method_return(msg)) trust_device_path(conn, dev_path) + if member == "DisplayPinCode": + code_str = str(msg.body[1]) if len(msg.body) >= 2 else "" + entered = 0 + else: + code_num = int(msg.body[1]) if len(msg.body) >= 2 else 0 + entered = int(msg.body[2]) if len(msg.body) >= 3 else 0 + code_str = f"{code_num:06d}" + d_name, d_mac, _ = lookup_agent_device_info(dev_path, dev_props_cache) + write_display_pair_prompt(d_name, d_mac, code_str, entered) notify_networks_ui() return True - if member in ("Cancel", "Release"): - conn.send(new_method_return(msg)) + if member == "RequestConfirmation": + passkey_num = int(msg.body[1]) if len(msg.body) >= 2 else 0 + code_str = f"{passkey_num:06d}" + def _run_confirm(): + d_name, d_mac, d_info = lookup_agent_device_info(dev_path, dev_props_cache) + if is_classic_audio_props(d_info): + dbus_send_safe(conn, new_method_return(msg)) + trust_device_path(conn, dev_path) + notify_networks_ui() + return + accepted, _val, cancelled = request_user_pairing_interaction("CONFIRM", d_name, d_mac, code_str) + if cancelled: + return + if accepted: + dbus_send_safe(conn, new_method_return(msg)) + trust_device_path(conn, dev_path) + else: + dbus_send_safe(conn, new_error(msg, "org.bluez.Error.Rejected", "s", ("Pairing rejected",))) + notify_networks_ui() + threading.Thread(target=_run_confirm, daemon=True).start() return True - conn.send(new_method_return(msg)) + if member == "RequestPinCode": + def _run_pin(): + d_name, d_mac, _ = lookup_agent_device_info(dev_path, dev_props_cache) + accepted, val, cancelled = request_user_pairing_interaction("PIN", d_name, d_mac, "") + if cancelled: + return + pin = (val or "").strip() + if accepted and pin: + dbus_send_safe(conn, new_method_return(msg, "s", (pin,))) + trust_device_path(conn, dev_path) + else: + dbus_send_safe(conn, new_error(msg, "org.bluez.Error.Rejected", "s", ("PIN entry cancelled",))) + notify_networks_ui() + threading.Thread(target=_run_pin, daemon=True).start() + return True + if member == "RequestPasskey": + def _run_passkey(): + d_name, d_mac, _ = lookup_agent_device_info(dev_path, dev_props_cache) + accepted, val, cancelled = request_user_pairing_interaction("PASSKEY", d_name, d_mac, "") + if cancelled: + return + raw = (val or "").strip() + if accepted and raw.isdigit() and 0 <= int(raw) <= 999999: + dbus_send_safe(conn, new_method_return(msg, "u", (int(raw),))) + trust_device_path(conn, dev_path) + else: + dbus_send_safe(conn, new_error(msg, "org.bluez.Error.Rejected", "s", ("Passkey entry cancelled",))) + notify_networks_ui() + threading.Thread(target=_run_passkey, daemon=True).start() + return True + if member in ("Cancel", "Release"): + dbus_send_safe(conn, new_method_return(msg)) + PAIR_CANCEL_EVENT.set() + clear_pair_prompt_files(notify_cancel=True) + return True + dbus_send_safe(conn, new_method_return(msg)) return True def dbus_call_with_agent(conn, call_msg, agent_path, timeout=5.0): from jeepney import HeaderFields, MessageType serial = next(conn.outgoing_serial) - conn.send(call_msg, serial=serial) + dbus_send_safe(conn, call_msg, serial=serial) deadline = time.time() + timeout while time.time() < deadline: rem = max(0.05, deadline - time.time()) @@ -1060,13 +1351,18 @@ def dbus_call_with_agent(conn, call_msg, agent_path, timeout=5.0): def register_bluez_services(conn, profile_path, agent_path): from jeepney import DBusAddress, MessageType, new_method_call + try: + if os.path.exists(AGENT_READY_FILE): + os.unlink(AGENT_READY_FILE) + except OSError: + pass try: aprop = DBusAddress("/org/bluez/hci0", bus_name="org.bluez", interface="org.freedesktop.DBus.Properties") dbus_call_with_agent( conn, new_method_call(aprop, "Set", "ssv", - ("org.bluez.Adapter1", "PairableTimeout", ("u", 60))), + ("org.bluez.Adapter1", "PairableTimeout", ("u", 0))), agent_path, timeout=2.0 ) @@ -1079,22 +1375,33 @@ def register_bluez_services(conn, profile_path, agent_path): ) except Exception: pass + agent_ok = False try: am = DBusAddress("/org/bluez", bus_name="org.bluez", interface="org.bluez.AgentManager1") - dbus_call_with_agent( + rep_reg = dbus_call_with_agent( conn, new_method_call(am, "RegisterAgent", "os", - (agent_path, "NoInputNoOutput")), + (agent_path, "KeyboardDisplay")), agent_path, timeout=3.0 ) - dbus_call_with_agent( + if rep_reg is not None: + if rep_reg.header.message_type == MessageType.method_return: + agent_ok = True + else: + err_s = " ".join(str(x) for x in (rep_reg.body or ())).lower() + if "already" in err_s: + agent_ok = True + rep_def = dbus_call_with_agent( conn, new_method_call(am, "RequestDefaultAgent", "o", (agent_path,)), agent_path, timeout=3.0 ) + if agent_ok and rep_def is not None and rep_def.header.message_type == MessageType.method_return: + ensure_obex_ipc_dir() + write_status(AGENT_READY_FILE, str(os.getpid())) except Exception: pass try: @@ -1168,9 +1475,14 @@ def run_daemon(): from jeepney import DBusAddress, new_method_call, new_method_return, MessageType from jeepney.io.blocking import open_dbus_connection - with open(PID_FILE, "w", encoding="utf-8") as pf: - pf.write(f"{os.getpid()}\n") - + ensure_obex_ipc_dir() + for p in (AGENT_READY_FILE, PAIR_PROMPT_FILE, PAIR_DECISION_FILE): + try: + if os.path.exists(p): + os.unlink(p) + except OSError: + pass + write_status(PID_FILE, str(os.getpid())) write_status(RX_STATUS_FILE, f"IDLE\tReady ({shorten_obex_dir(get_configured_obex_dir())})") notify_networks_ui() @@ -1184,6 +1496,7 @@ def run_daemon(): def stop_handler(_signum, _frame): nonlocal running running = False + PAIR_CANCEL_EVENT.set() try: os.write(wake_w, b"\x01") except OSError: @@ -1192,50 +1505,6 @@ def run_daemon(): signal.signal(signal.SIGTERM, stop_handler) signal.signal(signal.SIGINT, stop_handler) - bt_name = "" - try: - if os.path.exists("/home/user/.config/sxmo/bt_name"): - with open("/home/user/.config/sxmo/bt_name", "r", encoding="utf-8") as nf: - bt_name = nf.readline().strip() - except OSError: - pass - if not bt_name: - try: - bt_name = socket.gethostname().strip() - except Exception: - bt_name = "Bananarchy" - if bt_name: - subprocess.run(["timeout", "2", "bluetoothctl", "system-alias", bt_name], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - - if os.geteuid() == 0: - try: - subprocess.run(["timeout", "2", "/usr/bin/btmgmt", "-i", "hci0", "class", "2", "3"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - except Exception: - pass - - bt_disc = "0" - try: - if os.path.exists("/home/user/.config/sxmo/bt_discoverable"): - with open("/home/user/.config/sxmo/bt_discoverable", "r", encoding="utf-8") as df: - bt_disc = df.readline().strip() or "0" - except OSError: - pass - disc_on = bt_disc.lower() not in ("0", "off", "no", "false") - - subprocess.run(["timeout", "2", "bluetoothctl", "discoverable-timeout", "60"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - subprocess.run(["timeout", "2", "bluetoothctl", "discoverable", "on" if disc_on else "off"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - if disc_on: - subprocess.run(["timeout", "2", "bluetoothctl", "pairable", "on"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - - gp_thread = threading.Thread(target=run_gamepad_uinput_bridge, - args=(lambda: running, wake_r), daemon=True) - gp_thread.start() - def bind_rfcomm_fallback(): s = None try: @@ -1257,32 +1526,103 @@ def run_daemon(): conn = None opp_registered = False rfcomm_listener = None + dev_props_cache = {} + + def refresh_dev_props_cache(dbus_c): + if dbus_c is None: + return + try: + om_a = DBusAddress("/", bus_name="org.bluez", + interface="org.freedesktop.DBus.ObjectManager") + rep = dbus_call_with_agent( + dbus_c, new_method_call(om_a, "GetManagedObjects"), agent_path, timeout=2.5 + ) + if rep is not None and rep.header.message_type == MessageType.method_return and rep.body: + objs = rep.body[0] + if isinstance(objs, dict): + for opath, ifaces in objs.items(): + if isinstance(opath, str) and isinstance(ifaces, dict) and "org.bluez.Device1" in ifaces: + raw = ifaces["org.bluez.Device1"] + if isinstance(raw, dict): + dev_props_cache[opath] = { + k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v) + for k, v in raw.items() + } + except Exception: + pass + try: conn = open_dbus_connection(bus="SYSTEM", enable_fds=True) dbus_bus = DBusAddress("/org/freedesktop/DBus", bus_name="org.freedesktop.DBus", interface="org.freedesktop.DBus") - conn.send(new_method_call( + dbus_send_safe(conn, new_method_call( dbus_bus, "AddMatch", "s", ("type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.bluez'",) )) - conn.send(new_method_call( + dbus_send_safe(conn, new_method_call( dbus_bus, "AddMatch", "s", ("type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Device1'",) )) + dbus_send_safe(conn, new_method_call( + dbus_bus, "AddMatch", "s", + ("type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesAdded'",) + )) for _attempt in range(10): if not running: break opp_registered = register_bluez_services(conn, profile_path, agent_path) - if opp_registered: - break - time.sleep(0.4) + if opp_registered or os.path.exists(AGENT_READY_FILE): + if opp_registered: + break + time.sleep(0.3) + refresh_dev_props_cache(conn) except Exception: pass if running and not opp_registered: rfcomm_listener = bind_rfcomm_fallback() + prepare_bt_controller() + + bt_name = "" + try: + if os.path.exists("/home/user/.config/sxmo/bt_name"): + with open("/home/user/.config/sxmo/bt_name", "r", encoding="utf-8") as nf: + bt_name = nf.readline().strip() + except OSError: + pass + if not bt_name: + try: + bt_name = socket.gethostname().strip() + except Exception: + bt_name = "Bananarchy" + if bt_name: + subprocess.run(["timeout", "2", "bluetoothctl", "system-alias", bt_name], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + bt_disc = "0" + try: + if os.path.exists("/home/user/.config/sxmo/bt_discoverable"): + with open("/home/user/.config/sxmo/bt_discoverable", "r", encoding="utf-8") as df: + bt_disc = df.readline().strip() or "0" + except OSError: + pass + disc_on = bt_disc.lower() not in ("0", "off", "no", "false") + + subprocess.run(["timeout", "2", "bluetoothctl", "pairable-timeout", "0"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + subprocess.run(["timeout", "2", "bluetoothctl", "pairable", "on"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + subprocess.run(["timeout", "2", "bluetoothctl", "discoverable-timeout", "60"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + subprocess.run(["timeout", "2", "bluetoothctl", "discoverable", "on" if disc_on else "off"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + gp_thread = threading.Thread(target=run_gamepad_uinput_bridge, + args=(lambda: running, wake_r), daemon=True) + gp_thread.start() + while running: try: if conn is not None: @@ -1300,7 +1640,7 @@ def run_daemon(): break if msg is None: break - if handle_agent_method_call(conn, msg, agent_path): + if handle_agent_method_call(conn, msg, agent_path, dev_props_cache=dev_props_cache): pass elif msg.header.message_type == MessageType.method_call: member = msg.header.fields.get(3) # Member name @@ -1309,22 +1649,23 @@ def run_daemon(): # Args: (o device, h fd, a{sv} fd_properties) dev_path, fd_obj, _props = msg.body reply = new_method_return(msg) - conn.send(reply) + dbus_send_safe(conn, reply) raw_fd = os.dup(fd_obj.fileno()) fd_obj.close() client_sock = socket.socket(fileno=raw_fd) - s_name, s_mac = lookup_bt_device_label(conn, dev_path, agent_path) + s_name, s_mac, _ = lookup_agent_device_info(dev_path, dev_props_cache) t = threading.Thread(target=handle_obex_rx_session, args=(client_sock, s_name, s_mac), daemon=True) t.start() elif path == profile_path and member in ("RequestDisconnection", "Release"): reply = new_method_return(msg) - conn.send(reply) + dbus_send_safe(conn, reply) elif msg.header.message_type == MessageType.signal: member = msg.header.fields.get(3) if member == "NameOwnerChanged" and msg.body and len(msg.body) >= 3: name, _old_owner, new_owner = msg.body[0], msg.body[1], msg.body[2] if name == "org.bluez" and new_owner: + dev_props_cache.clear() if rfcomm_listener is not None: try: rfcomm_listener.close() @@ -1334,9 +1675,33 @@ def run_daemon(): opp_registered = register_bluez_services(conn, profile_path, agent_path) if not opp_registered: rfcomm_listener = bind_rfcomm_fallback() + refresh_dev_props_cache(conn) + elif member == "InterfacesAdded" and msg.body and len(msg.body) >= 2: + opath, ifaces = msg.body[0], msg.body[1] + if isinstance(opath, str) and isinstance(ifaces, dict) and "org.bluez.Device1" in ifaces: + raw = ifaces["org.bluez.Device1"] + if isinstance(raw, dict): + dev_props_cache[opath] = { + k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v) + for k, v in raw.items() + } elif member == "PropertiesChanged" and msg.body and len(msg.body) >= 2: + obj_path = msg.header.fields.get(1) iface, changed = msg.body[0], msg.body[1] if iface == "org.bluez.Device1" and isinstance(changed, dict): + if isinstance(obj_path, str): + entry = dev_props_cache.setdefault(obj_path, {}) + for k, v in changed.items(): + entry[k] = v[1] if (isinstance(v, (tuple, list)) and len(v) == 2) else v + if changed.get("Paired"): + try: + if os.path.exists(PAIR_PROMPT_FILE): + with open(PAIR_PROMPT_FILE, "r", encoding="utf-8", errors="replace") as pf: + pln = pf.readline() + if "\tDISPLAY\t" in pln: + clear_pair_prompt_files(notify_cancel=True) + except OSError: + pass if any(k in changed for k in ("Connected", "Paired", "Bonded")): notify_networks_ui() @@ -1346,7 +1711,7 @@ def run_daemon(): csock, addr = rfcomm_listener.accept() rmac = addr[0].upper() if isinstance(addr, (tuple, list)) and addr else "" dpath = ("/org/bluez/hci0/dev_" + rmac.replace(":", "_")) if rmac else "" - s_name, s_mac = lookup_bt_device_label(conn, dpath, agent_path) + s_name, s_mac, _ = lookup_agent_device_info(dpath, dev_props_cache) t = threading.Thread(target=handle_obex_rx_session, args=(csock, s_name, s_mac or rmac), daemon=True) t.start() @@ -1376,11 +1741,13 @@ def run_daemon(): os.close(fd) except OSError: pass - try: - if os.path.exists(PID_FILE): - os.unlink(PID_FILE) - except OSError: - pass + clear_pair_prompt_files(notify_cancel=True) + for p in (PID_FILE, AGENT_READY_FILE): + try: + if os.path.exists(p): + os.unlink(p) + except OSError: + pass def connect_opp_socket(mac): @@ -1560,22 +1927,50 @@ def send_file_obex(mac, filepath): pass +def is_daemon_pid_alive(pid): + if pid <= 0 or pid == os.getpid(): + return False + try: + with open(f"/proc/{pid}/cmdline", "rb") as cf: + cmd = cf.read().replace(b"\x00", b" ").decode("utf-8", "replace") + return ("bananarchy-bt-obex" in cmd) and (" daemon" in cmd) + except OSError: + return False + + +def find_running_daemon_pids(): + pids = [] + try: + for entry in os.listdir("/proc"): + if entry.isdigit(): + pid = int(entry) + if is_daemon_pid_alive(pid): + pids.append(pid) + except OSError: + pass + return pids + + def ensure_daemon_running(): - if os.path.exists(PID_FILE): + if find_running_daemon_pids() and os.path.exists(AGENT_READY_FILE): + return + if not find_running_daemon_pids(): try: - with open(PID_FILE, "r", encoding="utf-8") as f: - pid = int(f.read().strip()) - os.kill(pid, 0) - return + if os.geteuid() != 0: + subprocess.Popen(["doas", "-n", "/usr/bin/bananarchy-bt-obex", "daemon"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True) + else: + subprocess.Popen([sys.executable, __file__, "daemon"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True) except Exception: pass - try: - subprocess.Popen([sys.executable, __file__, "daemon"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, - start_new_session=True) - time.sleep(0.25) - except Exception: - pass + deadline = time.monotonic() + 1.5 + while time.monotonic() < deadline: + if find_running_daemon_pids() and os.path.exists(AGENT_READY_FILE): + return + time.sleep(0.05) def prepare_bt_controller(): @@ -1666,6 +2061,8 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): conn = None nonlocal_conn = [None] + cli_registered = False + use_cli_agent = not (bool(find_running_daemon_pids()) and os.path.exists(AGENT_READY_FILE)) try: conn = open_dbus_connection(bus="SYSTEM") nonlocal_conn[0] = conn @@ -1674,23 +2071,32 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): dbus_call_with_agent( conn, new_method_call(aprop_addr, "Set", "ssv", - ("org.bluez.Adapter1", "Pairable", ("b", True))), + ("org.bluez.Adapter1", "PairableTimeout", ("u", 0))), cli_agent_path, timeout=2.0 ) dbus_call_with_agent( conn, - new_method_call(am_addr, "RegisterAgent", "os", - (cli_agent_path, "NoInputNoOutput")), + new_method_call(aprop_addr, "Set", "ssv", + ("org.bluez.Adapter1", "Pairable", ("b", True))), cli_agent_path, - timeout=2.5 - ) - dbus_call_with_agent( - conn, - new_method_call(am_addr, "RequestDefaultAgent", "o", (cli_agent_path,)), - cli_agent_path, - timeout=2.5 + timeout=2.0 ) + if use_cli_agent: + dbus_call_with_agent( + conn, + new_method_call(am_addr, "RegisterAgent", "os", + (cli_agent_path, "KeyboardDisplay")), + cli_agent_path, + timeout=2.5 + ) + cli_registered = True + dbus_call_with_agent( + conn, + new_method_call(am_addr, "RequestDefaultAgent", "o", (cli_agent_path,)), + cli_agent_path, + timeout=2.5 + ) def pump_agent(duration): end_t = time.time() + duration @@ -1758,6 +2164,8 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): score += 100 if is_classic_audio_props(dprops): score += 60 + elif is_phone_or_computer_props(dprops): + score += 50 if addr_type == "public": score += 40 elif addr_type == "random" and not is_hog_device_props(dprops): @@ -1840,6 +2248,7 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): p = get_dev_props(dpath) set_hog_preferred_bearer(nonlocal_conn[0], dpath, p) set_audio_preferred_bearer(nonlocal_conn[0], dpath, p) + set_preferred_bearer_for_device(nonlocal_conn[0], dpath, p) trust_device_path(nonlocal_conn[0], dpath) if p is None: return False @@ -1856,23 +2265,41 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): interface="org.bluez.Device1") if want_pair and not (p.get("Paired") or p.get("Bonded")): rep = dbus_call_with_agent( - nonlocal_conn[0], new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=8.0 - ) - if rep is None: - cancel_pending_connect(dpath) - p = get_dev_props(dpath) or {} - set_hog_preferred_bearer(nonlocal_conn[0], dpath, p) - set_audio_preferred_bearer(nonlocal_conn[0], dpath, p) - - if not p.get("Connected"): - rep = dbus_call_with_agent( - nonlocal_conn[0], new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=8.0 + nonlocal_conn[0], new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=50.0 ) if rep is None: cancel_pending_connect(dpath) elif rep.header.message_type == MessageType.error: err_str = " ".join(str(x) for x in (rep.body or ())).lower() - if "key-missing" in err_str or "authentication" in err_str: + if "key-missing" in err_str: + dev_mac = dpath.split("dev_")[-1].replace("_", ":") + if clear_stale_linkkey(dev_mac): + prepare_bt_controller() + if not use_cli_agent: + w_end = time.monotonic() + 2.0 + while time.monotonic() < w_end and not os.path.exists(AGENT_READY_FILE): + time.sleep(0.05) + rep = dbus_call_with_agent( + nonlocal_conn[0], new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=50.0 + ) + p = get_dev_props(dpath) or {} + set_hog_preferred_bearer(nonlocal_conn[0], dpath, p) + set_audio_preferred_bearer(nonlocal_conn[0], dpath, p) + set_preferred_bearer_for_device(nonlocal_conn[0], dpath, p) + + if is_phone_or_computer_props(p) and want_pair and (p.get("Paired") or p.get("Bonded")): + trust_device_path(nonlocal_conn[0], dpath) + return True + + if not p.get("Connected"): + rep = dbus_call_with_agent( + nonlocal_conn[0], new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=12.0 + ) + if rep is None: + cancel_pending_connect(dpath) + elif rep.header.message_type == MessageType.error: + err_str = " ".join(str(x) for x in (rep.body or ())).lower() + if "key-missing" in err_str or ("authentication" in err_str and "rejected" not in err_str and "canceled" not in err_str): dev_mac = dpath.split("dev_")[-1].replace("_", ":") if clear_stale_linkkey(dev_mac): try: @@ -1888,28 +2315,37 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): cli_agent_path, timeout=2.0 ) - dbus_call_with_agent( - conn_new, - new_method_call(am_addr, "RegisterAgent", "os", - (cli_agent_path, "NoInputNoOutput")), - cli_agent_path, - timeout=2.5 - ) - dbus_call_with_agent( - conn_new, - new_method_call(am_addr, "RequestDefaultAgent", "o", (cli_agent_path,)), - cli_agent_path, - timeout=2.5 - ) + if use_cli_agent: + dbus_call_with_agent( + conn_new, + new_method_call(am_addr, "RegisterAgent", "os", + (cli_agent_path, "KeyboardDisplay")), + cli_agent_path, + timeout=2.5 + ) + dbus_call_with_agent( + conn_new, + new_method_call(am_addr, "RequestDefaultAgent", "o", (cli_agent_path,)), + cli_agent_path, + timeout=2.5 + ) + else: + w_end = time.monotonic() + 2.0 + while time.monotonic() < w_end and not os.path.exists(AGENT_READY_FILE): + time.sleep(0.05) + prepare_bt_controller() trust_device_path(conn_new, dpath) set_hog_preferred_bearer(conn_new, dpath, p) set_audio_preferred_bearer(conn_new, dpath, p) + set_preferred_bearer_for_device(conn_new, dpath, p) dbus_call_with_agent( - conn_new, new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=8.0 - ) - dbus_call_with_agent( - conn_new, new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=8.0 + conn_new, new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=50.0 ) + p_after = get_dev_props(dpath) or p + if not (is_phone_or_computer_props(p_after) and (p_after.get("Paired") or p_after.get("Bonded"))): + dbus_call_with_agent( + conn_new, new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=12.0 + ) p = get_dev_props(dpath) or {} if is_classic_audio_props(p) and (not p.get("Connected") or not has_media_transport(dpath)): @@ -2012,15 +2448,16 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): finally: c_final = nonlocal_conn[0] if c_final is not None: - try: - dbus_call_with_agent( - c_final, - new_method_call(am_addr, "UnregisterAgent", "o", (cli_agent_path,)), - cli_agent_path, - timeout=1.5 - ) - except Exception: - pass + if cli_registered: + try: + dbus_call_with_agent( + c_final, + new_method_call(am_addr, "UnregisterAgent", "o", (cli_agent_path,)), + cli_agent_path, + timeout=1.5 + ) + except Exception: + pass try: c_final.close() except Exception: @@ -2028,43 +2465,35 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): def stop_daemon(): - pids = set() + pids = set(find_running_daemon_pids()) if os.path.exists(PID_FILE): try: with open(PID_FILE, "r", encoding="utf-8") as f: pid = int(f.read().strip()) pids.add(pid) - os.kill(pid, signal.SIGTERM) except Exception: pass - try: - os.unlink(PID_FILE) - except OSError: - pass - # The target rootfs is BusyBox-based and does not ship an external process - # killer, so find stale daemon command lines through /proc instead. - try: - for entry in os.listdir("/proc"): - if not entry.isdigit() or int(entry) == os.getpid(): - continue - try: - with open("/proc/" + entry + "/cmdline", "rb") as cf: - cmd = cf.read().replace(b"\x00", b" ").decode("utf-8", "replace") - except OSError: - continue - if "bananarchy-bt-obex" in cmd and " daemon" in cmd: - pids.add(int(entry)) - except OSError: - pass for pid in pids: try: os.kill(pid, signal.SIGTERM) except OSError: pass + clear_pair_prompt_files(notify_cancel=True) + for p in (PID_FILE, AGENT_READY_FILE): + try: + if os.path.exists(p): + os.unlink(p) + except OSError: + pass def main(): - cmd = sys.argv[1] if len(sys.argv) > 1 else "status" + args = sys.argv[1:] + async_ui = False + if "--async-ui" in args: + async_ui = True + args = [a for a in args if a != "--async-ui"] + cmd = args[0] if len(args) > 0 else "status" if cmd == "daemon": run_daemon() elif cmd == "start": @@ -2073,27 +2502,28 @@ def main(): elif cmd == "stop": stop_daemon() return 0 - elif cmd == "connect": - if len(sys.argv) < 3: - print("Usage: bananarchy-bt-obex connect [name]", file=sys.stderr) + elif cmd in ("connect", "pair"): + if len(args) < 2: + print(f"Usage: bananarchy-bt-obex {cmd} [name]", file=sys.stderr) return 1 - nm = sys.argv[3] if len(sys.argv) >= 4 else "" - return connect_or_pair_bt_device(sys.argv[2], nm, do_pair=False) - elif cmd == "pair": - if len(sys.argv) < 3: - print("Usage: bananarchy-bt-obex pair [name]", file=sys.stderr) - return 1 - nm = sys.argv[3] if len(sys.argv) >= 4 else "" - return connect_or_pair_bt_device(sys.argv[2], nm, do_pair=True) + mac = args[1] + nm = args[2] if len(args) >= 3 else "" + rc = connect_or_pair_bt_device(mac, nm, do_pair=(cmd == "pair")) + if async_ui: + ensure_obex_ipc_dir() + safe_nm = str(nm or mac).replace("\t", " ").replace("\n", " ").strip() + write_status(OP_DONE_FILE, f"{rc}\t{cmd}\t{mac.strip().upper()}\t{safe_nm}") + notify_networks_ui("BT_OP_DONE\n") + return rc elif cmd == "clear-linkkey": - if len(sys.argv) < 3: + if len(args) < 2: return 1 - return 0 if clear_stale_linkkey(sys.argv[2]) else 1 + return 0 if clear_stale_linkkey(args[1]) else 1 elif cmd == "send": - if len(sys.argv) < 4: + if len(args) < 3: print("Usage: bananarchy-bt-obex send ", file=sys.stderr) return 1 - return send_file_obex(sys.argv[2], sys.argv[3]) + return send_file_obex(args[1], args[2]) elif cmd == "status": if os.path.exists(RX_STATUS_FILE): with open(RX_STATUS_FILE, "r", encoding="utf-8") as f: diff --git a/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh b/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh index f9b626f..c5d5039 100755 --- a/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh +++ b/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh @@ -25,8 +25,10 @@ on() { if [ -s /etc/bananarchy/bt_mac ] && [ -x /usr/bin/bananarchy-engmenu-ctl ]; then /usr/bin/bananarchy-engmenu-ctl apply-boot >/dev/null 2>&1 || true fi + /usr/bin/bananarchy-bt-le-enable.sh >/dev/null 2>&1 || true timeout 2 /usr/bin/btmgmt -i hci0 class 2 3 >/dev/null 2>&1 || true timeout 2 bluetoothctl power on >/dev/null 2>&1 || true + /usr/bin/bananarchy-bt-le-enable.sh >/dev/null 2>&1 || true timeout 2 /usr/bin/btmgmt -i hci0 class 2 3 >/dev/null 2>&1 || true bt_name="" @@ -44,10 +46,11 @@ on() { if [ -r /home/user/.config/sxmo/bt_discoverable ]; then IFS= read -r bt_disc < /home/user/.config/sxmo/bt_discoverable 2>/dev/null || true fi + timeout 2 bluetoothctl pairable-timeout 0 >/dev/null 2>&1 || true + timeout 2 bluetoothctl pairable on >/dev/null 2>&1 || true timeout 2 bluetoothctl discoverable-timeout 60 >/dev/null 2>&1 || true case "$bt_disc" in 1|on|ON|yes|YES|true|TRUE) - timeout 2 bluetoothctl pairable on >/dev/null 2>&1 || true timeout 2 bluetoothctl discoverable on >/dev/null 2>&1 || true ;; *) @@ -55,7 +58,7 @@ on() { ;; esac - /usr/bin/bananarchy-bt-obex start >/dev/null 2>&1 & + /usr/bin/bananarchy-bt-obex start >/dev/null 2>&1 || true } off() { diff --git a/overlay/rootfs/usr/lib/dwm/plugins/networks.so b/overlay/rootfs/usr/lib/dwm/plugins/networks.so index 7de2cbb..6213a44 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/networks.so and b/overlay/rootfs/usr/lib/dwm/plugins/networks.so differ diff --git a/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_start.sh b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_start.sh index 386eaa5..e82bb52 100755 --- a/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_start.sh +++ b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_start.sh @@ -153,5 +153,8 @@ superctl start sxmo_notificationmonitor ( sxmo_hook_apps.sh >/dev/null 2>&1 || true sxmo_hook_scripts.sh >/dev/null 2>&1 || true + if [ "$(/usr/bin/sxmo_bluetoothtoggle.sh status 2>/dev/null)" = "on" ]; then + SXMO_OS=alpine doas -n /usr/bin/sxmo_bluetoothtoggle.sh on >/dev/null 2>&1 || true + fi ) & ) diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so index 7de2cbb..6213a44 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so differ diff --git a/scripts/check-rebuild.sh b/scripts/check-rebuild.sh index 8acf8b1..33d3ad1 100755 --- a/scripts/check-rebuild.sh +++ b/scripts/check-rebuild.sh @@ -557,15 +557,15 @@ fi echo "[check] Known-good flashable image set..." for pair in \ - "92b23d34180c157861c492e7c2ea848ea4580857f3c1674020ae6b9f6fbdd39f images/bananarchy-nokia-argon.img" \ - "5c284c314a378d09fda37e56ebe745ab557d45c77499206440e8c362c709e7a7 images/bananarchy-nokia-beatles.img" \ - "80485ccf2af4f1d6107965ecde43d888c66ec19006e6feabc7fb63b6a7852391 images/boot-bananarchy-nokia-beatles.img" \ + "09c46d21b140b486e21ebed39740b57808f8f1f0045f1801af2a7f8eba72bb4d images/bananarchy-nokia-argon.img" \ + "5d8c50f89e257dbadd9050479d56c46b1902cb38707f6f692e3508b44aa4fd10 images/bananarchy-nokia-beatles.img" \ + "f6c897f8e5fac17df38ac3d3222279f229b84c53ea73c323d06de5c40b26ccc0 images/boot-bananarchy-nokia-beatles.img" \ "b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d images/boot-lk2nd-nokia-beatles-display.img" \ - "4e1d4799d42f56423f9cba8e175adf3b1f6c7fcd89965a7bc0b84a4f03ebc6e5 images/bananarchy-nokia-coconut.img" \ - "1e22879fc0533f419dc98c88a1700d75101fda85669837d1457bb15b9ab4ed9c images/boot-bananarchy-nokia-coconut.img" \ + "836331fb3034d0527f8c03eb90aae25bc8c87a84cc56baf24459d2e81e7a28d1 images/bananarchy-nokia-coconut.img" \ + "6e2fefec812594dc7b4dc322c68b1ab4c10b1c93abee4a0fbd11dfbf2dc59a0b images/boot-bananarchy-nokia-coconut.img" \ "e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a images/boot-lk2nd-nokia-coconut-display.img" \ - "6b40db4674821bdde80d6f7619acc5a6414df684201d3e4e2e7cc3ac6c25dcfd images/bananarchy-nokia-sparkler.img" \ - "8f41328f0197f5debba92eaffa9df46c530721719309024a4d9cd7bf79a722c7 images/boot-bananarchy-nokia-sparkler.img" \ + "61a068ca432f064812a96356b0dc49f1a38102a717c8dccd31768f0cbd1d7639 images/bananarchy-nokia-sparkler.img" \ + "4357d48ac069104495629f1f35e220a01cde3412950e73e3e47e5372649fb6a2 images/boot-bananarchy-nokia-sparkler.img" \ "bc41c2ddd1079246a7e91a40222fcafb82b0b52965c8ee8081872767d006748f images/boot-lk2nd-nokia-sparkler-display.img"; do set -- $pair want=$1 @@ -2043,11 +2043,19 @@ if ! "$BT_HEADSET_TEST" >/dev/null 2>&1; then fail "host Bluetooth headset verification failed" fi -echo "[check] Bluetooth OBEX phone CoD, L2CAP SEQPACKET, and confirmation dialog..." +echo "[check] Bluetooth OBEX phone CoD, L2CAP SEQPACKET, pairing agent, and confirmation dialog..." BT_OBEX_TEST="$BASE_DIR/scripts/test-bluetooth-obex.py" if [ ! -x "$BT_OBEX_TEST" ]; then fail "missing host unit test scripts/test-bluetooth-obex.py" fi +if ! grep -qF 'Class = 0x5a020c' "$BT_MAIN_CONF" || \ + ! grep -qF 'PairableTimeout = 0' "$BT_MAIN_CONF" || \ + ! grep -qF 'btmgmt -i hci0 ssp on' "$BASE_DIR/overlay/rootfs/usr/bin/bananarchy-bt-le-enable.sh" || \ + ! grep -qF '"KeyboardDisplay"' "$BT_OBEX" || \ + ! grep -qF 'PAIR_PROMPT' "$BASE_DIR/src/dwm-plugins/networks_plugin.cpp" || \ + ! grep -qF 'BtPairingPrompt' "$BASE_DIR/src/dwm-plugins/networks_plugin.cpp"; then + fail "Bluetooth OBEX or KeyboardDisplay pairing dialog configuration is missing" +fi if ! "$BT_OBEX_TEST" >/dev/null 2>&1; then fail "host Bluetooth OBEX verification failed" fi diff --git a/scripts/test-bluetooth-headset.py b/scripts/test-bluetooth-headset.py index 388e407..e8b6734 100755 --- a/scripts/test-bluetooth-headset.py +++ b/scripts/test-bluetooth-headset.py @@ -60,6 +60,7 @@ def load_obex_pure_helpers(): tree = ast.parse(src, filename=str(BT_OBEX)) wanted_assigns = {"CLASSIC_AUDIO_UUID_PREFIXES"} wanted_defs = { + "is_phone_or_computer_props", "is_hog_device_props", "is_classic_audio_props", "avrcp_fifo_command_for_key", @@ -107,6 +108,7 @@ def test_wireplumber_config(): def test_obex_bearer_and_avrcp(): ns = load_obex_pure_helpers() + is_phone = ns["is_phone_or_computer_props"] is_hog = ns["is_hog_device_props"] is_audio = ns["is_classic_audio_props"] map_avrcp = ns["avrcp_fifo_command_for_key"] @@ -122,11 +124,23 @@ def test_obex_bearer_and_avrcp(): "Icon": "audio-headset", "Class": 0x240404, } + android_phone = { + "AddressType": "public", + "Icon": "phone", + "Class": 0x5a020c, + "UUIDs": [ + "00001105-0000-1000-8000-00805f9b34fb", + "0000110a-0000-1000-8000-00805f9b34fb", + "0000111f-0000-1000-8000-00805f9b34fb", + ], + } ble_beacon = {"AddressType": "random", "UUIDs": ["00001800-0000-1000-8000-00805f9b34fb"]} cod_only_speaker = {"Class": 0x200414} require(is_hog(hog_kbd) and not is_audio(hog_kbd), "HOGP keyboard misclassified as Classic Audio") + require(is_phone(android_phone) and not is_audio(android_phone), + "Android phone with Audio Source/HFP-AG UUIDs misclassified as Classic Audio") require(is_audio(bt5_dual_buds) and not is_hog(bt5_dual_buds), "Dual-mode BT 5.x/6.x headset not recognized for BR/EDR bearer selection") require(is_audio({"Icon": "audio-headphones"}), @@ -163,14 +177,17 @@ def test_discoverability_and_power(): obex_src = read(BT_OBEX) toggle_src = read(BT_TOGGLE) net_src = read(NETWORKS_CPP) + main_src = read(BASE / "overlay/rootfs/etc/bluetooth/main.conf") + require('DiscoverableTimeout = 60' in main_src and 'PairableTimeout = 0' in main_src, + "main.conf must enforce DiscoverableTimeout = 60 and PairableTimeout = 0") require('discoverable-timeout 0' not in toggle_src, "sxmo_bluetoothtoggle.sh still sets infinite discoverable-timeout 0") require('discoverable-timeout 60' in toggle_src and 'bt_disc="0"' in toggle_src, "sxmo_bluetoothtoggle.sh must default bt_disc=0 and timeout=60") require('"discoverable-timeout", "0"' not in obex_src and - '("org.bluez.Adapter1", "PairableTimeout", ("u", 0))' not in obex_src, - "bananarchy-bt-obex still forces infinite discoverable/pairable timeout 0") + '("org.bluez.Adapter1", "PairableTimeout", ("u", 0))' in obex_src, + "bananarchy-bt-obex must bound discoverable-timeout to 60 and keep PairableTimeout=0") require('"discoverable-timeout", "60"' in obex_src and 'bt_disc = "0"' in obex_src, "bananarchy-bt-obex must default bt_disc='0' and timeout=60") require("discoverable-timeout 0" not in net_src and diff --git a/scripts/test-bluetooth-obex.py b/scripts/test-bluetooth-obex.py index 90bbf7c..3213145 100755 --- a/scripts/test-bluetooth-obex.py +++ b/scripts/test-bluetooth-obex.py @@ -52,16 +52,24 @@ def load_obex_module(): def test_class_and_roles(): main_conf = read(MAIN_CONF) + le_src = read(LE_HELPER) + toggle_src = read(BT_TOGGLE) require("ControllerMode = dual" in main_conf, "main.conf must keep ControllerMode = dual") require("Class = 0x5a020c" in main_conf, "main.conf missing Smartphone Class = 0x5a020c") - require("btmgmt -i hci0 class 2 3" in read(LE_HELPER), - "bananarchy-bt-le-enable.sh missing btmgmt class 2 3") - require("btmgmt -i hci0 class 2 3" in read(BT_TOGGLE), + require("PairableTimeout = 0" in main_conf, "main.conf must keep PairableTimeout = 0") + for cmd in ("btmgmt -i hci0 bredr on", "btmgmt -i hci0 ssp on", + "btmgmt -i hci0 linksec on", "btmgmt -i hci0 bondable on", + "btmgmt -i hci0 advertising off", "btmgmt -i hci0 class 2 3", + "btmgmt -i hci0 le on"): + require(cmd in le_src, f"bananarchy-bt-le-enable.sh missing {cmd}") + require("btmgmt -i hci0 class 2 3" in toggle_src, "sxmo_bluetoothtoggle.sh missing btmgmt class 2 3") + require("pairable-timeout 0" in toggle_src and "pairable on" in toggle_src, + "sxmo_bluetoothtoggle.sh must keep pairable on with timeout 0") wp = read(WP_CONF) require("a2dp_source" not in wp and "bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ]" in wp, "50-bluetooth.conf must omit a2dp_source so phones do not treat us as an audio sink") - print("[ok] Smartphone Class-of-Device and Phone/OPP SDP profile role gate") + print("[ok] Smartphone Class-of-Device, MGMT SSP/bondable flags, and OPP role gate") def build_obex_put_headers(filename, total_len): @@ -243,24 +251,243 @@ def test_accept_and_reject_sessions(mod): print("[ok] Incoming OBEX Accept/Reject & custom target directory loopback sessions") +def _ensure_jeepney_available(): + try: + import jeepney # noqa: F401 + return None + except ImportError: + jmod = types.ModuleType("jeepney") + + class MessageType: + method_call = 1 + method_return = 2 + error = 3 + signal = 4 + + class Header: + def __init__(self, mtype, fields=None, serial=1): + self.message_type = mtype + self.fields = dict(fields or {}) + self.serial = serial + + class Message: + def __init__(self, header, body=()): + self.header = header + self.body = body + + class DBusAddress: + def __init__(self, object_path, bus_name=None, interface=None): + self.object_path = object_path + self.bus_name = bus_name + self.interface = interface + + def new_method_call(addr, member, signature=None, body=()): + fields = {1: addr.object_path, 2: addr.interface, 3: member} + return Message(Header(MessageType.method_call, fields), body) + + def new_method_return(parent_msg, signature=None, body=()): + fields = {5: parent_msg.header.serial} + if signature is not None: + fields[8] = signature + return Message(Header(MessageType.method_return, fields), body) + + def new_error(parent_msg, error_name, signature=None, body=()): + fields = {4: error_name, 5: parent_msg.header.serial} + if signature is not None: + fields[8] = signature + return Message(Header(MessageType.error, fields), body) + + jmod.MessageType = MessageType + jmod.Header = Header + jmod.Message = Message + jmod.DBusAddress = DBusAddress + jmod.new_method_call = new_method_call + jmod.new_method_return = new_method_return + jmod.new_error = new_error + sys.modules["jeepney"] = jmod + return jmod + + +def _make_agent_call(member, dev_path, extra_args=(), serial=77): + from jeepney import MessageType + try: + from jeepney.low_level import Header, Message + hdr = Header(MessageType.method_call) + hdr.serial = serial + hdr.fields = {1: "/org/bananarchy/bt_agent", 3: member} + return Message(hdr, (dev_path,) + extra_args) + except ImportError: + import jeepney + return jeepney.Message( + jeepney.Header(MessageType.method_call, {1: "/org/bananarchy/bt_agent", 3: member}, serial=serial), + (dev_path,) + extra_args, + ) + + +def test_keyboard_display_agent(mod): + injected = _ensure_jeepney_available() + from jeepney import MessageType + old_no_ui = os.environ.get("BANANARCHY_OBEX_NO_UI") + os.environ["BANANARCHY_OBEX_NO_UI"] = "1" + orig_vals = ( + mod.OBEX_IPC_DIR, + mod.PAIR_PROMPT_FILE, + mod.PAIR_DECISION_FILE, + ) + + class RecordingConn: + def __init__(self): + self.sent = [] + self.ev = threading.Event() + + def send(self, msg, serial=None): + self.sent.append(msg) + self.ev.set() + + def wait_sent(rc, min_count, timeout=3.0): + deadline = time.monotonic() + timeout + while len(rc.sent) < min_count and time.monotonic() < deadline: + rc.ev.clear() + rc.ev.wait(0.05) + require(len(rc.sent) >= min_count, f"expected >= {min_count} sent replies, got {len(rc.sent)}") + + def wait_prompt(p_path, timeout=3.0): + deadline = time.monotonic() + timeout + while not p_path.exists() and time.monotonic() < deadline: + time.sleep(0.02) + require(p_path.exists(), "pair_prompt.tsv was never created") + return p_path.read_text(encoding="utf-8").strip().split("\t") + + try: + with tempfile.TemporaryDirectory(prefix="bananarchy-pair-test-") as tmp: + root = pathlib.Path(tmp) + ipc = root / "ipc" + ipc.mkdir() + mod.OBEX_IPC_DIR = str(ipc) + mod.PAIR_PROMPT_FILE = str(ipc / "pair_prompt.tsv") + mod.PAIR_DECISION_FILE = str(ipc / "pair_decision.tsv") + p_file = pathlib.Path(mod.PAIR_PROMPT_FILE) + d_file = pathlib.Path(mod.PAIR_DECISION_FILE) + agent_path = "/org/bananarchy/bt_agent" + phone_path = "/org/bluez/hci0/dev_11_22_33_44_55_66" + buds_path = "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF" + cache = { + phone_path: {"Name": "Android Pixel", "Icon": "phone", "Class": 0x5a020c, + "UUIDs": ["00001105-0000-1000-8000-00805f9b34fb"]}, + buds_path: {"Name": "Test Buds", "Icon": "audio-headset", "Class": 0x240404, + "UUIDs": ["0000110b-0000-1000-8000-00805f9b34fb"]}, + } + + # 1. RequestConfirmation for phone -> prompt & accept + rc = RecordingConn() + msg = _make_agent_call("RequestConfirmation", phone_path, (42719,), serial=10) + require(mod.handle_agent_method_call(rc, msg, agent_path, dev_props_cache=cache), + "RequestConfirmation not handled") + cols = wait_prompt(p_file) + require(cols[1] == "CONFIRM" and cols[2] == "Android Pixel" and cols[4] == "042719", + f"unexpected CONFIRM prompt: {cols}") + d_file.write_text(f"{cols[0]}\tACCEPT\t\n", encoding="utf-8") + wait_sent(rc, 2) + require(rc.sent[0].header.message_type == MessageType.method_return, + "accepted RequestConfirmation must reply method_return") + require("Trusted" in str(rc.sent[1].body), "accepted phone must be trusted") + + # 2. RequestConfirmation for phone -> reject + rc = RecordingConn() + msg = _make_agent_call("RequestConfirmation", phone_path, (991100,), serial=11) + mod.handle_agent_method_call(rc, msg, agent_path, dev_props_cache=cache) + cols = wait_prompt(p_file) + d_file.write_text(f"{cols[0]}\tREJECT\t\n", encoding="utf-8") + wait_sent(rc, 1) + require(rc.sent[0].header.message_type == MessageType.error and + "Rejected" in str(rc.sent[0].header.fields), + "rejected RequestConfirmation must return org.bluez.Error.Rejected") + + # 3. RequestConfirmation for Classic Audio headset -> auto-confirm with no prompt + rc = RecordingConn() + msg = _make_agent_call("RequestConfirmation", buds_path, (0,), serial=12) + mod.handle_agent_method_call(rc, msg, agent_path, dev_props_cache=cache) + wait_sent(rc, 2) + require(not p_file.exists() and rc.sent[0].header.message_type == MessageType.method_return, + "Classic Audio headset must auto-confirm without blocking prompt") + + # 4. RequestPinCode -> custom user PIN + rc = RecordingConn() + msg = _make_agent_call("RequestPinCode", phone_path, (), serial=13) + mod.handle_agent_method_call(rc, msg, agent_path, dev_props_cache=cache) + cols = wait_prompt(p_file) + require(cols[1] == "PIN", f"expected PIN prompt, got {cols}") + d_file.write_text(f"{cols[0]}\tACCEPT\t5829\n", encoding="utf-8") + wait_sent(rc, 2) + require(rc.sent[0].header.message_type == MessageType.method_return and + rc.sent[0].body == ("5829",), + f"RequestPinCode reply mismatch: {rc.sent[0].body}") + + # 5. RequestPasskey -> custom user uint32 passkey + rc = RecordingConn() + msg = _make_agent_call("RequestPasskey", phone_path, (), serial=14) + mod.handle_agent_method_call(rc, msg, agent_path, dev_props_cache=cache) + cols = wait_prompt(p_file) + require(cols[1] == "PASSKEY", f"expected PASSKEY prompt, got {cols}") + d_file.write_text(f"{cols[0]}\tACCEPT\t073412\n", encoding="utf-8") + wait_sent(rc, 2) + require(rc.sent[0].header.message_type == MessageType.method_return and + rc.sent[0].body == (73412,), + f"RequestPasskey reply mismatch: {rc.sent[0].body}") + + # 6. DisplayPasskey & Cancel + rc = RecordingConn() + msg = _make_agent_call("DisplayPasskey", phone_path, (193847, 2), serial=15) + mod.handle_agent_method_call(rc, msg, agent_path, dev_props_cache=cache) + cols = wait_prompt(p_file) + require(cols[1] == "DISPLAY" and cols[4] == "193847" and cols[5] == "2", + f"unexpected DISPLAY prompt: {cols}") + c_msg = _make_agent_call("Cancel", phone_path, (), serial=16) + mod.handle_agent_method_call(rc, c_msg, agent_path, dev_props_cache=cache) + require(not p_file.exists(), "Agent1.Cancel must clean up active pair_prompt.tsv") + finally: + ( + mod.OBEX_IPC_DIR, + mod.PAIR_PROMPT_FILE, + mod.PAIR_DECISION_FILE, + ) = orig_vals + if old_no_ui is None: + os.environ.pop("BANANARCHY_OBEX_NO_UI", None) + else: + os.environ["BANANARCHY_OBEX_NO_UI"] = old_no_ui + if injected is not None: + sys.modules.pop("jeepney", None) + print("[ok] KeyboardDisplay Agent1 confirmation, PIN, passkey, and display flows") + + def test_networks_ui_wiring(): src = read(NETWORKS_CPP) for tok in ( "ObexActions", "ObexDirPicker", "ObexIncomingPrompt", + "BtPairingPrompt", "OBEX_PROMPT", + "PAIR_PROMPT", + "PAIR_CANCEL", + "BT_OP_DONE", + "pair_prompt.tsv", + "pair_decision.tsv", + "--async-ui", "bt_obex_dir", "writeObexDecision", "readObexPromptFile", "openObexDirPicker", "tryPresentObexPrompt", + "tryPresentPairPrompt", ): - require(tok in src, f"networks_plugin.cpp missing OBEX UI element {tok}") + require(tok in src, f"networks_plugin.cpp missing OBEX/Pairing UI element {tok}") obex_src = read(BT_OBEX) + require('"KeyboardDisplay"' in obex_src and '"NoInputNoOutput"' not in obex_src, + "bananarchy-bt-obex must register KeyboardDisplay rather than NoInputNoOutput") require("if running and not opp_registered:\n rfcomm_listener = bind_rfcomm_fallback()" in obex_src, "bananarchy-bt-obex must register BlueZ OPP profile before fallback channel 9 bind") - print("[ok] networks_plugin.cpp OBEX confirmation & directory picker UI wiring") + print("[ok] networks_plugin.cpp OBEX & KeyboardDisplay pairing UI wiring") def main(): @@ -268,6 +495,7 @@ def main(): test_class_and_roles() test_seqpacket_and_stream_reader(mod) test_accept_and_reject_sessions(mod) + test_keyboard_display_agent(mod) test_networks_ui_wiring() print("bluetooth obex verification: all checks passed") diff --git a/src/dwm-plugins/networks_plugin.cpp b/src/dwm-plugins/networks_plugin.cpp index c752069..b5fed9d 100644 --- a/src/dwm-plugins/networks_plugin.cpp +++ b/src/dwm-plugins/networks_plugin.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #ifdef None @@ -44,6 +45,7 @@ enum class NetModal { ObexActions = 6, ObexDirPicker = 7, ObexIncomingPrompt = 8, + BtPairingPrompt = 9, }; constexpr const char* kIconHeadphones = "\xef\x80\xa5"; // U+F025 headphones @@ -201,6 +203,9 @@ void writeSavedBtDiscoverable(bool disc) { constexpr const char* kObexIpcDir = "/run/bananarchy/bt-obex"; constexpr const char* kObexPromptPath = "/run/bananarchy/bt-obex/prompt.tsv"; constexpr const char* kObexDecisionPath = "/run/bananarchy/bt-obex/decision.tsv"; +constexpr const char* kPairPromptPath = "/run/bananarchy/bt-obex/pair_prompt.tsv"; +constexpr const char* kPairDecisionPath = "/run/bananarchy/bt-obex/pair_decision.tsv"; +constexpr const char* kBtOpDonePath = "/run/bananarchy/bt-obex/op_done.tsv"; std::string shortenHomePath(const std::string& p) { if (p.empty()) return "~/Downloads"; @@ -307,6 +312,54 @@ void writeObexDecision(const std::string& reqId, bool accept, const std::string& ::rename(tmpPath.c_str(), kObexDecisionPath); } +struct BtPairPromptInfo { + bool active = false; + std::string reqId; + std::string mode; // CONFIRM, PIN, PASSKEY, DISPLAY + std::string devName; + std::string devMac; + std::string code; + int entered = 0; +}; + +BtPairPromptInfo readPairPromptFile() { + BtPairPromptInfo p; + std::ifstream in(kPairPromptPath); + std::string line; + if (!in.is_open() || !std::getline(in, line)) return p; + line = trimStr(line); + if (line.empty()) return p; + std::vector cols; + std::stringstream ss(line); + std::string c; + while (std::getline(ss, c, '\t')) { + cols.push_back(c); + } + if (cols.size() < 4 || cols[0].empty() || cols[1].empty()) return p; + p.active = true; + p.reqId = cols[0]; + p.mode = cols[1]; + p.devName = cols[2]; + p.devMac = cols[3]; + if (cols.size() >= 5) p.code = cols[4]; + if (cols.size() >= 6) p.entered = std::atoi(cols[5].c_str()); + return p; +} + +void writePairDecision(const std::string& reqId, bool accept, const std::string& value) { + if (reqId.empty()) return; + ::mkdir("/run/bananarchy", 0755); + ::mkdir(kObexIpcDir, 0755); + std::string tmpPath = std::string(kPairDecisionPath) + ".tmp"; + { + std::ofstream out(tmpPath, std::ios::trunc); + if (out.is_open()) { + out << reqId << "\t" << (accept ? "ACCEPT" : "REJECT") << "\t" << value << "\n"; + } + } + ::rename(tmpPath.c_str(), kPairDecisionPath); +} + bool isLidClosedState() { std::ifstream in("/run/bananarchy/lid-state"); std::string line; @@ -778,18 +831,14 @@ std::vector queryBtDevices(const std::string& scanRaw = "") { std::string nameLow = toLowerStr(d.name); bool hasA2dp = (infoLow.find("0000110b-") != std::string::npos || - infoLow.find("0000110a-") != std::string::npos || - infoLow.find("audio sink") != std::string::npos || - infoLow.find("audio source") != std::string::npos); + infoLow.find("audio sink") != std::string::npos); bool hasHfp = (infoLow.find("00001108-") != std::string::npos || - infoLow.find("00001112-") != std::string::npos || - infoLow.find("0000111e-") != std::string::npos || - infoLow.find("0000111f-") != std::string::npos || - infoLow.find("handsfree") != std::string::npos || - infoLow.find("headset") != std::string::npos); + infoLow.find("0000111e-") != std::string::npos); bool hasHid = (infoLow.find("00001124-") != std::string::npos || infoLow.find("00001812-") != std::string::npos || infoLow.find("human interface device") != std::string::npos); + bool isPhoneOrPc = (infoLow.find("icon: phone") != std::string::npos || + infoLow.find("icon: computer") != std::string::npos); if (infoLow.find("icon: input-gaming") != std::string::npos || infoLow.find("icon: input-joystick") != std::string::npos || @@ -813,6 +862,9 @@ std::vector queryBtDevices(const std::string& scanRaw = "") { nameLow.find("trackpad") != std::string::npos) { d.kind = BtDevKind::Mouse; d.profileLabel = "HID Mouse"; + } else if (isPhoneOrPc) { + d.kind = BtDevKind::Phone; + d.profileLabel = "OBEX/PAN"; } else if (hasPaSink || hasPaSrc || hasA2dp || hasHfp || infoLow.find("icon: audio-") != std::string::npos) { d.kind = BtDevKind::Audio; @@ -843,10 +895,6 @@ std::vector queryBtDevices(const std::string& scanRaw = "") { } else if (hasHid) { d.kind = BtDevKind::Keyboard; d.profileLabel = "HID Input"; - } else if (infoLow.find("icon: phone") != std::string::npos || - infoLow.find("icon: computer") != std::string::npos) { - d.kind = BtDevKind::Phone; - d.profileLabel = "OBEX/PAN"; } size_t batPos = info.find("Battery Percentage:"); @@ -1024,6 +1072,13 @@ int runNetworksApp(int argc, char** argv) { int obexPickerSel = 0; bool obexPickerForPrompt = false; + // Bluetooth pairing confirmation / PIN / passkey prompt state + BtPairPromptInfo pairPrompt; + int pairPromptSel = 0; + std::string pairInput; + bool openedForPairPrompt = false; + bool pendingDeferredPairPrompt = false; + // Multi-tap state for text inputs TextMode textMode = TextMode::Lower; int lastTapDigit = -1; @@ -1062,8 +1117,8 @@ int runNetworksApp(int argc, char** argv) { std::string scanRaw; if (btOn) { int obexPid = readIntFile("/tmp/bananarchy_bt_obex.pid"); - if (obexPid <= 0 || ::kill(obexPid, 0) != 0) { - runAsyncCmd("/usr/bin/bananarchy-bt-obex start >/dev/null 2>&1"); + if (obexPid <= 0 || (::kill(obexPid, 0) != 0 && errno != EPERM)) { + runAsyncCmd("doas -n /usr/bin/bananarchy-bt-obex start >/dev/null 2>&1"); } btRx = readBtRxStatus(); if (forceScan) { @@ -1182,7 +1237,7 @@ int runNetworksApp(int argc, char** argv) { auto applyOpenArg = [&](const std::string& arg) { std::string a = toLowerStr(trimStr(arg)); modal = NetModal::None; - if (a == "bluetooth" || a == "bt" || a == "obex-prompt") { + if (a == "bluetooth" || a == "bt" || a == "obex-prompt" || a == "pair-prompt") { activeTab = NetTab::Bluetooth; } else if (a == "cell" || a == "cellular" || a == "apn" || a == "hotspot") { activeTab = NetTab::Cellular; @@ -1802,6 +1857,101 @@ int runNetworksApp(int argc, char** argv) { drawPango(layoutSmall, fg, 20, ry, 34, pRows[i], kWinWidth - 40); } drawSoftkeyBar("Accept", "Select", "Reject"); + } else if (modal == NetModal::BtPairingPrompt) { + XSetForeground(dpy, gc, pt.spec.bgOverlay); + XFillRectangle(dpy, pix, gc, 8, 28, kWinWidth - 16, 232); + XSetForeground(dpy, gc, pt.spec.accent); + XDrawRectangle(dpy, pix, gc, 8, 28, kWinWidth - 17, 231); + + std::string devLbl = pairPrompt.devName.empty() ? pairPrompt.devMac : pairPrompt.devName; + if (pairPrompt.mode == "CONFIRM") { + drawPango(layoutMain, &colYellow, 16, 34, 22, "Bluetooth Pairing", kWinWidth - 32); + drawPango(layoutSmall, &colLight, 16, 58, 18, + tailFitPangoText(layoutSmall, devLbl, kWinWidth - 32), kWinWidth - 32); + XSetForeground(dpy, gc, pt.spec.bgInput); + XFillRectangle(dpy, pix, gc, 16, 80, kWinWidth - 32, 42); + XSetForeground(dpy, gc, pt.spec.border); + XDrawRectangle(dpy, pix, gc, 16, 80, kWinWidth - 33, 41); + drawPango(layoutMain, &colWhite, 24, 80, 42, + "Code: " + (pairPrompt.code.empty() ? std::string("------") : pairPrompt.code), + kWinWidth - 48); + drawPango(layoutSmall, &colMuted, 16, 124, 18, + "Confirm passkey matches", kWinWidth - 32); + + const char* pOpts[2] = {"Accept & Pair", "Reject Pairing"}; + for (int i = 0; i < 2; ++i) { + int ry = 148 + i * 44; + bool isSel = (pairPromptSel == i); + XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgButton); + XFillRectangle(dpy, pix, gc, 16, ry, kWinWidth - 32, 36); + XftColor* fg = isSel ? &colWhite : ((i == 0) ? &colGreen : &colOrange); + drawPango(layoutMain, fg, 24, ry, 36, pOpts[i], kWinWidth - 48); + } + drawSoftkeyBar("Pair", "Select", "Reject"); + } else if (pairPrompt.mode == "PIN" || pairPrompt.mode == "PASSKEY") { + bool isPin = (pairPrompt.mode == "PIN"); + drawPango(layoutMain, &colYellow, 16, 34, 22, + isPin ? "Enter BT PIN" : "Enter Passkey", kWinWidth - 80); + if (isPin) { + drawPango(layoutSmall, &colBlue, kWinWidth - 58, 36, 20, + std::string("[") + textModeLabel() + "]"); + } + drawPango(layoutSmall, &colLight, 16, 58, 18, + tailFitPangoText(layoutSmall, devLbl, kWinWidth - 32), kWinWidth - 32); + + XSetForeground(dpy, gc, pt.spec.bgInputFocus); + XFillRectangle(dpy, pix, gc, 16, 86, kWinWidth - 32, 34); + XSetForeground(dpy, gc, pt.spec.accent); + XDrawRectangle(dpy, pix, gc, 16, 86, kWinWidth - 33, 33); + drawPango(layoutMain, &colWhite, 22, 86, 34, + tailFitPangoText(layoutMain, pairInput + "_", kWinWidth - 44), kWinWidth - 44); + + if (isPin) { + if (lastTapDigit >= 0 && lastTapDigit <= 9 && (nowMs() - lastTapMs) <= 850) { + const char* seq = (textMode == TextMode::Sym) + ? kSymTapMap[lastTapDigit] + : kMultiTapMap[lastTapDigit]; + std::string cand = formatMultiTapBar( + std::to_string(lastTapDigit) + ":", seq, lastTapCycle, + textMode == TextMode::Upper, 6, 19); + drawPango(layoutSmall, &colYellow, 16, 130, 18, cand, kWinWidth - 32); + } else { + drawPango(layoutSmall, &colMuted, 16, 130, 18, + "# Input mode (123/abc)", kWinWidth - 32); + } + drawPango(layoutSmall, &colMuted, 16, 152, 18, + "Enter matching PIN on device", kWinWidth - 32); + } else { + drawPango(layoutSmall, &colMuted, 16, 130, 18, + "Type 6-digit passkey shown", kWinWidth - 32); + drawPango(layoutSmall, &colMuted, 16, 152, 18, + "on the other device", kWinWidth - 32); + } + drawPango(layoutSmall, &colMuted, 16, 174, 18, + "[0-9] Digits [BkSp] Delete", kWinWidth - 32); + drawSoftkeyBar("Pair", "Pair", "Reject"); + } else { + drawPango(layoutMain, &colYellow, 16, 34, 22, "Keyboard Pairing", kWinWidth - 32); + drawPango(layoutSmall, &colLight, 16, 58, 18, + tailFitPangoText(layoutSmall, devLbl, kWinWidth - 32), kWinWidth - 32); + XSetForeground(dpy, gc, pt.spec.bgInput); + XFillRectangle(dpy, pix, gc, 16, 86, kWinWidth - 32, 44); + XSetForeground(dpy, gc, pt.spec.accent); + XDrawRectangle(dpy, pix, gc, 16, 86, kWinWidth - 33, 43); + drawPango(layoutMain, &colWhite, 22, 86, 44, + "Code: " + (pairPrompt.code.empty() ? std::string("------") : pairPrompt.code), + kWinWidth - 44); + drawPango(layoutSmall, &colLight, 16, 140, 18, + "Type this code on device", kWinWidth - 32); + drawPango(layoutSmall, &colMuted, 16, 162, 18, + "then press Enter to finish", kWinWidth - 32); + if (pairPrompt.entered > 0) { + drawPango(layoutSmall, &colGreen, 16, 186, 18, + "Entered: " + std::to_string(pairPrompt.entered) + " digit(s)", + kWinWidth - 32); + } + drawSoftkeyBar("OK", "OK", "Close"); + } } if (!statusBanner.empty() && nowMs() < statusBannerUntilMs) { @@ -1850,7 +2000,16 @@ int runNetworksApp(int argc, char** argv) { writeObexDecision(obexPrompt.reqId, false, obexPrompt.targetDir); obexPrompt.active = false; } + if (modal == NetModal::BtPairingPrompt && pairPrompt.active) { + if (pairPrompt.mode == "DISPLAY") { + ::unlink(kPairPromptPath); + } else { + writePairDecision(pairPrompt.reqId, false, ""); + } + pairPrompt.active = false; + } openedForObexPrompt = false; + openedForPairPrompt = false; int xfdLocal = ConnectionNumber(dpy); int64_t drainDeadline = nowMs() + 180; while (nowMs() < drainDeadline && querySoftkeysDown(dpy) != 0) { @@ -1920,6 +2079,67 @@ int runNetworksApp(int argc, char** argv) { render(); }; + auto resolvePairPrompt = [&](bool accept) { + if (pairPrompt.active) { + if (pairPrompt.mode == "DISPLAY") { + ::unlink(kPairPromptPath); + } else { + if (accept && (pairPrompt.mode == "PIN" || pairPrompt.mode == "PASSKEY") && + trimStr(pairInput).empty()) { + setBanner(pairPrompt.mode == "PIN" ? "Enter PIN first" : "Enter passkey first"); + render(); + return; + } + writePairDecision(pairPrompt.reqId, accept, trimStr(pairInput)); + } + pairPrompt.active = false; + } + modal = NetModal::None; + if (openedForPairPrompt) { + openedForPairPrompt = false; + hideWindow(); + } else { + refreshCurrentTab(false); + if (pairPrompt.mode != "DISPLAY") { + setBanner(accept ? "Pairing confirmed..." : "Pairing rejected"); + } + render(); + } + }; + + auto tryPresentPairPrompt = [&](bool forceMarkOpened = false) { + BtPairPromptInfo p = readPairPromptFile(); + if (!p.active) { + pendingDeferredPairPrompt = false; + return; + } + if (isPhonePasscodeLocked() || isPidFileAlive(getRuntimeFile("xlocker.pid")) || + isCallActiveOrRingingFast() || isLidClosedState()) { + pendingDeferredPairPrompt = true; + return; + } + pendingDeferredPairPrompt = false; + bool sameReq = (modal == NetModal::BtPairingPrompt && pairPrompt.reqId == p.reqId); + bool wasVisible = visible; + pairPrompt = p; + if (!sameReq) { + pairPromptSel = 0; + pairInput.clear(); + textMode = TextMode::Num; + lastTapDigit = -1; + } + if (!wasVisible) { + openedForPairPrompt = true; + showWindow("bluetooth"); + } else { + if (forceMarkOpened) openedForPairPrompt = true; + activeTab = NetTab::Bluetooth; + } + wakeDisplayForObex(dpy); + modal = NetModal::BtPairingPrompt; + render(); + }; + auto connectWifiNow = [&](const std::string& ssid, const std::string& pass) { modal = NetModal::None; setBanner("Connecting to " + ssid + "..."); @@ -2061,20 +2281,11 @@ int runNetworksApp(int argc, char** argv) { modal = NetModal::None; int rc = 0; if (act == 0) { - setBanner("Connecting " + targetBt.name + "..."); + setBanner("Connecting " + targetBt.name + "...", 55000); render(); - runCaptureCmd("/usr/bin/bananarchy-bt-obex connect " + - shellQuote(targetBt.mac) + " " + - shellQuote(targetBt.name) + " >/dev/null 2>&1", &rc); - refreshCurrentTab(false); - refreshTargetBtFromList(); - bool isConn = (rc == 0) || targetBt.connected; - if (isConn && targetBt.kind == BtDevKind::Audio) { - std::ofstream ofs("/tmp/sxmo_audio_out_device", std::ios::trunc); - if (ofs) ofs << "Bluetooth\n"; - runAsyncCmd("sxmo_audio.sh device set Bluetooth >/dev/null 2>&1"); - } - setBanner(isConn ? ("Connected: " + targetBt.name) : "Connect failed"); + runAsyncCmd("doas -n /usr/bin/bananarchy-bt-obex --async-ui connect " + + shellQuote(targetBt.mac) + " " + + shellQuote(targetBt.name) + " >/dev/null 2>&1"); } else if (act == 1) { setBanner("Disconnecting " + targetBt.name + "..."); render(); @@ -2087,21 +2298,11 @@ int runNetworksApp(int argc, char** argv) { refreshCurrentTab(false); setBanner("Disconnected " + targetBt.name); } else if (act == 2) { - setBanner("Pairing " + targetBt.name + "..."); + setBanner("Pairing " + targetBt.name + "...", 55000); render(); - runCaptureCmd("/usr/bin/bananarchy-bt-obex pair " + - shellQuote(targetBt.mac) + " " + - shellQuote(targetBt.name) + " >/dev/null 2>&1", &rc); - refreshCurrentTab(false); - refreshTargetBtFromList(); - bool isPairedOrConn = (rc == 0) || targetBt.connected || targetBt.paired; - if (isPairedOrConn && targetBt.kind == BtDevKind::Audio) { - std::ofstream ofs("/tmp/sxmo_audio_out_device", std::ios::trunc); - if (ofs) ofs << "Bluetooth\n"; - runAsyncCmd("sxmo_audio.sh device set Bluetooth >/dev/null 2>&1"); - } - setBanner(isPairedOrConn ? ("Paired & connected: " + targetBt.name) - : ("Pairing failed: " + targetBt.name)); + runAsyncCmd("doas -n /usr/bin/bananarchy-bt-obex --async-ui pair " + + shellQuote(targetBt.mac) + " " + + shellQuote(targetBt.name) + " >/dev/null 2>&1"); } else if (act == 3) { std::string macU = targetBt.mac; for (char& c : macU) { @@ -2219,6 +2420,14 @@ int runNetworksApp(int argc, char** argv) { } return; } + if (modal == NetModal::BtPairingPrompt) { + if (pairPrompt.mode == "CONFIRM") { + resolvePairPrompt(pairPromptSel == 0); + } else { + resolvePairPrompt(true); + } + return; + } if (activeTab == NetTab::Wifi) { if (wifiRowSel == 0) { @@ -2350,6 +2559,10 @@ int runNetworksApp(int argc, char** argv) { resolveObexPrompt(true); return; } + if (modal == NetModal::BtPairingPrompt) { + resolvePairPrompt(true); + return; + } if (modal != NetModal::None) { handleEnterKey(); return; @@ -2382,6 +2595,10 @@ int runNetworksApp(int argc, char** argv) { resolveObexPrompt(false); return; } + if (modal == NetModal::BtPairingPrompt) { + resolvePairPrompt(false); + return; + } if (modal == NetModal::ObexDirPicker) { modal = obexPickerForPrompt ? NetModal::ObexIncomingPrompt : NetModal::ObexActions; return; @@ -2395,8 +2612,11 @@ int runNetworksApp(int argc, char** argv) { if (!isPreload) { showWindow(openArg); - if (toLowerStr(trimStr(openArg)) == "obex-prompt") { + std::string lowerOpen = toLowerStr(trimStr(openArg)); + if (lowerOpen == "obex-prompt") { tryPresentObexPrompt(true); + } else if (lowerOpen == "pair-prompt") { + tryPresentPairPrompt(true); } } @@ -2459,6 +2679,8 @@ int runNetworksApp(int argc, char** argv) { if (sym == XF86XK_HangupPhone || sym == XK_Cancel) { if (modal == NetModal::ObexIncomingPrompt) { resolveObexPrompt(false); + } else if (modal == NetModal::BtPairingPrompt) { + resolvePairPrompt(false); } else { hideWindow(); } @@ -2588,6 +2810,45 @@ int runNetworksApp(int argc, char** argv) { continue; } + if (modal == NetModal::BtPairingPrompt) { + if (pairPrompt.mode == "CONFIRM") { + if (sym == XK_Up || sym == XK_KP_Up || sym == XK_Down || sym == XK_KP_Down) { + pairPromptSel = (pairPromptSel + 1) % 2; + render(); + } else if (sym == XK_Return || sym == XK_KP_Enter) { + handleEnterKey(); + } + } else if (pairPrompt.mode == "PIN" || pairPrompt.mode == "PASSKEY") { + if (sym == XK_Return || sym == XK_KP_Enter) { + resolvePairPrompt(true); + continue; + } + if (pairPrompt.mode == "PASSKEY") { + char kd = mapDialKey(sym, kc, ev.xkey.state); + if (kd >= '0' && kd <= '9' && pairInput.size() < 6) { + pairInput.push_back(kd); + render(); + } else if ((sym == XK_BackSpace || sym == XK_Delete) && !pairInput.empty()) { + pairInput.pop_back(); + render(); + } + } else { + if (pairInput.size() < 16 || sym == XK_BackSpace || sym == XK_Delete || + mapDialKey(sym, kc, ev.xkey.state) == '#') { + if (handleMultiTapKey(pairInput, sym, kc, ev.xkey.state)) { + if (pairInput.size() > 16) pairInput.resize(16); + render(); + } + } + } + } else { + if (sym == XK_Return || sym == XK_KP_Enter) { + resolvePairPrompt(true); + } + } + continue; + } + // Main View Tab & Row Navigation char dch = mapDialKey(sym, kc, ev.xkey.state); if (dch == '#' && activeTab == NetTab::Bluetooth && btOn) { @@ -2687,7 +2948,8 @@ int runNetworksApp(int argc, char** argv) { } if (lastTapDigit != -1 && (modal == NetModal::WifiPassword || modal == NetModal::ApnEditor || - modal == NetModal::BtNameEditor)) { + modal == NetModal::BtNameEditor || + (modal == NetModal::BtPairingPrompt && pairPrompt.mode == "PIN"))) { int64_t tRem = (lastTapMs + 851) - now; if (tRem <= 0) { lastTapDigit = -1; @@ -2721,6 +2983,36 @@ int runNetworksApp(int argc, char** argv) { } } + if (pendingDeferredPairPrompt) { + tryPresentPairPrompt(); + if (pendingDeferredPairPrompt && (timeoutMs < 0 || timeoutMs > 250)) { + timeoutMs = 250; + } + } + if (modal == NetModal::BtPairingPrompt) { + BtPairPromptInfo curP = readPairPromptFile(); + if (!curP.active || curP.reqId != pairPrompt.reqId) { + if (curP.active && curP.reqId != pairPrompt.reqId) { + tryPresentPairPrompt(); + } else { + pairPrompt.active = false; + modal = NetModal::None; + if (openedForPairPrompt) { + openedForPairPrompt = false; + hideWindow(); + } else { + refreshCurrentTab(false); + if (pairPrompt.mode != "DISPLAY") { + setBanner("Pairing ended"); + } + render(); + } + } + } else if (timeoutMs < 0 || timeoutMs > 250) { + timeoutMs = 250; + } + } + struct pollfd pfds[2]; pfds[0].fd = xfd; pfds[0].events = POLLIN; @@ -2743,14 +3035,78 @@ int runNetworksApp(int argc, char** argv) { if (visible) render(); } else if (cmd.rfind("OBEX_PROMPT", 0) == 0) { tryPresentObexPrompt(); + } else if (cmd.rfind("PAIR_PROMPT", 0) == 0) { + tryPresentPairPrompt(); + } else if (cmd == "PAIR_CANCEL") { + pendingDeferredPairPrompt = false; + if (modal == NetModal::BtPairingPrompt) { + pairPrompt.active = false; + modal = NetModal::None; + if (openedForPairPrompt) { + openedForPairPrompt = false; + hideWindow(); + } else { + refreshCurrentTab(false); + setBanner("Pairing cancelled"); + render(); + } + } + } else if (cmd == "BT_OP_DONE") { + int opRc = 1; + std::string opMode = "pair", opMac, opName; + { + std::ifstream in(kBtOpDonePath); + std::string line; + if (in.is_open() && std::getline(in, line)) { + std::vector cols; + std::stringstream ss(line); + std::string c; + while (std::getline(ss, c, '\t')) cols.push_back(c); + if (!cols.empty()) opRc = std::atoi(cols[0].c_str()); + if (cols.size() >= 2) opMode = cols[1]; + if (cols.size() >= 3) opMac = cols[2]; + if (cols.size() >= 4) opName = cols[3]; + } + } + ::unlink(kBtOpDonePath); + if (!opMac.empty()) targetBt.mac = opMac; + if (!opName.empty()) targetBt.name = opName; + refreshCurrentTab(false); + refreshTargetBtFromList(); + if (opMode == "pair") { + bool ok = (opRc == 0) || targetBt.connected || targetBt.paired; + if (ok && targetBt.kind == BtDevKind::Audio) { + std::ofstream ofs("/tmp/sxmo_audio_out_device", std::ios::trunc); + if (ofs) ofs << "Bluetooth\n"; + runAsyncCmd("sxmo_audio.sh device set Bluetooth >/dev/null 2>&1"); + } + if (modal != NetModal::BtPairingPrompt) { + setBanner(ok ? ("Paired: " + targetBt.name) + : ("Pairing failed: " + targetBt.name)); + } + } else { + bool ok = (opRc == 0) || targetBt.connected; + if (ok && targetBt.kind == BtDevKind::Audio) { + std::ofstream ofs("/tmp/sxmo_audio_out_device", std::ios::trunc); + if (ofs) ofs << "Bluetooth\n"; + runAsyncCmd("sxmo_audio.sh device set Bluetooth >/dev/null 2>&1"); + } + if (modal != NetModal::BtPairingPrompt) { + setBanner(ok ? ("Connected: " + targetBt.name) : "Connect failed"); + } + } + if (visible) render(); } else if (cmd == "TOGGLE") { if (visible) hideWindow(); else showWindow(); } else if (cmd.rfind("OPEN", 0) == 0) { std::string arg = (cmd.size() > 5) ? trimStr(cmd.substr(5)) : ""; showWindow(arg); - if (toLowerStr(arg) == "obex-prompt") { + std::string lowArg = toLowerStr(arg); + if (lowArg == "obex-prompt") { tryPresentObexPrompt(true); + } else if (lowArg == "pair-prompt") { + tryPresentPairPrompt(true); } } }