#!/usr/bin/env python3 """Host selftest for the compiled C DSDS and session daemons.""" import os import subprocess import tempfile import unittest BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SRC_DIR = os.path.join(BASE_DIR, "src", "bananarchy-daemons") def encode_gsm7_with_fill(text, udh=b""): septets = [] ext_map = { "\f": 0x0A, "^": 0x14, "{": 0x28, "}": 0x29, "\\": 0x2F, "[": 0x3C, "~": 0x3D, "]": 0x3E, "|": 0x40, "\u20ac": 0x65, } basic = ( "@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n\u00d8\u00f8\r\u00c5\u00e5" "\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\x1b\u00c6\u00e6\u00df\u00c9" " !\"#\u00a4%&'()*+,-./0123456789:;<=>?" "\u00a1ABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c4\u00d6\u00d1\u00dc\u00a7" "\u00bfabcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0" ) for ch in text: if ch in ext_map: septets.append(0x1B) septets.append(ext_map[ch]) else: septets.append(basic.index(ch)) fill_bits = (7 - ((len(udh) * 8) % 7)) % 7 if udh else 0 start_septet = ((len(udh) * 8) + fill_bits) // 7 udl = start_septet + len(septets) packed_len = (udl * 7 + 7) // 8 buf = bytearray(max(len(udh), packed_len)) buf[:len(udh)] = udh for idx, val in enumerate(septets): sidx = start_septet + idx bit_off = sidx * 7 bidx = bit_off // 8 sh = bit_off % 8 buf[bidx] |= (val << sh) & 0xFF if sh > 1: buf[bidx + 1] |= (val >> (8 - sh)) & 0xFF return udl, bytes(buf) def build_deliver_pdu(oa_digits, oa_ton_npi, oa_bytes, dcs, udl, ud, udh=False, smsc=b"\x00"): fo = 0x40 if udh else 0x00 scts = bytes([0x62, 0x11, 0x31, 0x61, 0x03, 0x00, 0x08]) tpdu = bytearray([fo, oa_digits, oa_ton_npi]) + oa_bytes + bytes([0x00, dcs]) + scts + bytes([udl]) + ud return (smsc + bytes(tpdu)).hex() class DsdsDaemonTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.tmpdir = tempfile.TemporaryDirectory() cls.bin = os.path.join(cls.tmpdir.name, "dsds_selftest") subprocess.run( [ "gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", "-DBANANARCHY_DSDS_SELFTEST", "-I", SRC_DIR, "-o", cls.bin, os.path.join(SRC_DIR, "bananarchy-dsds.c"), ], check=True, ) @classmethod def tearDownClass(cls): cls.tmpdir.cleanup() def test_all_c_daemons_host_compile_cleanly(self): for name in [ "bananarchy-dsds.c", "bananarchy-modemmonitor.c", "bananarchy-soundmonitor.c", "bananarchy-notifmonitor.c", "bananarchy-run-aligned.c", "bananarchy-session-loop.c", ]: out = os.path.join(self.tmpdir.name, name + ".bin") subprocess.run( [ "gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", "-I", SRC_DIR, "-o", out, os.path.join(SRC_DIR, name), ], check=True, ) def test_gsm7_and_ext_and_international_oa(self): udl, ud = encode_gsm7_with_fill("Price: 10\u20ac [ok]") # +358401234567 -> 12 digits, TON=1 NPI=1 (0x91) oa = bytes.fromhex("534810325476") pdu = build_deliver_pdu(12, 0x91, oa, 0x00, udl, ud) res = subprocess.run([self.bin, pdu], capture_output=True, text=True, check=True) self.assertIn("DELIVER\t2\t+358401234567\tPrice: 10\u20ac [ok]\n", res.stdout) def test_alphanumeric_sender_and_ucs2_surrogate(self): # Alphanumeric "Nokia" (5 chars -> 35 bits -> 9 hex digits rounded up = 9 nibbles) _, oa = encode_gsm7_with_fill("Nokia") oa_digits = (len("Nokia") * 7 + 3) // 4 payload = "Hi \U0001F34C".encode("utf-16-be") pdu = "tpdu:" + build_deliver_pdu( oa_digits, 0xD0, oa, 0x08, len(payload), payload, smsc=b"" ) res = subprocess.run([self.bin, pdu], capture_output=True, text=True, check=True) self.assertIn("DELIVER\t2\tNokia\tHi \U0001F34C\n", res.stdout) def test_multipart_csms_out_of_order_and_dedup(self): oa = bytes.fromhex("534810325476") udh1 = bytes([0x05, 0x00, 0x03, 0x2A, 0x02, 0x01]) udh2 = bytes([0x06, 0x08, 0x04, 0x00, 0x2A, 0x02, 0x02]) # Use matching 8-bit CSMS ref 0x2A across both parts udh2_8 = bytes([0x05, 0x00, 0x03, 0x2A, 0x02, 0x02]) u1, d1 = encode_gsm7_with_fill("Hello ", udh1) u2, d2 = encode_gsm7_with_fill("World!", udh2_8) pdu1 = build_deliver_pdu(12, 0x91, oa, 0x00, u1, d1, udh=True) pdu2 = build_deliver_pdu(12, 0x91, oa, 0x00, u2, d2, udh=True) res = subprocess.run( [self.bin, pdu2, pdu1, pdu1], capture_output=True, text=True, check=True, ) delivers = [ln for ln in res.stdout.splitlines() if ln.startswith("DELIVER\t")] self.assertEqual(delivers, ["DELIVER\t2\t+358401234567\tHello World!"]) # Also verify 16-bit CSMS UDH IEI 0x08 in UCS-2 udh16_1 = bytes([0x06, 0x08, 0x04, 0x12, 0x34, 0x02, 0x01]) udh16_2 = bytes([0x06, 0x08, 0x04, 0x12, 0x34, 0x02, 0x02]) p1 = udh16_1 + "One ".encode("utf-16-be") p2 = udh16_2 + "Two".encode("utf-16-be") q1 = build_deliver_pdu(12, 0x91, oa, 0x08, len(p1), p1, udh=True) q2 = build_deliver_pdu(12, 0x91, oa, 0x08, len(p2), p2, udh=True) _ = udh2 res2 = subprocess.run([self.bin, q1, q2], capture_output=True, text=True, check=True) self.assertIn("DELIVER\t2\t+358401234567\tOne Two\n", res2.stdout) def test_sxmo_calls_post_call_markers_ignored_and_reaped(self): phone_dir = os.path.join(BASE_DIR, "src", "dwm-plugins") cpp_src = os.path.join(self.tmpdir.name, "test_calls.cpp") cpp_bin = os.path.join(self.tmpdir.name, "test_calls.bin") with open(cpp_src, "w") as handle: handle.write( '#include \n' '#include \n' '#include "phone_data.h"\n' 'int main(int argc, char** argv) {\n' ' if (argc < 3) return 2;\n' ' std::string dir = argv[1];\n' ' std::string name = argv[2];\n' ' return bananarchy::isLiveSxmoCallFile(dir, name.c_str()) ? 0 : 1;\n' '}\n' ) pkg_cflags = subprocess.run( ["pkg-config", "--cflags", "xft", "pangoxft"], capture_output=True, text=True, check=True, ).stdout.split() subprocess.run( [ "g++", "-std=c++20", "-O2", "-Wall", "-Wextra", "-Werror", "-I", phone_dir, *pkg_cflags, "-o", cpp_bin, cpp_src, ], check=True, ) work = os.path.join(self.tmpdir.name, "calls_work") rt = os.path.join(work, "run") cfg = os.path.join(work, "cfg") data = os.path.join(work, "data") hooks = os.path.join(cfg, "sxmo", "hooks") calls_dir = os.path.join(rt, "sxmo_calls") os.makedirs(calls_dir, exist_ok=True) os.makedirs(hooks, exist_ok=True) os.makedirs(data, exist_ok=True) stubs = { "mmcli": "#!/bin/sh\necho 'No calls were found.'\nexit 0\n", "doas": "#!/bin/sh\nexit 1\n", "sxmo_hook_discard.sh": "#!/bin/sh\nexit 0\n", "sxmo_hook_hangup.sh": "#!/bin/sh\nexit 0\n", "sxmo_log": "#!/bin/sh\nexit 0\n", "pgrep": "#!/bin/sh\nexit 1\n", "dbus-send": "#!/bin/sh\nexit 0\n", "sxmo_hook_icons.sh": "icon_phn=P\n", "sxmo_common.sh": 'export SXMO_LOGDIR="${SXMO_LOGDIR:-$XDG_DATA_HOME/sxmo/modem}"\n', } for name, content in stubs.items(): path = os.path.join(hooks, name) with open(path, "w") as handle: handle.write(content) os.chmod(path, 0o755) appmenu = os.path.join(BASE_DIR, "overlay", "rootfs", "usr", "bin", "sxmo_appmenu.sh") modemcall = os.path.join(BASE_DIR, "overlay", "rootfs", "usr", "bin", "sxmo_modemcall.sh") env = dict(os.environ) env.update({ "HOME": work, "XDG_CONFIG_HOME": cfg, "XDG_DATA_HOME": data, "XDG_CACHE_HOME": os.path.join(work, "cache"), "XDG_STATE_HOME": os.path.join(work, "state"), "XDG_RUNTIME_DIR": rt, "SXMO_LOGDIR": os.path.join(data, "sxmo", "modem"), "SHELLSPEC_PATH": "1", "PATH": f"{hooks}:{os.environ.get('PATH', '/usr/bin:/bin')}", }) def clear_calls(): for fn in os.listdir(calls_dir): os.unlink(os.path.join(calls_dir, fn)) def check_live(files, probe_name, expect_live): clear_calls() for fn in files: open(os.path.join(calls_dir, fn), "w").close() res_cpp = subprocess.run([cpp_bin, calls_dir, probe_name], env=env) self.assertEqual( res_cpp.returncode == 0, expect_live, f"isLiveSxmoCallFile({files}, {probe_name}) expected {expect_live}", ) res_sh = subprocess.run( ["sh", "-c", f'. "{appmenu}"; has_tracked_calls'], env=env, ) self.assertEqual( res_sh.returncode == 0, expect_live, f"sxmo_appmenu.sh has_tracked_calls({files}) expected {expect_live}", ) for marker in [ "1.discardedcall", "1.hangedupcall", "1.terminated", "1.blockedcall", "1.mutedring", ]: check_live([marker], marker, False) check_live(["1.monitoredcall", "1.discardedcall"], "1.monitoredcall", False) check_live(["1.monitoredcall"], "1.monitoredcall", True) check_live(["1.monitoredcall", "1.mutedring"], "1.monitoredcall", True) for live_marker in [ "1.pickedupcall", "1.initiatedcall", "sub1_1.ringing-in", "sub1_1.active", ]: check_live([live_marker], live_marker, True) clear_calls() open(os.path.join(calls_dir, "1.monitoredcall"), "w").close() had_hangup_req = os.path.exists("/tmp/sxmo_hangup_requested") try: subprocess.run(["sh", modemcall, "hangup", "1"], env=env, check=True) finally: if not had_hangup_req and os.path.exists("/tmp/sxmo_hangup_requested"): os.unlink("/tmp/sxmo_hangup_requested") self.assertEqual(os.listdir(calls_dir), []) if __name__ == "__main__": unittest.main()