#!/usr/bin/env python3 """Host tests for Bluetooth OBEX OPP recognition, L2CAP SEQPACKET & confirmation UI. Covers: - Smartphone Class of Device (0x5a020c in main.conf, btmgmt class 2 3 in LE/toggle helpers) and absence of a2dp_source role in 50-bluetooth.conf so Android phones recognize Bananarchy as a phone capable of OPP transfers. - ObexPacketReader over both AF_UNIX SOCK_SEQPACKET (simulating L2CAP GOEP 2.0) and SOCK_STREAM (RFCOMM GOEP 1.1) without packet truncation. - End-to-end handle_obex_rx_session() over SOCK_SEQPACKET verifying user ACCEPT into a custom target directory and user REJECT returning 0xC3 without writing. - Reliable RegisterProfile before RFCOMM channel 9 fallback and NeoUI dialog wiring in networks_plugin.cpp. """ import os import pathlib import socket import struct import sys import tempfile import threading import time import types sys.dont_write_bytecode = True BASE = pathlib.Path(__file__).resolve().parent.parent MAIN_CONF = BASE / "overlay/rootfs/etc/bluetooth/main.conf" LE_HELPER = BASE / "overlay/rootfs/usr/bin/bananarchy-bt-le-enable.sh" BT_TOGGLE = BASE / "overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh" BT_OBEX = BASE / "overlay/rootfs/usr/bin/bananarchy-bt-obex" NETWORKS_CPP = BASE / "src/dwm-plugins/networks_plugin.cpp" WP_CONF = BASE / "overlay/rootfs/etc/wireplumber/wireplumber.conf.d/50-bluetooth.conf" def require(cond, msg): if not cond: raise SystemExit("FAIL: " + msg) def read(path): return path.read_text(encoding="utf-8") def load_obex_module(): src = read(BT_OBEX) mod = types.ModuleType("bananarchy_bt_obex") mod.__file__ = str(BT_OBEX) exec(compile(src, str(BT_OBEX), "exec"), mod.__dict__) return mod 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("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, MGMT SSP/bondable flags, and OPP role gate") def build_obex_put_headers(filename, total_len): name_utf16 = filename.encode("utf-16-be") + b"\x00\x00" name_hdr = struct.pack(">BH", 0x01, 3 + len(name_utf16)) + name_utf16 len_hdr = struct.pack(">BI", 0xC3, total_len) return name_hdr + len_hdr def build_obex_body(chunk, is_final): hi = 0x49 if is_final else 0x48 return struct.pack(">BH", hi, 3 + len(chunk)) + chunk def recv_raw_pkt(sock): dat = sock.recv(4096) require(len(dat) >= 3, "short OBEX response packet") return dat[0], dat[3:] def test_seqpacket_and_stream_reader(mod): # 1. SOCK_SEQPACKET (Android L2CAP GOEP 2.0): full PDU arrived in one recv() a, b = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET) try: payload = build_obex_put_headers("android_photo_test.jpg", 12345) + build_obex_body(b"ABCD1234", False) pkt = struct.pack(">BH", 0x02, 3 + len(payload)) + payload a.sendall(pkt) reader = mod.ObexPacketReader(b) op, got = mod.recv_obex_packet(reader) require(op == 0x02 and got == payload, f"SOCK_SEQPACKET packet truncated or corrupted (got {len(got or b'')} vs {len(payload)})") finally: a.close() b.close() # 2. SOCK_STREAM (RFCOMM): split headers across fragments a, b = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM) try: payload = build_obex_put_headers("rfcomm_test.txt", 5) + build_obex_body(b"hello", True) pkt = struct.pack(">BH", 0x82, 3 + len(payload)) + payload a.sendall(pkt[:2]) a.sendall(pkt[2:9]) a.sendall(pkt[9:]) reader = mod.ObexPacketReader(b) op, got = mod.recv_obex_packet(reader) require(op == 0x82 and got == payload, "SOCK_STREAM reassembly failed") finally: a.close() b.close() print("[ok] ObexPacketReader framing over SOCK_SEQPACKET and SOCK_STREAM") def test_accept_and_reject_sessions(mod): old_no_ui = os.environ.get("BANANARCHY_OBEX_NO_UI") os.environ["BANANARCHY_OBEX_NO_UI"] = "1" orig_vals = ( mod.OBEX_CFG_FILE, mod.OBEX_IPC_DIR, mod.OBEX_PROMPT_FILE, mod.OBEX_DECISION_FILE, mod.RX_STATUS_FILE, mod.TX_STATUS_FILE, ) try: with tempfile.TemporaryDirectory(prefix="bananarchy-obex-test-") as tmp: root = pathlib.Path(tmp) ipc_dir = root / "ipc" default_dir = root / "downloads" custom_dir = root / "sdcard_custom" default_dir.mkdir() custom_dir.mkdir() cfg_file = root / "bt_obex_dir" cfg_file.write_text(str(default_dir) + "\n", encoding="utf-8") mod.OBEX_CFG_FILE = str(cfg_file) mod.OBEX_IPC_DIR = str(ipc_dir) mod.OBEX_PROMPT_FILE = str(ipc_dir / "prompt.tsv") mod.OBEX_DECISION_FILE = str(ipc_dir / "decision.tsv") mod.RX_STATUS_FILE = str(root / "rx.status") mod.TX_STATUS_FILE = str(root / "tx.status") # --- Case A: Accept and save to custom folder over SOCK_SEQPACKET --- cli, srv = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET) t = threading.Thread( target=mod.handle_obex_rx_session, args=(srv, "Pixel Test", "AA:BB:CC:DD:EE:11"), daemon=True, ) t.start() try: cli.sendall(struct.pack(">BHBBH", 0x80, 7, 0x10, 0x00, 0x8000)) op, _ = recv_raw_pkt(cli) require(op == 0xA0, f"expected CONNECT OK (0xA0), got {hex(op)}") hdrs = build_obex_put_headers("greeting.txt", 12) + build_obex_body(b"hello ", False) cli.sendall(struct.pack(">BH", 0x02, 3 + len(hdrs)) + hdrs) prompt_path = pathlib.Path(mod.OBEX_PROMPT_FILE) deadline = time.monotonic() + 3.0 while not prompt_path.exists() and time.monotonic() < deadline: time.sleep(0.02) require(prompt_path.exists(), "OBEX prompt file was never created") fields = prompt_path.read_text(encoding="utf-8").strip().split("\t") require(len(fields) == 6 and fields[1] == "Pixel Test" and fields[3] == "greeting.txt", f"unexpected prompt TSV: {fields}") req_id = fields[0] pathlib.Path(mod.OBEX_DECISION_FILE).write_text( f"{req_id}\tACCEPT\t{custom_dir}\n", encoding="utf-8" ) op, _ = recv_raw_pkt(cli) require(op == 0x90, f"expected Continue (0x90) after ACCEPT, got {hex(op)}") tail = build_obex_body(b"world!", True) cli.sendall(struct.pack(">BH", 0x82, 3 + len(tail)) + tail) op, _ = recv_raw_pkt(cli) require(op == 0xA0, f"expected OK (0xA0) after PUT-Final, got {hex(op)}") cli.sendall(struct.pack(">BH", 0x81, 3)) op, _ = recv_raw_pkt(cli) require(op == 0xA0, "expected DISCONNECT OK (0xA0)") finally: cli.close() t.join(timeout=3.0) saved_file = custom_dir / "greeting.txt" require(saved_file.is_file() and saved_file.read_bytes() == b"hello world!", "accepted file missing or corrupted in custom target folder") require(not pathlib.Path(mod.OBEX_PROMPT_FILE).exists(), "stale OBEX prompt file was not removed") # --- Case B: Reject inline PUT-Final over SOCK_SEQPACKET --- cli, srv = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET) t = threading.Thread( target=mod.handle_obex_rx_session, args=(srv, "Unknown Phone", "AA:BB:CC:DD:EE:22"), daemon=True, ) t.start() try: cli.sendall(struct.pack(">BHBBH", 0x80, 7, 0x10, 0x00, 0x8000)) op, _ = recv_raw_pkt(cli) require(op == 0xA0, "expected CONNECT OK") one_shot = build_obex_put_headers("rejected.bin", 4) + build_obex_body(b"NOPE", True) cli.sendall(struct.pack(">BH", 0x82, 3 + len(one_shot)) + one_shot) prompt_path = pathlib.Path(mod.OBEX_PROMPT_FILE) deadline = time.monotonic() + 3.0 while not prompt_path.exists() and time.monotonic() < deadline: time.sleep(0.02) require(prompt_path.exists(), "OBEX prompt file not created for reject case") req_id = prompt_path.read_text(encoding="utf-8").strip().split("\t")[0] pathlib.Path(mod.OBEX_DECISION_FILE).write_text( f"{req_id}\tREJECT\t{custom_dir}\n", encoding="utf-8" ) op, _ = recv_raw_pkt(cli) require(op == 0xC3, f"expected Forbidden (0xC3) on REJECT, got {hex(op)}") finally: cli.close() t.join(timeout=3.0) require(not (custom_dir / "rejected.bin").exists() and not (default_dir / "rejected.bin").exists(), "rejected file must never be written to disk") finally: ( mod.OBEX_CFG_FILE, mod.OBEX_IPC_DIR, mod.OBEX_PROMPT_FILE, mod.OBEX_DECISION_FILE, mod.RX_STATUS_FILE, mod.TX_STATUS_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 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", "bt_state.tsv", "dump-state", "parseBtStateTsv", ): 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 & KeyboardDisplay pairing UI wiring") def test_managed_objects_state_cache(mod): require("RSSI" in mod.EPHEMERAL_DEV_PROPS and "ManufacturerData" in mod.EPHEMERAL_DEV_PROPS, "EPHEMERAL_DEV_PROPS must suppress RSSI/advertising cache rewrites") objs = { "/org/bluez/hci0": { "org.bluez.Adapter1": { "Powered": ("b", True), "Discoverable": ("b", False), "Alias": ("s", "Bananarchy"), }, }, "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF": { "org.bluez.Device1": { "Address": ("s", "AA:BB:CC:DD:EE:FF"), "Alias": ("s", "Audio Headset"), "Paired": ("b", True), "Connected": ("b", True), "Icon": ("s", "audio-headset"), "Class": ("u", 0x240404), "UUIDs": ("as", [ "0000110B-0000-1000-8000-00805F9B34FB", "0000111e-0000-1000-8000-00805f9b34fb", ]), }, "org.bluez.Battery1": { "Percentage": ("y", 85), }, }, "/org/bluez/hci0/dev_11_22_33_44_55_66": { "org.bluez.Device1": { "Address": ("s", "11:22:33:44:55:66"), "Name": ("s", "Pixel Phone"), "Paired": ("b", True), "Connected": ("b", False), "Icon": ("s", "phone"), "Class": ("u", 0x5a020c), "UUIDs": ("as", ["00001105-0000-1000-8000-00805f9b34fb"]), }, }, } lines = mod.format_managed_objects_tsv(objs).splitlines() expected = [ "CTRL\t1\t0\tBananarchy", "DEV\t11:22:33:44:55:66\tPixel Phone\t1\t0\tphone\t0x5a020c\t-1\t00001105-0000-1000-8000-00805f9b34fb", "DEV\tAA:BB:CC:DD:EE:FF\tAudio Headset\t1\t1\taudio-headset\t0x240404\t85\t0000110b-0000-1000-8000-00805f9b34fb;0000111e-0000-1000-8000-00805f9b34fb", ] require(lines == expected, f"unexpected format_managed_objects_tsv output: {lines!r}") print("[ok] BlueZ ObjectManager bt_state.tsv snapshot formatter & ephemeral property filter") def main(): mod = load_obex_module() test_class_and_roles() test_seqpacket_and_stream_reader(mod) test_accept_and_reject_sessions(mod) test_keyboard_display_agent(mod) test_managed_objects_state_cache(mod) test_networks_ui_wiring() print("bluetooth obex verification: all checks passed") if __name__ == "__main__": main()