"""RF admin link to a MeshCore repeater (or companion) through a companion radio. Shared by the tth.meshcore modules. The companion is either a TCP companion (e.g. an openHop companion), a USB serial companion, or a BLE companion bonded on the host the module runs on. Everything below was learned the hard way: * subscribe to replies BEFORE sending anything -- wait_for_event only sees events created after it is called, so a reply delivered meanwhile is lost; * set the companion's path hash width to 2 B (its own pref, default 1 B); * a repeater that never advertised can still be addressed: build the contact from its full pubkey (the login secret is derived from the contact); * use send_login_sync -- plain send_login + wait times out on a flood login; * never echo the password: the node's `password` reply contains it. A COMPANION target (companion=True), fw 1.18+ / Solo 2.0+: its ACL is the "remote CLI" flag (ContactInfo flags 0x10) on its contacts, set on the companion itself -- the same mc_admins keys as on the repeaters, nobody else. A command comes as TXT_TYPE_CLI_COMMAND (3), encrypted to that contact's shared secret, so only a flagged key gets an answer; there is no password step on top. Type 1 that send_cmd uses is a CLI *reply* there and only lands in its app. Plus what the RF itself does: replies get lost and occasionally arrive late, so every CLI exchange checks that the reply came from the target and looks like the expected kind of answer, and retries otherwise. """ import asyncio import re import time try: from meshcore import EventType, MeshCore HAS_MESHCORE = True except ImportError: # reported by the module via missing_required_lib HAS_MESHCORE = False HEX64 = re.compile(r"^[0-9a-f]{64}$") class LinkError(Exception): pass class Link: def __init__( self, transport, target, password="", path_hash_mode=1, reply_timeout=None, retries=None, companion=False, name=None, ): self.transport = transport self.companion = companion self.last_reply_ts = None # node clock (sender_timestamp) of the last matched reply self.last_reply_at = None self.contact_name = (name or "target")[:31] self.target_pk = target.lower() if not HEX64.match(self.target_pk): raise LinkError("target must be the node's full 64-hex pubkey") self.password = password or "" self.path_hash_mode = path_hash_mode # A repeater with a BLE client connected lost three CLI replies in a row # (a BLE link mutes DIRECT traffic, and CLI replies are DIRECT), so the # default is generous; both can be set per host in mc_transport. self.reply_timeout = float(reply_timeout or transport.get("reply_timeout", 20)) self.retries = int(retries if retries is not None else transport.get("retries", 4)) self.mc = None self.contact = None self.inbox = [] self.log = [] # human-readable trace, returned by the modules (no secrets) # ── session ───────────────────────────────────────────────────────────── async def open(self): t = self.transport if t.get("type") == "serial": self.mc = await MeshCore.create_serial(t["port"], int(t.get("baud", 115200))) elif t.get("type") == "ble": # No PIN here on purpose: it would end up in the task's logged # arguments. The companion is bonded once by hand (bluetoothctl pair) # on the host the module runs on, and the bond does the encryption. self.mc = await MeshCore.create_ble(t["address"]) else: self.mc = await MeshCore.create_tcp( host=t.get("host", "127.0.0.1"), port=int(t["port"]), auto_reconnect=False ) if self.mc is None: raise LinkError(f"cannot connect to companion {t}") # Bench guard: an inventory that says which frequency its companion must # be on never transmits anywhere else (a bench run must not reach the # live mesh because a cable went to the wrong board). if t.get("expect_freq") is not None: freq = float((self.mc.self_info or {}).get("radio_freq") or 0) if abs(freq - float(t["expect_freq"])) > 0.01: await self.mc.disconnect() raise LinkError(f"companion is on {freq} MHz, inventory expects {t['expect_freq']} -- nothing sent") self.mc.subscribe(EventType.CONTACT_MSG_RECV, lambda ev: self.inbox.append(ev.payload)) if (await self.mc.commands.get_path_hash_mode()) != self.path_hash_mode: await self.mc.commands.set_path_hash_mode(self.path_hash_mode) await self.mc.ensure_contacts() self.contact = self._find_contact() if self.contact is None: await self._add_contact() await self.mc.start_auto_message_fetching() async def close(self): if self.mc is not None: await self.mc.disconnect() def self_pubkey(self): return (self.mc.self_info or {}).get("public_key", "").lower() def _find_contact(self): for c in (self.mc.contacts or {}).values(): if (c.get("public_key") or "").lower() == self.target_pk: return c return None async def _add_contact(self): contact = { "public_key": self.target_pk, "type": 1 if self.companion else 2, "flags": 0, "out_path": "", "out_path_len": -1, # last_advert = now: with 0 it is the "oldest" contact and the next # eviction (table full) would pick exactly the one just created. "out_path_hash_mode": 0, "adv_name": self.contact_name, "last_advert": int(time.time()), "adv_lat": 0.0, "adv_lon": 0.0, } ev = await self.mc.commands.add_contact(contact) if ev is not None and ev.type == EventType.ERROR: # Table full (a busy companion with auto-add sits at 1000/1000): # make room the way the firmware's own auto-add does -- drop the # contact heard longest ago that is not a favourite. cands = [ c for c in (self.mc.contacts or {}).values() if not (c.get("flags") or 0) & 1 and (c.get("public_key") or "").lower() != self.target_pk ] if not cands: raise LinkError(f"companion refused the contact ({ev.payload}) and nothing can be evicted") victim = min(cands, key=lambda c: c.get("last_advert") or 0) await self.mc.commands.remove_contact(victim["public_key"]) self.log.append(f"contact table full: evicted {victim.get('adv_name') or victim['public_key'][:12]}") await self.mc.commands.add_contact(contact) await asyncio.sleep(2) fresh = await self.mc.commands.get_contacts() for c in ((fresh.payload if fresh else None) or {}).values(): if (c.get("public_key") or "").lower() == self.target_pk: self.contact = c self.log.append("contact created from pubkey") return raise LinkError("could not create a contact for the target") async def login(self): """Admin login; blank password works for a client already in the ACL.""" for attempt in range(1 + self.retries): # a stale path from an earlier session would send the login nowhere await self.mc.commands.reset_path(self.contact) ev = await self.mc.commands.send_login_sync(self.contact, self.password, timeout=45) if ev is not None and ev.type == EventType.LOGIN_SUCCESS: # LOGIN_SUCCESS alone is not enough: a password that equals the # node's GUEST password (or a blank one when guest is blank) logs # in as guest, and the admin requests then just go unanswered. if not (ev.payload or {}).get("is_admin"): raise LinkError( "logged in as GUEST, not admin -- the node's admin password differs " "(prefs override the build) or this companion is not admin in its ACL" ) self.log.append(f"login ok as admin (attempt {attempt + 1})") return True raise LinkError("login refused or no reply (wrong password, or not in the ACL)") # ── CLI ───────────────────────────────────────────────────────────────── def _from_target(self, msg): pfx = (msg.get("pubkey_prefix") or "").lower() return bool(pfx) and self.target_pk.startswith(pfx) async def cli(self, cmd, expect, retries=None, timeout=None, quiet=False, before_send=None): """Send one CLI command and return the reply text that matches `expect` (regex). A reply that does not match (a late answer to an earlier command, or another node) is drained and the command is resent, up to `retries`. quiet: no trace line on success (hundreds of firmware chunks). before_send: awaited before every attempt (the OTA airtime budget). """ retries = self.retries if retries is None else retries timeout = self.reply_timeout if timeout is None else timeout # never log a secret the command carries (the trace is returned to Ansible) shown = cmd for secret_cmd in ("password ", "ble pin "): if cmd.startswith(secret_cmd): shown = secret_cmd + "***" if quiet and len(shown) > 24: shown = shown[:24] + "..." for attempt in range(1 + retries): self.inbox.clear() if before_send is not None: await before_send() if self.companion: await self.send_cli_command(cmd) else: await self.mc.commands.send_cmd(self.contact, cmd) deadline = time.monotonic() + timeout while time.monotonic() < deadline: for msg in list(self.inbox): text = (msg.get("text") or "").strip() if self._from_target(msg) and re.search(expect, text): if not quiet: self.log.append(f"$ {shown} -> {self._redact(text)}") # The reply carries the NODE's clock: what fw_facts reports as skew. self.last_reply_ts = msg.get("sender_timestamp") self.last_reply_at = time.time() await asyncio.sleep(0.5) # let a straggler land before the next command return text await asyncio.sleep(0.3) seen = [self._redact((m.get("text") or "").strip()) for m in self.inbox] self.log.append(f"$ {shown} -> no matching reply (attempt {attempt + 1}, got {seen})") raise LinkError(f"no reply matching /{expect}/ to `{shown}`") async def send_cli_command(self, cmd): """CMD_SEND_TXT_MSG with txt_type 3 -- what a companion's remote CLI answers.""" data = ( b"\x02\x03\x00" + int(time.time()).to_bytes(4, "little") + bytes.fromhex(self.target_pk[:12]) + cmd.encode() ) ev = await self.mc.commands.send(data, [EventType.MSG_SENT, EventType.ERROR]) if ev is not None and ev.type == EventType.ERROR: raise LinkError(f"companion refused to send `{cmd}`: {ev.payload}") def name(self): return (self.contact or {}).get("adv_name") or "" def _redact(self, text): return text.replace(self.password, "***") if self.password else text async def get(self, key): """`get ` -> the value string (reply is '> value').""" text = await self.cli(f"get {key}", r"^(>|Err|\?)") if not text.startswith(">"): raise LinkError(f"`get {key}`: {text}") return text[1:].strip() async def acl(self): """Real ACL as {prefix12: perm}, via the binary access-list request.""" for attempt in range(1 + self.retries): res = await self.mc.commands.req_acl_sync(self.contact, timeout=40) if res is not None: return {e["key"].lower(): e["perm"] for e in res} self.log.append(f"ACL request: no reply (attempt {attempt + 1})") raise LinkError("ACL request: no reply") def run(coro): return asyncio.run(coro)