Files
bananarchy/scripts/test-bluetooth-obex.py
T

276 lines
10 KiB
Python
Raw Normal View History

#!/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)
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),
"sxmo_bluetoothtoggle.sh missing btmgmt class 2 3")
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")
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 test_networks_ui_wiring():
src = read(NETWORKS_CPP)
for tok in (
"ObexActions",
"ObexDirPicker",
"ObexIncomingPrompt",
"OBEX_PROMPT",
"bt_obex_dir",
"writeObexDecision",
"readObexPromptFile",
"openObexDirPicker",
"tryPresentObexPrompt",
):
require(tok in src, f"networks_plugin.cpp missing OBEX UI element {tok}")
obex_src = read(BT_OBEX)
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")
def main():
mod = load_obex_module()
test_class_and_roles()
test_seqpacket_and_stream_reader(mod)
test_accept_and_reject_sessions(mod)
test_networks_ui_wiring()
print("bluetooth obex verification: all checks passed")
if __name__ == "__main__":
main()