#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only # Bananarchy Bluetooth OBEX Object Push (OPP) Server & Client import os import sys import time import fcntl import select import struct import socket import signal import subprocess import threading OPP_UUID = "00001105-0000-1000-8000-00805f9b34fb" RX_STATUS_FILE = "/tmp/bananarchy_bt_rx.status" TX_STATUS_FILE = "/tmp/bananarchy_bt_tx.status" PID_FILE = "/tmp/bananarchy_bt_obex.pid" DURESS_FLAG = "/tmp/bananarchy_duress_mode" 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" OBEX_PROMPT_LOCK = threading.Lock() def is_duress_mode(): return os.path.exists(DURESS_FLAG) def shorten_obex_dir(path): if not path: return "~/Downloads" if path == "/home/user": return "~" if path.startswith("/home/user/"): return "~/" + path[len("/home/user/"):] return path def sanitize_obex_target_dir(raw_dir): duress_base = "/tmp/duress_home" default_dir = os.path.join(duress_base, "Downloads") if is_duress_mode() else "/home/user/Downloads" cand = str(raw_dir or "").strip() if not cand or "\n" in cand or "\r" in cand or "\t" in cand: cand = default_dir if not cand.startswith("/"): cand = default_dir norm = os.path.normpath(cand) if is_duress_mode(): if norm != duress_base and not norm.startswith(duress_base + "/"): norm = default_dir os.makedirs(norm, exist_ok=True) if norm.startswith("/home/user") or norm.startswith(duress_base): try: os.chown(norm, 10000, 10000) except OSError: pass return norm def get_configured_obex_dir(): raw = "" if not is_duress_mode() and os.path.exists(OBEX_CFG_FILE): try: with open(OBEX_CFG_FILE, "r", encoding="utf-8") as cf: raw = cf.readline().strip() except OSError: raw = "" return sanitize_obex_target_dir(raw) def get_downloads_dir(): return get_configured_obex_dir() def ensure_obex_ipc_dir(): os.makedirs(OBEX_IPC_DIR, mode=0o755, exist_ok=True) try: os.chmod(OBEX_IPC_DIR, 0o755) os.chown(OBEX_IPC_DIR, 10000, 10000) except OSError: pass def write_status(path, text): 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) except OSError: pass def notify_networks_ui(msg="REFRESH_BT\n"): fifo = "/tmp/dwm_plugin_networks.fifo" if os.path.exists(fifo): try: fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK) os.write(fd, msg.encode("utf-8")) os.close(fd) return True except OSError: pass return False def notify_user(title, body): try: bus_addr = "unix:path=/run/user/10000/bus" if os.path.exists("/run/user/10000/dbus.bus"): try: with open("/run/user/10000/dbus.bus", "r", encoding="utf-8") as bf: line = bf.readline().strip() if line: bus_addr = line except OSError: pass if os.geteuid() == 0: subprocess.Popen([ "su", "-", "user", "-c", f"DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS={subprocess.list2cmdline([bus_addr])} notify-send {subprocess.list2cmdline([title, body])}" ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) else: env = os.environ.copy() env.setdefault("DISPLAY", ":0") env.setdefault("DBUS_SESSION_BUS_ADDRESS", bus_addr) subprocess.Popen(["notify-send", title, body], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except Exception: pass def format_size(num_bytes): if num_bytes >= 1024 * 1024: return f"{num_bytes / (1024.0 * 1024.0):.1f} MB" if num_bytes >= 1024: return f"{num_bytes / 1024.0:.1f} KB" return f"{num_bytes} B" def safe_filename(raw_name): name = os.path.basename(raw_name.replace("\\", "/")).strip() clean = "".join(c if (c.isalnum() or c in "._- ()[]") else "_" for c in name) if not clean or clean in (".", ".."): clean = f"bt_file_{int(time.time())}.bin" return clean def unique_dest_path(directory, filename): cand = os.path.join(directory, filename) if not os.path.exists(cand): return cand stem, ext = os.path.splitext(filename) idx = 1 while True: cand = os.path.join(directory, f"{stem}_{idx}{ext}") if not os.path.exists(cand): return cand idx += 1 class ObexPacketReader: """Read OBEX PDUs safely over both RFCOMM SOCK_STREAM and L2CAP SOCK_SEQPACKET.""" def __init__(self, sock): self.sock = sock self.buf = bytearray() seq_val = getattr(socket, "SOCK_SEQPACKET", 5) stype = getattr(sock, "type", socket.SOCK_STREAM) try: stype = sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE) except Exception: pass self.is_seqpacket = (stype == seq_val) def _recv_exact_stream(self, n): while len(self.buf) < n: chunk = self.sock.recv(max(4096, n - len(self.buf))) if not chunk: return None self.buf.extend(chunk) out = bytes(self.buf[:n]) del self.buf[:n] return out def recv_packet(self): if self.is_seqpacket and not self.buf: dat = self.sock.recv(65536) if not dat or len(dat) < 3: return None, None opcode = dat[0] pkt_len = struct.unpack(">H", dat[1:3])[0] if pkt_len < 3: return opcode, b"" if pkt_len <= len(dat): return opcode, bytes(dat[3:pkt_len]) self.buf.extend(dat) hdr = self._recv_exact_stream(3) if not hdr: return None, None payload = self._recv_exact_stream(pkt_len - 3) if payload is None: return None, None return opcode, payload hdr = self._recv_exact_stream(3) if not hdr: return None, None opcode = hdr[0] pkt_len = struct.unpack(">H", hdr[1:3])[0] if pkt_len < 3: return opcode, b"" payload = self._recv_exact_stream(pkt_len - 3) if payload is None: return None, None return opcode, payload def recv_obex_packet(sock_or_reader): if isinstance(sock_or_reader, ObexPacketReader): return sock_or_reader.recv_packet() return ObexPacketReader(sock_or_reader).recv_packet() def _sock_peer_aborted(sock): try: rlist, _, _ = select.select([sock], [], [], 0.0) if sock in rlist: peek = sock.recv(1, socket.MSG_PEEK) if not peek or peek[0] in (0xFF, 0x7F): return True except BlockingIOError: return False except OSError: return True return False def request_user_obex_confirmation(sock, sender_name, sender_mac, file_name, total_len, default_dir, timeout_sec=55.0): with OBEX_PROMPT_LOCK: ensure_obex_ipc_dir() for p in (OBEX_PROMPT_FILE, OBEX_DECISION_FILE): try: if os.path.exists(p): os.unlink(p) except OSError: pass req_id = f"{os.getpid()}_{int(time.monotonic() * 1000)}" s_label = str(sender_name or sender_mac or "Bluetooth Device").replace("\t", " ").replace("\n", " ").strip() s_mac = str(sender_mac or "").replace("\t", " ").replace("\n", " ").strip() f_label = str(file_name or "file.bin").replace("\t", " ").replace("\n", " ").strip() d_label = sanitize_obex_target_dir(default_dir).replace("\t", " ").replace("\n", " ").strip() tmp_prompt = OBEX_PROMPT_FILE + ".tmp" with open(tmp_prompt, "w", encoding="utf-8") as pf: pf.write(f"{req_id}\t{s_label}\t{s_mac}\t{f_label}\t{int(total_len or 0)}\t{d_label}\n") try: os.chmod(tmp_prompt, 0o644) os.chown(tmp_prompt, 10000, 10000) except OSError: pass os.replace(tmp_prompt, OBEX_PROMPT_FILE) 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") deadline = time.monotonic() + timeout_sec try: while time.monotonic() < deadline: if os.path.exists(OBEX_DECISION_FILE): try: with open(OBEX_DECISION_FILE, "r", encoding="utf-8", errors="replace") as df: line = df.readline().strip() parts = line.split("\t") if len(parts) >= 2 and parts[0] == req_id: accepted = (parts[1].strip().upper() == "ACCEPT") chosen = parts[2].strip() if len(parts) >= 3 and parts[2].strip() else d_label return accepted, sanitize_obex_target_dir(chosen), False except OSError: pass if sock is not None and _sock_peer_aborted(sock): return False, sanitize_obex_target_dir(d_label), True time.sleep(0.1) return False, sanitize_obex_target_dir(d_label), False finally: for p in (OBEX_PROMPT_FILE, OBEX_DECISION_FILE): try: if os.path.exists(p): os.unlink(p) except OSError: pass notify_networks_ui() def handle_obex_rx_session(sock, sender_name="Bluetooth Device", sender_mac=""): sock.settimeout(65.0) reader = ObexPacketReader(sock) out_file = None out_path = None file_name = "" total_len = 0 rx_bytes = 0 last_ui_notify = 0.0 awaiting_decision = True target_dir = get_configured_obex_dir() def reset_rx_file_state(): nonlocal out_file, out_path, file_name, total_len, rx_bytes, awaiting_decision, target_dir if out_file: try: out_file.close() except Exception: pass out_file = None out_path = None file_name = "" total_len = 0 rx_bytes = 0 awaiting_decision = True target_dir = get_configured_obex_dir() try: while True: opcode, payload = recv_obex_packet(reader) if opcode is None: break op_base = opcode & 0x7F is_final = (opcode & 0x80) != 0 if opcode == 0x80: # CONNECT # OBEX CONNECT response: 0xA0 (OK), len 7, ver 0x10, flags 0, max_pkt 0x8000 resp = struct.pack(">BHBBH", 0xA0, 7, 0x10, 0x00, 0x8000) sock.sendall(resp) elif opcode == 0x81: # DISCONNECT sock.sendall(struct.pack(">BH", 0xA0, 3)) break elif opcode in (0xFF, 0x7F): # ABORT stale_path = out_path reset_rx_file_state() if stale_path and os.path.exists(stale_path): try: os.unlink(stale_path) except OSError: pass write_status(RX_STATUS_FILE, f"IDLE\tReady ({shorten_obex_dir(get_configured_obex_dir())})") notify_networks_ui() sock.sendall(struct.pack(">BH", 0xA0, 3)) break elif op_base == 0x02: # PUT / PUT-Final pos = 0 plen = len(payload) body_chunks = [] while pos < plen: hi = payload[pos] pos += 1 h_encoding = hi & 0xC0 if h_encoding in (0x00, 0x40): # 2-byte length prefixed if pos + 2 > plen: break hlen = struct.unpack(">H", payload[pos:pos + 2])[0] if hlen < 3 or pos + hlen - 1 > plen: break hdata = payload[pos + 2:pos + hlen - 1] pos += hlen - 1 if hi == 0x01: # Name (UTF-16BE) try: decoded = hdata.decode("utf-16-be", errors="replace").rstrip("\x00") except Exception: decoded = "received_file" file_name = safe_filename(decoded) elif hi in (0x48, 0x49): # Body / End-of-Body body_chunks.append(hdata) elif h_encoding == 0x80: # 1-byte value pos += 1 elif h_encoding == 0xC0: # 4-byte value if pos + 4 > plen: break val = struct.unpack(">I", payload[pos:pos + 4])[0] pos += 4 if hi == 0xC3: # Length total_len = val if awaiting_decision and is_final and not body_chunks and not file_name and total_len == 0: sock.sendall(struct.pack(">BH", 0xC3, 3)) # Disallow empty Delete PUT reset_rx_file_state() continue if awaiting_decision: if not file_name: file_name = f"bt_rx_{int(time.time())}.bin" accepted, chosen_dir, remote_aborted = request_user_obex_confirmation( sock, sender_name, sender_mac, file_name, total_len, get_configured_obex_dir() ) if remote_aborted: write_status(RX_STATUS_FILE, f"IDLE\tReady ({shorten_obex_dir(get_configured_obex_dir())})") notify_networks_ui() reset_rx_file_state() continue if not accepted: write_status( RX_STATUS_FILE, f"IDLE\tRejected {file_name} ({shorten_obex_dir(get_configured_obex_dir())})" ) notify_networks_ui() sock.sendall(struct.pack(">BH", 0xC3, 3)) # Forbidden (Rejected) reset_rx_file_state() continue awaiting_decision = False target_dir = chosen_dir sock.settimeout(30.0) if out_file is None: if not file_name: file_name = f"bt_rx_{int(time.time())}.bin" out_path = unique_dest_path(target_dir, file_name) out_file = open(out_path, "wb") try: os.chown(out_path, 10000, 10000) except OSError: pass for chunk in body_chunks: if out_file: out_file.write(chunk) rx_bytes += len(chunk) now = time.time() if not is_final: if now - last_ui_notify >= 0.4 or rx_bytes == 0: pct = int((rx_bytes * 100) // total_len) if total_len > 0 else 0 write_status( RX_STATUS_FILE, f"RECEIVING\t{file_name or '...'}\t{rx_bytes}\t{total_len}\t{pct}%" ) notify_networks_ui() last_ui_notify = now sock.sendall(struct.pack(">BH", 0x90, 3)) # Continue else: saved_base = os.path.basename(out_path) saved_full = out_path saved_dir_short = shorten_obex_dir(target_dir) out_file.flush() out_file.close() out_file = None try: os.chown(saved_full, 10000, 10000) os.chmod(saved_full, 0o644) except OSError: pass sz_str = format_size(rx_bytes) write_status( RX_STATUS_FILE, f"RECEIVED\t{saved_base}\t{sz_str}\t{saved_full}" ) notify_networks_ui() notify_user("Bluetooth File Received", f"{saved_base} ({sz_str}) saved to {saved_dir_short}") sock.sendall(struct.pack(">BH", 0xA0, 3)) # Success reset_rx_file_state() elif op_base == 0x05: # SETPATH sock.sendall(struct.pack(">BH", 0xA0, 3)) else: sock.sendall(struct.pack(">BH", 0xD1, 3)) # Not Implemented except Exception: stale_path = out_path reset_rx_file_state() if stale_path and os.path.exists(stale_path): try: os.unlink(stale_path) except OSError: pass finally: if out_file: try: out_file.close() except Exception: pass try: sock.close() except Exception: pass def open_input_inotify_fd(): try: import ctypes libc = ctypes.CDLL(None, use_errno=True) libc.inotify_init.argtypes = [] libc.inotify_init.restype = ctypes.c_int libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32] libc.inotify_add_watch.restype = ctypes.c_int fd = libc.inotify_init() if fd < 0: return -1 os.set_inheritable(fd, False) os.set_blocking(fd, False) # IN_ATTRIB (0x04) | IN_MOVED_TO (0x80) | IN_CREATE (0x100) | IN_DELETE (0x200) if libc.inotify_add_watch(fd, b"/dev/input", 0x00000384) < 0: os.close(fd) return -1 return fd except Exception: return -1 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_hog_device_props(props): if not isinstance(props, dict): return False uuids = [str(v).lower() for v in (props.get("UUIDs") or [])] return any(u.startswith("00001812-") for u in uuids) def is_classic_audio_props(props): if not isinstance(props, dict) or is_hog_device_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): return True icon = str(props.get("Icon") or "").strip().lower() if icon.startswith("audio-"): return True cod = props.get("Class") if isinstance(cod, int) and (cod & 0x1F00) == 0x0400: return True return False def avrcp_fifo_command_for_key(code): mapping = { 164: "PLAYPAUSE", # KEY_PLAYPAUSE 200: "PLAY", # KEY_PLAYCD 207: "PLAY", # KEY_PLAY 201: "PAUSE", # KEY_PAUSECD 119: "PAUSE", # KEY_PAUSE 166: "STOP", # KEY_STOPCD 128: "STOP", # KEY_STOP 163: "NEXT", # KEY_NEXTSONG 165: "PREV", # KEY_PREVIOUSSONG } return mapping.get(code) def dispatch_avrcp_key(code): cmd = avrcp_fifo_command_for_key(code) if not cmd: return False if cmd != "PAUSE" and ( os.path.exists("/tmp/sxmo_in_call") or os.path.exists("/tmp/sxmo_call_ringing") ): return False fifo = "/tmp/dwm_plugin_music.fifo" if os.path.exists(fifo): try: fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK) os.write(fd, (cmd + "\n").encode("ascii")) os.close(fd) return True except OSError: pass if cmd == "PAUSE": try: env = os.environ.copy() env.setdefault("XDG_RUNTIME_DIR", "/run/user/10000") subprocess.Popen(["sxmo_playerctl.sh", "pause_all"], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except Exception: pass return True def run_gamepad_uinput_bridge(is_running, wake_r=-1): ev_fmt = "llHHi" ev_size = struct.calcsize(ev_fmt) ui_set_evbit = 0x40045564 ui_set_keybit = 0x40045565 ui_dev_create = 0x5501 ui_dev_destroy = 0x5502 eviocgbit_key = (2 << 30) | (96 << 16) | (0x45 << 8) | (0x20 + 0x01) # Map Linux gamepad button codes to Bananarchy keypad/navigation keys: # South(A)=Enter(OK), East(B)=8(GB B), West(X)=5(Fire/Turbo B), North(Y)=6(Turbo A) # Start=2(GB Start), Select=3(GB Select), L1=F1(LSK), R1=F2(RSK), L2=*, R2=0, Mode=Esc btn_map = { 0x130: 28, # BTN_SOUTH (A) -> KEY_ENTER 0x131: 9, # BTN_EAST (B) -> KEY_8 0x132: 8, # BTN_C -> KEY_7 0x133: 6, # BTN_WEST (X) -> KEY_5 0x134: 7, # BTN_NORTH (Y) -> KEY_6 0x135: 10, # BTN_Z -> KEY_9 0x136: 59, # BTN_TL (L1) -> KEY_F1 (Left Softkey) 0x137: 60, # BTN_TR (R1) -> KEY_F2 (Right Softkey) 0x138: 55, # BTN_TL2 (L2) -> KEY_KPASTERISK (*) 0x139: 11, # BTN_TR2 (R2) -> KEY_0 0x13a: 4, # BTN_SELECT -> KEY_3 0x13b: 3, # BTN_START -> KEY_2 0x13c: 1, # BTN_MODE -> KEY_ESC 0x120: 28, # BTN_TRIGGER -> KEY_ENTER 0x121: 9, # BTN_THUMB -> KEY_8 0x220: 103, # BTN_DPAD_UP -> KEY_UP 0x221: 108, # BTN_DPAD_DOWN -> KEY_DOWN 0x222: 105, # BTN_DPAD_LEFT -> KEY_LEFT 0x223: 106, # BTN_DPAD_RIGHT -> KEY_RIGHT } all_keys = sorted(set(btn_map.values()) | {103, 108, 105, 106}) uinput_fd = None gamepads = {} # path -> {"fd": int, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {}} avrcp_devs = {} # path -> fd last_scan = 0.0 last_input_mtime = 0 inotify_fd = open_input_inotify_fd() need_scan = True def ensure_uinput(): nonlocal uinput_fd if uinput_fd is not None: return True try: subprocess.run(["modprobe", "-q", "uinput"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) fd = os.open("/dev/uinput", os.O_WRONLY | os.O_NONBLOCK) fcntl.ioctl(fd, ui_set_evbit, 0x00) # EV_SYN fcntl.ioctl(fd, ui_set_evbit, 0x01) # EV_KEY for k in all_keys: fcntl.ioctl(fd, ui_set_keybit, k) name = b"Bananarchy BT Gamepad Bridge" udev = struct.pack("80sHHHHi", name, 0x06, 0x1209, 0x8110, 1, 0) + (b"\x00" * (64 * 4 * 4)) os.write(fd, udev) fcntl.ioctl(fd, ui_dev_create) uinput_fd = fd return True except Exception: return False def emit_key(code, val): if uinput_fd is None and not ensure_uinput(): return try: os.write(uinput_fd, struct.pack(ev_fmt, 0, 0, 0x01, code, val)) os.write(uinput_fd, struct.pack(ev_fmt, 0, 0, 0x00, 0, 0)) except OSError: pass def get_axis_dir(fd, axis, val, cache): if axis not in cache: try: ioc = (2 << 30) | (24 << 16) | (0x45 << 8) | (0x40 + axis) buf = fcntl.ioctl(fd, ioc, b"\x00" * 24) _v, min_v, max_v, _fz, _fl, _rs = struct.unpack("6i", buf) if max_v > min_v: cache[axis] = (min_v, max_v) else: cache[axis] = (-32768, 32767) except Exception: cache[axis] = (-32768, 32767) min_v, max_v = cache[axis] mid = (min_v + max_v) / 2.0 span = (max_v - min_v) / 2.0 if span <= 0: return 0 norm = (val - mid) / span if norm < -0.40: return -1 if norm > 0.40: return 1 return 0 while is_running(): now = time.monotonic() if need_scan or (inotify_fd < 0 and now - last_scan >= 2.0): need_scan = False last_scan = now try: st_in = os.stat("/dev/input") if last_input_mtime != 0 and st_in.st_mtime_ns != last_input_mtime: subprocess.Popen( ["sh", "-c", "DISPLAY=:0 xsetroot -name \"$(cat /tmp/sxmo_status_bar 2>/dev/null || printf 'Bananarchy')\" >/dev/null 2>&1 || sxmo_hook_statusbar.sh >/dev/null 2>&1"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) last_input_mtime = st_in.st_mtime_ns except OSError: pass try: for entry in os.listdir("/dev/input"): if not entry.startswith("event"): continue dev_path = f"/dev/input/{entry}" if dev_path in gamepads or dev_path in avrcp_devs: continue sys_name_path = f"/sys/class/input/{entry}/device/name" dname = "" try: with open(sys_name_path, "r", encoding="utf-8") as nf: dname = nf.read().strip() if "Bananarchy BT Gamepad Bridge" in dname: continue except OSError: pass try: fd = os.open(dev_path, os.O_RDONLY | os.O_NONBLOCK) buf = bytearray(96) fcntl.ioctl(fd, eviocgbit_key, buf, True) has_gamepad = bool((buf[0x130 // 8] >> (0x130 % 8)) & 1) or bool((buf[0x120 // 8] >> (0x120 % 8)) & 1) has_qwerty = bool((buf[16 // 8] >> (16 % 8)) & 1) and bool((buf[30 // 8] >> (30 % 8)) & 1) has_avrcp_keys = any( bool((buf[k // 8] >> (k % 8)) & 1) for k in (163, 164, 165, 166, 200, 201) ) dlow = dname.lower() is_avrcp_dev = ("(avrcp)" in dlow) or ( has_avrcp_keys and not has_qwerty and not has_gamepad and not any(w in dlow for w in ("gpio", "pm8941", "keypad", "pwrkey")) ) if has_gamepad and not has_qwerty: ensure_uinput() gamepads[dev_path] = { "fd": fd, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {} } elif is_avrcp_dev: avrcp_devs[dev_path] = fd else: os.close(fd) except Exception: pass except OSError: pass fd_map = {info["fd"]: (path, info) for path, info in list(gamepads.items())} avrcp_map = {fd: path for path, fd in list(avrcp_devs.items())} wait_fds = list(fd_map.keys()) + list(avrcp_map.keys()) if inotify_fd >= 0: wait_fds.append(inotify_fd) if wake_r >= 0: wait_fds.append(wake_r) if not wait_fds: time.sleep(1.5) continue sel_timeout = None if (inotify_fd >= 0 and wake_r >= 0) else 2.0 try: rlist, _, _ = select.select(wait_fds, [], [], sel_timeout) except Exception: if is_running(): time.sleep(0.5) continue if not is_running(): break if inotify_fd >= 0 and inotify_fd in rlist: while True: try: if not os.read(inotify_fd, 512): break except BlockingIOError: break except OSError: break need_scan = True for rfd in rlist: if rfd in avrcp_map: apath = avrcp_map[rfd] try: data = os.read(rfd, ev_size * 16) if not data: raise OSError("EOF") except OSError: try: os.close(rfd) except OSError: pass avrcp_devs.pop(apath, None) continue offset = 0 while offset + ev_size <= len(data): _sec, _usec, ev_type, ev_code, ev_val = struct.unpack_from(ev_fmt, data, offset) offset += ev_size if ev_type == 0x01 and ev_val == 1: dispatch_avrcp_key(ev_code) continue path, info = fd_map.get(rfd, (None, None)) if not path: continue try: data = os.read(rfd, ev_size * 16) if not data: raise OSError("EOF") except OSError: try: os.close(rfd) except OSError: pass gamepads.pop(path, None) continue offset = 0 while offset + ev_size <= len(data): _sec, _usec, ev_type, ev_code, ev_val = struct.unpack_from(ev_fmt, data, offset) offset += ev_size if ev_type == 0x01 and ev_code in btn_map: if ev_val in (0, 1, 2): emit_key(btn_map[ev_code], ev_val) elif ev_type == 0x03: if ev_code == 0x10: # ABS_HAT0X new_dir = -1 if ev_val < 0 else (1 if ev_val > 0 else 0) old_dir = info["hat_x"] if new_dir != old_dir: if old_dir == -1: emit_key(105, 0) elif old_dir == 1: emit_key(106, 0) if new_dir == -1: emit_key(105, 1) elif new_dir == 1: emit_key(106, 1) info["hat_x"] = new_dir elif ev_code == 0x11: # ABS_HAT0Y new_dir = -1 if ev_val < 0 else (1 if ev_val > 0 else 0) old_dir = info["hat_y"] if new_dir != old_dir: if old_dir == -1: emit_key(103, 0) elif old_dir == 1: emit_key(108, 0) if new_dir == -1: emit_key(103, 1) elif new_dir == 1: emit_key(108, 1) info["hat_y"] = new_dir elif ev_code == 0x00: # ABS_X (Left Stick X) new_dir = get_axis_dir(rfd, 0x00, ev_val, info["ax"]) old_dir = info["lx"] if new_dir != old_dir: if old_dir == -1: emit_key(105, 0) elif old_dir == 1: emit_key(106, 0) if new_dir == -1: emit_key(105, 1) elif new_dir == 1: emit_key(106, 1) info["lx"] = new_dir elif ev_code == 0x01: # ABS_Y (Left Stick Y) new_dir = get_axis_dir(rfd, 0x01, ev_val, info["ax"]) old_dir = info["ly"] if new_dir != old_dir: if old_dir == -1: emit_key(103, 0) elif old_dir == 1: emit_key(108, 0) if new_dir == -1: emit_key(103, 1) elif new_dir == 1: emit_key(108, 1) info["ly"] = new_dir if inotify_fd >= 0: try: os.close(inotify_fd) except OSError: pass for info in gamepads.values(): try: os.close(info["fd"]) except OSError: pass for afd in avrcp_devs.values(): try: os.close(afd) except OSError: pass if uinput_fd is not None: try: fcntl.ioctl(uinput_fd, ui_dev_destroy) except Exception: pass try: os.close(uinput_fd) except OSError: pass def trust_device_path(conn, dev_path): if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"): return try: 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)))) except Exception: pass def set_hog_preferred_bearer(conn, dev_path, props=None): """Force the LE bearer for HID-over-GATT devices before Pair/Connect.""" if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"): return uuids = [] if isinstance(props, dict): uuids = [str(v).lower() for v in (props.get("UUIDs") or [])] if not any(u.startswith("00001812-") for u in uuids): return try: 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")))) except Exception: pass def set_audio_preferred_bearer(conn, dev_path, props=None): """Force BR/EDR bearer for Classic A2DP/HFP audio headsets before Pair/Connect.""" if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"): return if not is_classic_audio_props(props): return try: 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")))) except Exception: pass def handle_agent_method_call(conn, msg, agent_path): from jeepney import new_method_return, MessageType if msg is None or msg.header.message_type != MessageType.method_call: return False path = msg.header.fields.get(1) member = msg.header.fields.get(3) 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,))) trust_device_path(conn, dev_path) notify_networks_ui() return True if member in ("DisplayPinCode", "DisplayPasskey"): conn.send(new_method_return(msg)) trust_device_path(conn, dev_path) notify_networks_ui() return True if member in ("Cancel", "Release"): conn.send(new_method_return(msg)) return True conn.send(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) deadline = time.time() + timeout while time.time() < deadline: rem = max(0.05, deadline - time.time()) try: msg = conn.receive(timeout=rem) except TimeoutError: return None if msg is None: continue if handle_agent_method_call(conn, msg, agent_path): continue if msg.header.message_type in (MessageType.method_return, MessageType.error): if msg.header.fields.get(HeaderFields.reply_serial, -1) == serial: return msg return None def register_bluez_services(conn, profile_path, agent_path): from jeepney import DBusAddress, MessageType, new_method_call 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))), agent_path, timeout=2.0 ) dbus_call_with_agent( conn, new_method_call(aprop, "Set", "ssv", ("org.bluez.Adapter1", "Pairable", ("b", True))), agent_path, timeout=2.0 ) except Exception: pass try: am = DBusAddress("/org/bluez", bus_name="org.bluez", interface="org.bluez.AgentManager1") dbus_call_with_agent( conn, new_method_call(am, "RegisterAgent", "os", (agent_path, "NoInputNoOutput")), agent_path, timeout=3.0 ) dbus_call_with_agent( conn, new_method_call(am, "RequestDefaultAgent", "o", (agent_path,)), agent_path, timeout=3.0 ) except Exception: pass try: pm = DBusAddress("/org/bluez", bus_name="org.bluez", interface="org.bluez.ProfileManager1") opts_v = { "Name": ("s", "OBEX Object Push"), "Role": ("s", "server"), "Channel": ("q", 9), "Version": ("q", 0x0102), "RequireAuthentication": ("b", False), "RequireAuthorization": ("b", False), } opts_basic = { "Name": ("s", "OBEX Object Push"), "Role": ("s", "server"), "Channel": ("q", 9), "RequireAuthentication": ("b", False), "RequireAuthorization": ("b", False), } for opts in (opts_v, opts_basic): rep = dbus_call_with_agent( conn, new_method_call(pm, "RegisterProfile", "osa{sv}", (profile_path, OPP_UUID, opts)), agent_path, timeout=3.0 ) if rep is None: continue if rep.header.message_type == MessageType.method_return: return True err_str = " ".join(str(x) for x in (rep.body or ())).lower() if "already" in err_str: return True except Exception: pass return False def lookup_bt_device_label(conn, dev_path, agent_path): mac = "" if isinstance(dev_path, str) and "dev_" in dev_path: mac = dev_path.split("dev_")[-1].replace("_", ":").upper() if conn is not None and isinstance(dev_path, str) and dev_path.startswith("/org/bluez/"): try: from jeepney import DBusAddress, MessageType, new_method_call prop_addr = DBusAddress(dev_path, bus_name="org.bluez", interface="org.freedesktop.DBus.Properties") rep = dbus_call_with_agent( conn, new_method_call(prop_addr, "GetAll", "s", ("org.bluez.Device1",)), agent_path, timeout=0.8 ) if rep is not None and rep.header.message_type == MessageType.method_return and rep.body: raw = rep.body[0] if isinstance(raw, dict): for key in ("Alias", "Name"): val = raw.get(key) if isinstance(val, (tuple, list)) and len(val) == 2: val = val[1] if isinstance(val, str) and val.strip(): return val.strip(), mac except Exception: pass return (mac or "Bluetooth Device"), mac 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") write_status(RX_STATUS_FILE, f"IDLE\tReady ({shorten_obex_dir(get_configured_obex_dir())})") notify_networks_ui() running = True wake_r, wake_w = os.pipe() os.set_inheritable(wake_r, False) os.set_inheritable(wake_w, False) os.set_blocking(wake_r, False) os.set_blocking(wake_w, False) def stop_handler(_signum, _frame): nonlocal running running = False try: os.write(wake_w, b"\x01") except OSError: pass 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: s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) s.bind(("00:00:00:00:00:00", 9)) s.listen(2) s.setblocking(False) return s except OSError: if s: try: s.close() except OSError: pass return None profile_path = "/org/bananarchy/obex_opp" agent_path = "/org/bananarchy/bt_agent" conn = None opp_registered = False rfcomm_listener = None 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_bus, "AddMatch", "s", ("type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.bluez'",) )) conn.send(new_method_call( dbus_bus, "AddMatch", "s", ("type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Device1'",) )) 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) except Exception: pass if running and not opp_registered: rfcomm_listener = bind_rfcomm_fallback() while running: try: if conn is not None: while running: try: msg = conn.receive(timeout=0.0) except TimeoutError: msg = None except (EOFError, OSError): try: conn.close() except Exception: pass conn = None break if msg is None: break if handle_agent_method_call(conn, msg, agent_path): pass elif msg.header.message_type == MessageType.method_call: member = msg.header.fields.get(3) # Member name path = msg.header.fields.get(1) # Object path if path == profile_path and member == "NewConnection": # Args: (o device, h fd, a{sv} fd_properties) dev_path, fd_obj, _props = msg.body reply = new_method_return(msg) conn.send(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) 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) 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: if rfcomm_listener is not None: try: rfcomm_listener.close() except OSError: pass rfcomm_listener = None opp_registered = register_bluez_services(conn, profile_path, agent_path) if not opp_registered: rfcomm_listener = bind_rfcomm_fallback() elif member == "PropertiesChanged" and msg.body and len(msg.body) >= 2: iface, changed = msg.body[0], msg.body[1] if iface == "org.bluez.Device1" and isinstance(changed, dict): if any(k in changed for k in ("Connected", "Paired", "Bonded")): notify_networks_ui() if rfcomm_listener is not None: while running: try: 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) t = threading.Thread(target=handle_obex_rx_session, args=(csock, s_name, s_mac or rmac), daemon=True) t.start() except BlockingIOError: break if not running: break wait_fds = [wake_r] if conn is not None and getattr(conn, "sock", None) is not None: wait_fds.append(conn.sock) if rfcomm_listener is not None: wait_fds.append(rfcomm_listener) select.select(wait_fds, [], [], None if len(wait_fds) > 1 else 5.0) except Exception: if running: time.sleep(0.5) if rfcomm_listener is not None: try: rfcomm_listener.close() except OSError: pass for fd in (wake_r, wake_w): try: os.close(fd) except OSError: pass try: if os.path.exists(PID_FILE): os.unlink(PID_FILE) except OSError: pass def connect_opp_socket(mac): from jeepney import DBusAddress, new_method_call, new_method_return, MessageType from jeepney.io.blocking import open_dbus_connection mac = mac.strip().upper() dev_path = "/org/bluez/hci0/dev_" + mac.replace(":", "_") client_profile_path = f"/org/bananarchy/obex_client_{os.getpid()}" # Method 1: Use BlueZ ProfileManager1 client profile + Device1.ConnectProfile try: conn = open_dbus_connection(bus="SYSTEM", enable_fds=True) pm = DBusAddress("/org/bluez", bus_name="org.bluez", interface="org.bluez.ProfileManager1") opts = { "Name": ("s", "OBEX Object Push Client"), "Role": ("s", "client"), } conn.send_and_get_reply( new_method_call(pm, "RegisterProfile", "osa{sv}", (client_profile_path, OPP_UUID, opts)), timeout=4.0 ) dev_addr = DBusAddress(dev_path, bus_name="org.bluez", interface="org.bluez.Device1") conn.send(new_method_call(dev_addr, "ConnectProfile", "s", (OPP_UUID,))) deadline = time.time() + 10.0 while time.time() < deadline: rem = max(0.1, deadline - time.time()) try: msg = conn.receive(timeout=rem) except TimeoutError: break if msg.header.message_type == MessageType.method_call: if msg.header.fields.get(1) == client_profile_path and \ msg.header.fields.get(3) == "NewConnection": _dpath, fd_obj, _props = msg.body conn.send(new_method_return(msg)) raw_fd = os.dup(fd_obj.fileno()) fd_obj.close() return socket.socket(fileno=raw_fd), conn, client_profile_path elif msg.header.message_type == MessageType.error: break try: conn.send_and_get_reply( new_method_call(pm, "UnregisterProfile", "o", (client_profile_path,)), timeout=2.0 ) conn.close() except Exception: pass except Exception: pass # Method 2: Direct RFCOMM channel scan for common OPP channels for ch in (12, 9, 4, 10, 5, 6, 1, 2, 3, 7, 8, 11): s = None try: s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) s.settimeout(2.5) s.connect((mac, ch)) return s, None, None except OSError: if s: try: s.close() except Exception: pass return None, None, None def send_file_obex(mac, filepath): if not os.path.isfile(filepath): write_status(TX_STATUS_FILE, "ERROR\tFile not found") return 1 filename = os.path.basename(filepath) filesize = os.path.getsize(filepath) write_status(TX_STATUS_FILE, f"CONNECTING\t{filename}\t{mac}") sock, dbus_conn, prof_path = connect_opp_socket(mac) if sock is None: write_status(TX_STATUS_FILE, f"ERROR\tCould not connect to {mac}") notify_user("Bluetooth Send Failed", f"Could not connect to {mac}") return 1 try: sock.settimeout(20.0) reader = ObexPacketReader(sock) # 1. OBEX CONNECT conn_pkt = struct.pack(">BHBBH", 0x80, 7, 0x10, 0x00, 0x8000) sock.sendall(conn_pkt) resp_op, resp_body = recv_obex_packet(reader) if resp_op != 0xA0 or resp_body is None or len(resp_body) < 4: write_status(TX_STATUS_FILE, "ERROR\tOBEX Connect rejected") notify_user("Bluetooth Send Failed", "Remote rejected OBEX connection") return 1 remote_max_pkt = struct.unpack(">H", resp_body[2:4])[0] max_pkt = min(max(255, remote_max_pkt), 8192) # 2. Build Name header (0x01) + Length header (0xC3) 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, filesize) first_headers = name_hdr + len_hdr sent_bytes = 0 with open(filepath, "rb") as f: first = True while True: hdr_prefix = first_headers if first else b"" first = False max_chunk = max_pkt - 3 - len(hdr_prefix) - 3 if max_chunk < 64: max_chunk = 64 chunk = f.read(max_chunk) eof = (len(chunk) == 0) or (sent_bytes + len(chunk) >= filesize) body_hi = 0x49 if eof else 0x48 body_hdr = struct.pack(">BH", body_hi, 3 + len(chunk)) + chunk pkt_payload = hdr_prefix + body_hdr pkt_op = 0x82 if eof else 0x02 pkt = struct.pack(">BH", pkt_op, 3 + len(pkt_payload)) + pkt_payload sock.sendall(pkt) sent_bytes += len(chunk) pct = int((sent_bytes * 100) // filesize) if filesize > 0 else 100 write_status(TX_STATUS_FILE, f"SENDING\t{filename}\t{pct}%") r_op, _r_body = recv_obex_packet(reader) if eof: if r_op == 0xA0: write_status(TX_STATUS_FILE, f"SENT\t{filename}\t{format_size(filesize)}") notify_user("Bluetooth File Sent", f"Sent {filename} ({format_size(filesize)})") break else: write_status(TX_STATUS_FILE, f"ERROR\tTransfer rejected (0x{r_op or 0:02X})") notify_user("Bluetooth Send Failed", f"Transfer rejected by {mac}") return 1 else: if r_op != 0x90: write_status(TX_STATUS_FILE, f"ERROR\tTransfer aborted (0x{r_op or 0:02X})") notify_user("Bluetooth Send Failed", f"Transfer interrupted ({pct}%)") return 1 # 3. OBEX DISCONNECT try: sock.sendall(struct.pack(">BH", 0x81, 3)) recv_obex_packet(reader) except Exception: pass return 0 except Exception as e: write_status(TX_STATUS_FILE, f"ERROR\t{e}") notify_user("Bluetooth Send Failed", str(e)) return 1 finally: try: sock.close() except Exception: pass if dbus_conn and prof_path: try: from jeepney import DBusAddress, new_method_call pm = DBusAddress("/org/bluez", bus_name="org.bluez", interface="org.bluez.ProfileManager1") dbus_conn.send_and_get_reply( new_method_call(pm, "UnregisterProfile", "o", (prof_path,)), timeout=2.0 ) dbus_conn.close() except Exception: pass def ensure_daemon_running(): if os.path.exists(PID_FILE): try: with open(PID_FILE, "r", encoding="utf-8") as f: pid = int(f.read().strip()) os.kill(pid, 0) return 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 def prepare_bt_controller(): """Power the adapter and enable LE before DBus Pair/Connect calls.""" try: subprocess.run(["timeout", "3", "bluetoothctl", "power", "on"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=4) except Exception: pass helper = "/usr/bin/bananarchy-bt-le-enable.sh" try: if os.geteuid() == 0: subprocess.run([helper], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=4) else: subprocess.run(["doas", "-n", helper], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=4) except Exception: pass def clear_stale_linkkey(mac): mac = mac.strip().upper() if not mac: return False if os.geteuid() != 0: res = subprocess.run( ["doas", "-n", "/usr/bin/bananarchy-bt-obex", "clear-linkkey", mac], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) return res.returncode == 0 bt_root = "/var/lib/bluetooth" changed = False if os.path.isdir(bt_root): for adapter in os.listdir(bt_root): info_path = os.path.join(bt_root, adapter, mac, "info") if not os.path.isfile(info_path): continue try: with open(info_path, "r", encoding="utf-8", errors="replace") as f: lines = f.readlines() out_lines = [] skip_sec = False for ln in lines: s = ln.strip() if s.startswith("[") and s.endswith("]"): skip_sec = s.lower() in ("[linkkey]", "[longtermkey]", "[peripherallongtermkey]", "[slaveLongtermkey]") if not skip_sec: out_lines.append(ln) if len(out_lines) != len(lines): with open(info_path, "w", encoding="utf-8") as f: f.writelines(out_lines) changed = True except Exception: pass if changed: subprocess.run(["rc-service", "bluetooth", "restart"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(0.8) subprocess.run(["bluetoothctl", "power", "on"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(0.4) return changed def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): from jeepney import DBusAddress, new_method_call, MessageType from jeepney.io.blocking import open_dbus_connection ensure_daemon_running() prepare_bt_controller() mac = mac.strip().upper() if not mac: return 1 dev_path = "/org/bluez/hci0/dev_" + mac.replace(":", "_") orig_path = dev_path cli_agent_path = f"/org/bananarchy/bt_cli_agent_{os.getpid()}" adapter_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez", interface="org.bluez.Adapter1") am_addr = DBusAddress("/org/bluez", bus_name="org.bluez", interface="org.bluez.AgentManager1") om_addr = DBusAddress("/", bus_name="org.bluez", interface="org.freedesktop.DBus.ObjectManager") conn = None nonlocal_conn = [None] try: conn = open_dbus_connection(bus="SYSTEM") nonlocal_conn[0] = conn aprop_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez", interface="org.freedesktop.DBus.Properties") dbus_call_with_agent( conn, new_method_call(aprop_addr, "Set", "ssv", ("org.bluez.Adapter1", "Pairable", ("b", True))), cli_agent_path, timeout=2.0 ) dbus_call_with_agent( conn, new_method_call(am_addr, "RegisterAgent", "os", (cli_agent_path, "NoInputNoOutput")), 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 ) def pump_agent(duration): end_t = time.time() + duration while time.time() < end_t: rem = max(0.05, min(0.25, end_t - time.time())) try: m = nonlocal_conn[0].receive(timeout=rem) if m is not None: handle_agent_method_call(nonlocal_conn[0], m, cli_agent_path) except TimeoutError: pass def get_dev_props(dpath): prop_addr = DBusAddress(dpath, bus_name="org.bluez", interface="org.freedesktop.DBus.Properties") rep = dbus_call_with_agent( nonlocal_conn[0], new_method_call(prop_addr, "GetAll", "s", ("org.bluez.Device1",)), cli_agent_path, timeout=2.5 ) if rep is None or rep.header.message_type != MessageType.method_return or not rep.body: return None raw = rep.body[0] if not isinstance(raw, dict): return None out = {} for k, v in raw.items(): out[k] = v[1] if (isinstance(v, (tuple, list)) and len(v) == 2) else v return out def find_matching_device(target_name, prefer_path=None): if not target_name: return None t_low = target_name.strip().lower() rep = dbus_call_with_agent( nonlocal_conn[0], new_method_call(om_addr, "GetManagedObjects"), cli_agent_path, timeout=3.0 ) if rep is None or rep.header.message_type != MessageType.method_return or not rep.body: return None objs = rep.body[0] if not isinstance(objs, dict): return None candidates = [] for opath, ifaces in objs.items(): if not isinstance(opath, str) or not opath.startswith("/org/bluez/hci0/dev_"): continue dprops_raw = ifaces.get("org.bluez.Device1") if isinstance(ifaces, dict) else None if not isinstance(dprops_raw, dict): continue dprops = { k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v) for k, v in dprops_raw.items() } nm = str(dprops.get("Name") or dprops.get("Alias") or "").strip().lower() exact = (nm == t_low) le_alias = (nm == f"{t_low} le" or f"{nm} le" == t_low) if exact or le_alias: score = 0 if exact else -25 addr_type = str(dprops.get("AddressType") or "").strip().lower() if dprops.get("Connected"): score += 100 if is_classic_audio_props(dprops): score += 60 if addr_type == "public": score += 40 elif addr_type == "random" and not is_hog_device_props(dprops): score -= 40 if "RSSI" in dprops and dprops.get("RSSI") is not None: score += 50 if opath == prefer_path: score += 10 candidates.append((score, opath)) if not candidates: return None candidates.sort(key=lambda x: x[0], reverse=True) return candidates[0][1] def has_media_transport(dpath): rep = dbus_call_with_agent( nonlocal_conn[0], new_method_call(om_addr, "GetManagedObjects"), cli_agent_path, timeout=2.5 ) if rep is None or rep.header.message_type != MessageType.method_return or not rep.body: return False objs = rep.body[0] if not isinstance(objs, dict): return False prefix = dpath + "/" for opath, ifaces in objs.items(): if isinstance(opath, str) and opath.startswith(prefix) and isinstance(ifaces, dict): if "org.bluez.MediaTransport1" in ifaces: return True return False def connect_classic_audio_profiles(dpath, props): if not is_classic_audio_props(props): return set_audio_preferred_bearer(nonlocal_conn[0], dpath, props) uuids = [str(v).lower() for v in (props.get("UUIDs") or [])] dev_addr = DBusAddress(dpath, bus_name="org.bluez", interface="org.bluez.Device1") profiles = [] if any(u.startswith("0000110b-") for u in uuids): profiles.append("0000110b-0000-1000-8000-00805f9b34fb") if any(u.startswith("0000111e-") for u in uuids): profiles.append("0000111e-0000-1000-8000-00805f9b34fb") if any(u.startswith("00001108-") for u in uuids): profiles.append("00001108-0000-1000-8000-00805f9b34fb") if not profiles: profiles = [ "0000110b-0000-1000-8000-00805f9b34fb", "0000111e-0000-1000-8000-00805f9b34fb", ] for prof_uuid in profiles: dbus_call_with_agent( nonlocal_conn[0], new_method_call(dev_addr, "ConnectProfile", "s", (prof_uuid,)), cli_agent_path, timeout=6.0 ) def wait_for_bond_if_connected(dpath, max_wait=3.5): deadline = time.time() + max_wait while time.time() < deadline: pump_agent(0.25) p = get_dev_props(dpath) if not p or not p.get("Connected"): break if p.get("Paired") or p.get("Bonded"): return p return get_dev_props(dpath) def cancel_pending_connect(dpath): dev_addr = DBusAddress(dpath, bus_name="org.bluez", interface="org.bluez.Device1") dbus_call_with_agent( nonlocal_conn[0], new_method_call(dev_addr, "Disconnect"), cli_agent_path, timeout=2.0 ) def attempt_connect_path(dpath, want_pair): p = get_dev_props(dpath) set_hog_preferred_bearer(nonlocal_conn[0], dpath, p) set_audio_preferred_bearer(nonlocal_conn[0], dpath, p) trust_device_path(nonlocal_conn[0], dpath) if p is None: return False if p.get("Connected"): if is_classic_audio_props(p) and not has_media_transport(dpath): connect_classic_audio_profiles(dpath, p) pump_agent(0.4) p = get_dev_props(dpath) or p p = wait_for_bond_if_connected(dpath, 3.5) or p if p.get("Connected") and (not want_pair or p.get("Paired") or p.get("Bonded")): return True dev_addr = DBusAddress(dpath, bus_name="org.bluez", 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 ) 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: dev_mac = dpath.split("dev_")[-1].replace("_", ":") if clear_stale_linkkey(dev_mac): try: nonlocal_conn[0].close() except Exception: pass conn_new = open_dbus_connection(bus="SYSTEM") nonlocal_conn[0] = conn_new dbus_call_with_agent( conn_new, new_method_call(aprop_addr, "Set", "ssv", ("org.bluez.Adapter1", "Pairable", ("b", True))), 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 ) trust_device_path(conn_new, dpath) set_hog_preferred_bearer(conn_new, dpath, p) set_audio_preferred_bearer(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 ) p = get_dev_props(dpath) or {} if is_classic_audio_props(p) and (not p.get("Connected") or not has_media_transport(dpath)): connect_classic_audio_profiles(dpath, p) pump_agent(0.4) p = get_dev_props(dpath) or p if p.get("Connected") and not (p.get("Paired") or p.get("Bonded")): p = wait_for_bond_if_connected(dpath, 4.0) or p if p.get("Connected"): return True if want_pair and (p.get("Paired") or p.get("Bonded")): return True return False def is_tentative_ble_non_hog(dprops): if not isinstance(dprops, dict): return False addr_type = str(dprops.get("AddressType") or "").strip().lower() return ( addr_type == "random" and not is_hog_device_props(dprops) and not is_classic_audio_props(dprops) and not dprops.get("Paired") and not dprops.get("Bonded") ) def scan_for_device(prefer_path, max_scan=15.0): dbus_call_with_agent( nonlocal_conn[0], new_method_call(adapter_addr, "StartDiscovery"), cli_agent_path, timeout=2.5 ) scan_start = time.time() scan_deadline = scan_start + max_scan discovered_path = prefer_path while time.time() < scan_deadline: pump_agent(0.35) elapsed = time.time() - scan_start p = get_dev_props(prefer_path) if p and p.get("Connected"): discovered_path = prefer_path break if dev_name: alt = find_matching_device(dev_name, prefer_path=prefer_path) if alt: ap = get_dev_props(alt) if ap and (ap.get("Connected") or ap.get("RSSI") is not None): discovered_path = alt trust_device_path(nonlocal_conn[0], discovered_path) min_wait = 3.5 if is_tentative_ble_non_hog(ap) else 0.8 if ap.get("Connected") or elapsed >= min_wait: break if p and p.get("RSSI") is not None: min_wait = 3.5 if is_tentative_ble_non_hog(p) else 0.8 if elapsed >= min_wait: discovered_path = prefer_path break dbus_call_with_agent( nonlocal_conn[0], new_method_call(adapter_addr, "StopDiscovery"), cli_agent_path, timeout=2.0 ) pump_agent(0.15) return discovered_path props = get_dev_props(dev_path) orig_unbonded = (props is None) or (not props.get("Paired") and not props.get("Bonded")) if not do_pair and orig_unbonded and (props is not None or dev_name): do_pair = True if props and not dev_name: dev_name = str(props.get("Name") or props.get("Alias") or "").strip() if props is None and dev_name: alt = find_matching_device(dev_name) if alt: dev_path = alt props = get_dev_props(dev_path) trust_device_path(nonlocal_conn[0], dev_path) # Try connecting directly first when BlueZ already knows the device (avoids # blocking 15s in StartDiscovery for paired BR/EDR headsets in Page Scan). if props is None: dev_path = scan_for_device(dev_path, max_scan=8.0) ok = attempt_connect_path(dev_path, do_pair) if not ok: discovered_path = scan_for_device(dev_path, max_scan=8.0) ok = attempt_connect_path(discovered_path, do_pair) if ok and discovered_path != orig_path and orig_unbonded: dbus_call_with_agent( nonlocal_conn[0], new_method_call(adapter_addr, "RemoveDevice", "o", (orig_path,)), cli_agent_path, timeout=2.0 ) notify_networks_ui() return 0 if ok else 1 except Exception: return 1 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 try: c_final.close() except Exception: pass def stop_daemon(): pids = set() 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 def main(): cmd = sys.argv[1] if len(sys.argv) > 1 else "status" if cmd == "daemon": run_daemon() elif cmd == "start": ensure_daemon_running() return 0 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) 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) elif cmd == "clear-linkkey": if len(sys.argv) < 3: return 1 return 0 if clear_stale_linkkey(sys.argv[2]) else 1 elif cmd == "send": if len(sys.argv) < 4: print("Usage: bananarchy-bt-obex send ", file=sys.stderr) return 1 return send_file_obex(sys.argv[2], sys.argv[3]) elif cmd == "status": if os.path.exists(RX_STATUS_FILE): with open(RX_STATUS_FILE, "r", encoding="utf-8") as f: print(f.read().strip()) else: print("IDLE\tReady (~/Downloads)") return 0 return 0 if __name__ == "__main__": sys.exit(main())