"""Durable allowlisted B2 operations; no firmware or arbitrary text commands.""" import hashlib import json import math import re import time from . import actions, configuration, full_configuration, restart, sim_guard, sim_selection from .delivery import MAX_DELIVERY_SECONDS from .observation import Observation from .transport_evidence import TransportEvidence from .web_protocol import decode_request, numeric_id_reply, time_reply COMMAND_SESSION_MAX_IDLE = 5 CONFIGURATION_KINDS = full_configuration.KINDS | { "read-settings", "configure-server1", "upload-configuration", "download-configuration", } def frame(text): raw = text.encode("cp1251") if not 1 <= len(raw) <= 255: raise ValueError("command length") return bytes((0x7B, len(raw), 0xFC, sum(raw) % 256)) + raw + b"}" class Commands: def __init__(self, store): self.store = store self.transport = TransportEvidence(store) self.sim_guard = sim_guard.SimGuard(store) self.sessions = {} self.session_started = {} self.session_activity = {} self.session_peers = {} self.session_ready = {} with store.db() as db: db.execute( "CREATE TABLE IF NOT EXISTS commands(id TEXT PRIMARY KEY, imei TEXT NOT NULL, " "digest TEXT NOT NULL, body TEXT NOT NULL)" ) db.execute( "CREATE INDEX IF NOT EXISTS commands_active " "ON commands(imei,json_extract(body,'$.state'))" ) # Effectful stages never replay. A committed full-image write may # resume its independent readback within the original deadline. for identifier, body in db.execute( "SELECT id,body FROM commands " "WHERE json_extract(body,'$.state') IN ('queued','dispatched')" ).fetchall(): value = json.loads(body) value = self.settle(db, identifier, value) if self.verification_recoverable(value): self.recover_verification(value) db.execute( "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) ) elif ( value["kind"] in actions.KINDS - {"request-position"} and value["state"] == "queued" ): value.update(state="expired", reason="host_restarted") db.execute( "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) ) elif ( value["state"] == "dispatched" or value.get("stage") in ("write", "verify", "restart") and value["state"] == "queued" ): value.update(state="uncertain", reason="host_restarted") db.execute( "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) ) @staticmethod def verification_recoverable(value): return ( value["kind"] == "configure-all" and value.get("stage") == "verify" and bool(value.get("write_reply_sent_at")) and value["state"] in ("queued", "dispatched") ) @staticmethod def recover_verification(value): value.update( state="queued", recovery_verification=True, recovery_at=time.time(), recovery_count=value.get("recovery_count", 0) + 1, not_before=max(value.get("not_before", 0), value.get("dispatched_at", 0) + 15), ) value.pop("session", None) def submit(self, body): # The original absolute deadline survives a lost HTTP reply and retry. # Keep it in the idempotency digest, outside the device command payload. original = body body = dict(body) not_after = body.pop("not_after", None) if not_after is not None and ( type(not_after) not in (int, float) or not math.isfinite(not_after) or not_after <= 0 ): raise ValueError("invalid command deadline") identifier, imei = body["id"], body["imei"] kind = body["kind"] password = body.get("password", "") if ( not re.fullmatch(r"[a-f0-9]{32}", identifier) or kind not in actions.KINDS | full_configuration.KINDS | {"read-settings", "configure-server1"} or not self.store.admitted(imei) ): raise ValueError("unsupported command") if kind not in actions.KINDS and not re.fullmatch(r"[0-9]{6}", password): raise ValueError("invalid password") allowed = {"id", "imei", "password", "kind"} details = {} if kind in actions.KINDS: details = actions.prepare(body) allowed = set(body) elif kind in full_configuration.KINDS: details = full_configuration.prepare(body) allowed = set(body) elif kind == "configure-server1": allowed |= {"expected", "target", "model", "firmware"} if body.get("model") != 231 or body.get("firmware") != "0.01": raise ValueError("unqualified firmware") details = { "expected": configuration.endpoint(body["expected"]), "target": configuration.endpoint(body["target"]), "stage": "preflight", } if set(body) - allowed: raise ValueError("unknown command fields") payload = password + "*GETP" digest = hashlib.sha256(json.dumps(original, sort_keys=True).encode()).hexdigest() with self.store.db() as db: db.execute("BEGIN IMMEDIATE") previous = db.execute( "SELECT digest,body FROM commands WHERE id=?", (identifier,) ).fetchone() if previous: if previous[0] != digest: raise ValueError("idempotency conflict") value = self.public(self.settle(db, identifier, json.loads(previous[1]))) value["transport"] = self.transport.read(db, identifier) return value if not_after is not None and not_after > time.time() + 600: raise ValueError("command deadline too distant") expired = not_after is not None and not_after <= time.time() if ( not expired and kind in (actions.KINDS | full_configuration.KINDS) - {"request-position"} and not self.sessions.get(imei) ): raise ValueError("device has no active session") last_configuration_at = 0 for (encoded,) in db.execute("SELECT body FROM commands WHERE imei=?", (imei,)): pending = json.loads(encoded) if pending["kind"] in full_configuration.KINDS: last_configuration_at = max( last_configuration_at, pending.get("configuration_received_at", 0), pending.get("write_reply_sent_at", 0), ) if not expired and self.active(db, imei): raise ValueError("command already pending") value = { "id": identifier, "kind": kind, **details, "state": "queued", "payload": payload, "password": password, "created_at": time.time(), "expires_at": time.time() + 120, "replies": [], "response_hashes": [], } if kind in actions.KINDS: value.update(expires_at=time.time() + 30, dispatch_deadline=time.time() + 3) if kind == "request-position": # A read may wait for reconnection until its original expiry. # Once dispatched it is never replayed, even after a crash. value["dispatch_deadline"] = value["expires_at"] if kind == "restart": value["expires_at"] = time.time() + 180 value["allowed_sessions"] = list(self.sessions.get(imei, ())) value.pop("payload") value.pop("password") elif kind in full_configuration.KINDS: value["expires_at"] = time.time() + (360 if kind == "select-sim" else 180) value["not_before"] = last_configuration_at + 15 if not_after is not None: value["expires_at"] = min(value["expires_at"], not_after) if "dispatch_deadline" in value: value["dispatch_deadline"] = min(value["dispatch_deadline"], not_after) if expired: value.update(state="expired", reason="request_deadline") elif kind == "probe-diagnostic-mode": lease_end = Observation.diagnostic_lease( db, value["observation_id"], identifier, bind_imei=imei ) value["expires_at"] = min(value["expires_at"], lease_end) value["dispatch_deadline"] = min(value["dispatch_deadline"], lease_end) db.execute( "INSERT INTO commands VALUES(?,?,?,?)", (identifier, imei, digest, json.dumps(value)), ) return self.public(value) def settle(self, db, identifier, value): state = self.public(value)["state"] if state != value["state"]: value = {**value, "state": state} db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)) return value def active(self, db, imei): # Terminal history never enters the per-packet/per-session hot path. rows = db.execute( "SELECT id,body FROM commands WHERE imei=? " "AND json_extract(body,'$.state') IN ('queued','dispatched') ORDER BY rowid", (imei,), ).fetchall() result = [] for identifier, encoded in rows: value = self.settle(db, identifier, json.loads(encoded)) if value["state"] in ("queued", "dispatched"): result.append((identifier, value)) return result def wait_delay(self, imei): with self.store.db() as db: # Idle senders sleep until admission, a packet or a new command. # Active staged operations retain their existing bounded timers. return 1 if self.active(db, imei) else None @staticmethod def public(value): value = dict(value) if ( value["state"] == "queued" and value.get("dispatch_deadline", float("inf")) < time.time() ): value["state"] = "expired" if value["expires_at"] < time.time() and value["state"] in ("queued", "dispatched"): value["state"] = ( "uncertain" if value.get("write_reply_sent_at") or value.get("stage") == "restart" else "expired" if value["state"] == "queued" else "unconfirmed" ) hidden = { "payload", "password", "before", "after", "response_hashes", "session", "binary", "token", "allowed_sessions", "restart_sessions", "target_configuration", "before_configuration", "sim_guard", } return {**{k: v for k, v in value.items() if k not in hidden}, "transport": []} def get(self, identifier): with self.store.db() as db: db.execute("BEGIN IMMEDIATE") row = db.execute("SELECT body FROM commands WHERE id=?", (identifier,)).fetchone() if not row: raise ValueError("unknown command") value = self.public(self.settle(db, identifier, json.loads(row[0]))) value["transport"] = self.transport.read(db, identifier) return value def take(self, imei, session="test"): delivery = self.take_delivery(imei, session) return delivery[0] if delivery else None def take_delivery(self, imei, session, *, with_receipt=False): # A configuration reload can leave half-open old sockets beside the new # live ones. Never let whichever sender wakes first steal the command. active = tuple(self.sessions.get(imei, ())) eligible = [s for s in active if self.session_ready.get((imei, s), True)] if active and session not in eligible: return None observed = [s for s in eligible if (imei, s) in self.session_activity] if observed and session != max( observed, key=lambda s: (self.session_activity.get((imei, s), 0), s) ): return None with self.store.db() as db: db.execute("BEGIN IMMEDIATE") for identifier, value in self.active(db, imei): if ( self.verification_recoverable(value) and value["state"] == "dispatched" and session != value.get("session") and self.session_started.get((imei, session), 0) > value.get("monotonic", 0) ): # A new B2 connection can outlive a half-open predecessor. # Only the independent read migrates, never the image write. self.recover_verification(value) db.execute( "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) ) if ( value["state"] == "queued" and value.get("dispatch_deadline", float("inf")) < time.time() ): value["state"] = "expired" db.execute( "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) ) continue if ( value["kind"] == "configure-server1" and value.get("stage") == "write" and value["state"] == "dispatched" and time.time() - value["dispatched_at"] >= 15 ): # SETP may reconnect before its reply. Read-only verification can # move to a new TCP session; the write itself is never resent. value.update(stage="verify", state="queued") value.pop("session", None) if ( value["state"] != "queued" or value["expires_at"] < time.time() or value.get("not_before", 0) > time.time() ): continue if value.get("session") and value["session"] != session: continue if ( value["kind"] in actions.KINDS - {"request-position"} and session not in value["allowed_sessions"] ): continue if value["kind"] == "request-position" and session not in active: continue if value["kind"] in CONFIGURATION_KINDS and active: last_input = self.session_activity.get((imei, session)) if last_input is None or not ( 0 <= time.monotonic() - last_input <= COMMAND_SESSION_MAX_IDLE ): # A drained but silent TCP stream may already be dead. # Await fresh device input; retain the original deadline # and never replay a previously dispatched stage. continue if not self.store.admitted(imei): return None if value["kind"] == "probe-diagnostic-mode": try: Observation.diagnostic_lease(db, value["observation_id"], identifier) except ValueError: value.update(state="expired", reason="observation_closed") db.execute( "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) ) continue if value.get("sim_guard") and value.get("stage") in ("write", "restart"): guard = self.sim_guard.check(imei, value["sim_guard"], db=db) if guard != "matched": if guard == "changed": value.update(state="rejected", reason="sim_card_changed") db.execute( "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier), ) continue value.update( state="dispatched", dispatched_at=time.time(), monotonic=time.monotonic(), session=session, ) restarting = value["kind"] == "restart" or ( value["kind"] == "select-sim" and value.get("stage") == "restart" ) if restarting: value["restart_sessions"] = list(self.sessions.get(imei, ())) if value["kind"] == "configure-server1": value["payload"] = configuration.payload(value) if value["stage"] == "write": value["write_dispatched_at"] = time.time() elif value["kind"] in full_configuration.KINDS and not restarting: value["payload"] = full_configuration.payload(value) db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)) data = ( actions.frame(value) if value["kind"] in actions.KINDS or restarting else frame(value["payload"]) ) deadline = value["monotonic"] + min( MAX_DELIVERY_SECONDS, max(0, value["expires_at"] - value["dispatched_at"]) ) if with_receipt: ticket = self.transport.prepare(db, identifier, value.get("stage", "execute")) return data, deadline, ticket return data, deadline return None def web_receive(self, raw, peer, *, with_deadline=False): """Qualified B2 HTTP channel, scoped to an admitted active modem peer.""" expires = time.time() + 12 def result(reply): if reply is None or not with_deadline: return reply return reply, time.monotonic() + max(0, expires - time.time()) imei, command, payload = decode_request(raw) if not self.store.admitted(imei) or not any( self.session_peers.get((imei, s)) == peer for s in tuple(self.sessions.get(imei, ())) ): return None reply = bytes.fromhex("5b00030006025d") if command == 6 else None if command == 1: number = self.store.numeric_id(imei) return result(numeric_id_reply(number) if number is not None else None) if command == 7: # A clock request is independent of a settings transaction. It # cannot advance its stage, confirm a write or extend its deadline. return result(time_reply(int(time.time()))) if command == 5: reply = bytes.fromhex("5b00030005015d") with self.store.db() as db: db.execute("BEGIN IMMEDIATE") for identifier, value in self.active(db, imei): if ( value["kind"] not in full_configuration.KINDS or value["state"] != "dispatched" or value["expires_at"] <= time.time() ): continue if command == 5 and value["stage"] in ("preflight", "verify"): full_configuration.upload(value, payload) elif command == 2 and value["stage"] == "write": guard = self.sim_guard.check(imei, value.get("sim_guard"), db=db) if guard != "matched": # No image bytes leave the process for a missing/replaced card. value.update( state="rejected" if guard == "changed" else "unconfirmed", reason="sim_card_changed" if guard == "changed" else "sim_identity_unavailable", ) reply = None else: reply = full_configuration.download(value) else: continue expires = min(expires, value["expires_at"]) db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)) break return result(reply) def receive(self, imei, raw, session="test"): self.sim_guard.observe(imei, raw) self.receive_actions(imei, raw, session) started = self.session_started.get((imei, session)) if started is not None: with self.store.db(write=True) as db: for identifier, value in self.active(db, imei): matched = ( self.sim_guard.check( imei, value.get("sim_guard"), after=value.get("dispatched_at"), db=db ) == "matched" ) if ( restart.observe(value, raw, session, started) or matched and sim_selection.observe(value, raw, session, started) ): if value.get("sim_guard") and value["state"] == "sim_selected": value["sim_guard_verified"] = True db.execute( "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) ) # Preserve text response evidence privately, never interpret receipt as settings applied. offset, replies = 2, [] while offset < len(raw) - 1: size = int.from_bytes(raw[offset + 1 : offset + 3], "little") if raw[offset] == 3: replies.append( ( int.from_bytes(raw[offset + 3 : offset + 7], "little"), raw[offset + 7 : offset + 7 + size].decode("cp1251", errors="replace"), ) ) offset += size + 8 if not replies: return with self.store.db(write=True) as db: for identifier, value in self.active(db, imei): if ( value["kind"] in actions.KINDS | full_configuration.KINDS or value["state"] != "dispatched" or value["expires_at"] < time.time() or value.get("session") != session ): continue accepted = [] for measured, reply in replies: digest = hashlib.sha256(f"{measured}:{reply}".encode()).hexdigest() if ( # This B2 timestamps text about 4 s behind the VPS clock. # Bound skew and require strictly newer evidence at every stage. measured < int(value["dispatched_at"]) - 10 or measured > time.time() + 5 or measured <= value.get("last_response_measured", 0) or digest in value.get("response_hashes", []) ): continue value.setdefault("response_hashes", []).append(digest) if value["kind"] == "configure-server1": if configuration.response(value, reply, self.store.config["tracker"]): accepted.append(reply) break # Never use two messages from one packet for separate stages. elif reply.startswith("#1="): accepted.append(reply) if not accepted: continue value["last_response_measured"] = measured if value["kind"] == "read-settings": value.update(state="reply_received", replies=accepted) elif value["stage"] == "verify" and value["state"] == "queued": value.pop("session", None) value["not_before"] = max( value.get("not_before", 0), value["write_dispatched_at"] + 15 ) value.update(received_at=time.time()) db.execute("UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier)) def receive_actions(self, imei, raw, session): replies = list(actions.confirmations(raw)) # B2 publishes the same token receipt through both monitoring streams. # Correlate the device and token, not the socket that carried the request. # Text commands still have no such correlation and are excluded below. if ( not replies or session not in self.sessions.get(imei, ()) or not self.store.admitted(imei) ): return with self.store.db(write=True) as db: for identifier, value in self.active(db, imei): if ( value["kind"] not in actions.KINDS or value.get("encoding") == "text" or value["state"] != "dispatched" or value["expires_at"] < time.time() ): continue for code, token in replies: if token != value["token"] or code > 9: continue value.update( received_at=time.time(), roundtrip_seconds=time.monotonic() - value["monotonic"], device_code=code, reply_via_alternate_session=session != value.get("session"), ) if code == 6 or value["kind"] == "restart" and code == 0: value.setdefault("device_accepted_at", time.time()) else: value["state"] = "device_confirmed" if code == 0 else "device_rejected" db.execute( "UPDATE commands SET body=? WHERE id=?", (json.dumps(value), identifier) ) break