feat(vps): ship durable ARNavi host with reproducible install and recovery

This commit is contained in:
DCCONSTRUCTIONS
2026-09-28 18:43:39 +03:00
parent b6efae3272
commit d684eb7e05
30 changed files with 5520 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
"""Headless NODE.DC Mission VPS Host; Python 3.12 standard library only."""
VERSION = "0.1.41"
+19
View File
@@ -0,0 +1,19 @@
import argparse
import asyncio
import json
from .service import Service
from .store import Store
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=("serve", "invitation", "status"))
parser.add_argument("--state", default="/var/lib/ndc-mission-vps")
args = parser.parse_args()
store = Store(args.state)
if args.action == "serve":
asyncio.run(Service(store).run())
elif args.action == "invitation":
store.invitation()
print("Invitation ready in /opt/nodedc-mission-vps/connect.key (valid 24 hours).")
else:
print(json.dumps(store.status()))
+120
View File
@@ -0,0 +1,120 @@
"""B2 manual §10 + INTERNAL SERVER_COM token envelope; no arbitrary commands."""
import re
import secrets
KINDS = {
"request-position",
"restart",
"pulse-output",
"set-output",
"upload-configuration",
"download-configuration",
"probe-diagnostic-mode",
}
def prepare(body):
if body.get("model") != 231 or body.get("firmware") != "0.01":
raise ValueError("unqualified action firmware")
allowed = {"id", "imei", "kind", "model", "firmware"}
if body["kind"] == "probe-diagnostic-mode":
# INTERNAL SERVER_COM 01 00. Engineering qualification only: neither
# a SIM read nor a promise about this firmware's mode/termination.
# Admission additionally requires an explicit live observation lease.
allowed.add("observation_id")
if not isinstance(body.get("observation_id"), str) or not re.fullmatch(
r"[a-f0-9]{32}", body["observation_id"]
):
raise ValueError("diagnostic probe requires observation")
command = b"\x01\x00"
elif body["kind"] == "request-position":
command = b"\x01\x01"
elif body["kind"] == "restart":
# B2 manual §10. A token receipt is not proof of a completed restart.
command = b"\x01\x07"
elif body["kind"] == "upload-configuration" and body.get("encoding") == "binary":
# Documented read-only counterpart to SERV*1.9; no image is written.
allowed.add("encoding")
command = b"\x01\x09"
elif body["kind"] in ("upload-configuration", "download-configuration"):
allowed.add("password")
password = body.get("password")
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
raise ValueError("invalid password")
if set(body) - allowed:
raise ValueError("unknown action fields")
# B2 manual §10: synchronize with the configured web endpoint. Download
# may apply settings: the endpoint owns staged data and readback checks.
number = 9 if body["kind"] == "upload-configuration" else 8
return {"encoding": "text", "binary": f"{password}*SERV*1.{number}".encode().hex()}
elif body["kind"] == "set-output":
allowed |= {"pin", "enabled", "encoding", "password"}
pin = body.get("pin")
enabled = body.get("enabled")
if type(pin) is not int or pin not in (4, 5, 6):
raise ValueError("unsupported output")
if type(enabled) is not bool:
raise ValueError("enabled must be boolean")
if body.get("encoding", "text") != "text":
raise ValueError("set-output requires text encoding")
password = body.get("password")
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
raise ValueError("invalid password")
if set(body) - allowed:
raise ValueError("unknown action fields")
# B2 manual section 10: explicit, persistent low-side output state.
# The caller must request both transitions; there is no implicit retry.
return {
"encoding": "text",
"binary": f"{password}*SERV*8.{pin}.{int(enabled)}".encode("ascii").hex(),
}
elif body["kind"] == "pulse-output":
allowed |= {"pin", "seconds", "encoding"}
pin, seconds = body["pin"], body["seconds"]
if type(pin) is not int or pin not in (4, 5, 6):
raise ValueError("unsupported output")
if type(seconds) is not int or not 1 <= seconds <= 5:
raise ValueError("pulse must be 1..5 seconds")
command = bytes((0x18, pin, 0, seconds))
encoding = body.get("encoding", "binary")
if encoding not in ("binary", "text"):
raise ValueError("unsupported action encoding")
if encoding == "text":
allowed.add("password")
password = body.get("password")
if not isinstance(password, str) or not re.fullmatch(r"[0-9]{6}", password):
raise ValueError("invalid password")
if set(body) - allowed:
raise ValueError("unknown action fields")
# B2 manual §10: FC text has no token envelope. A reply to an
# unrelated command must never turn this into confirmed actuation.
return {
"encoding": "text",
"binary": f"{password}*SERV*24.{pin}.0.{seconds}".encode("ascii").hex(),
}
else:
raise ValueError("unsupported action")
if set(body) - allowed:
raise ValueError("unknown action fields")
result = {"token": secrets.randbits(32), "binary": command.hex()}
if body["kind"] == "probe-diagnostic-mode":
result["observation_id"] = body["observation_id"]
return result
def frame(value):
if value.get("encoding") == "text":
raw = bytes.fromhex(value["binary"])
return bytes((0x7B, len(raw), 0xFC, sum(raw) % 256)) + raw + b"}"
raw = b"\xff" + value["token"].to_bytes(4, "little") + bytes.fromhex(value["binary"])
return bytes((0x7B, len(raw), 0xFF, sum(raw) % 256)) + raw + b"}"
def confirmations(raw):
offset = 2
while offset < len(raw) - 1:
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
if raw[offset] == 9 and size == 5:
yield raw[offset + 7], int.from_bytes(raw[offset + 8 : offset + 12], "little")
offset += size + 8
+585
View File
@@ -0,0 +1,585 @@
"""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
+85
View File
@@ -0,0 +1,85 @@
"""B2 231 / 0.01: documented SETP #1 only, with a surviving secondary uplink.
Never translate USB field numbers into SETP groups. No generic command escape.
GETP contains secrets; only the explicit endpoint projection may reach Core UI.
"""
import re
import time
def endpoint(value):
if not isinstance(value, dict) or set(value) != {"host", "port"}:
raise ValueError("invalid endpoint")
host, port = value["host"], value["port"]
if (
not isinstance(host, str)
or not 1 <= len(host) <= 32
or not re.fullmatch(r"[A-Za-z0-9]+(?:[.-][A-Za-z0-9]+)*", host)
or type(port) is not int
or not 1 <= port <= 65535
):
raise ValueError("invalid endpoint")
return {"host": host, "port": port}
def groups(reply):
if not isinstance(reply, str) or not reply.startswith("#") or len(reply) > 4096:
raise ValueError("invalid GETP")
result = {}
for part in reply.split("#")[1:]:
key, sep, value = part.partition("=")
if not sep or not key.isdecimal() or key in result:
raise ValueError("invalid GETP group")
result[key] = value
if not {"1", "2", "5", "7", "26"} <= result.keys():
raise ValueError("incomplete GETP")
return result
def server(value):
parts = value.split(",")
# Preserve the undocumented fifth value, accept only the qualified empty form.
if len(parts) != 5 or parts[2:] != ["0", "0", ""]:
raise ValueError("unsupported server settings")
return endpoint({"host": parts[0], "port": int(parts[1])})
def response(operation, reply, tracker):
"""Advance only from complete, scoped read evidence. Caller persists atomically."""
try:
actual = groups(reply)
primary, secondary = server(actual["1"]), server(actual["26"])
except (ValueError, KeyError):
return False
stage = operation["stage"]
if stage == "preflight":
if primary != operation["expected"] or secondary != endpoint(tracker):
operation.update(state="rejected", reason="configuration_changed")
elif primary == operation["target"]:
operation.update(state="verified", verified_at=time.time(), server1=primary)
else:
operation.update(before=actual, stage="write", state="queued")
elif stage == "write":
# SETP acknowledgement is never enough: issue a separate GETP after a drain interval.
operation.update(stage="verify", state="queued", not_before=time.time() + 3)
elif stage == "verify":
before = operation["before"]
preserved = {k: v for k, v in actual.items() if k != "1"} == {
k: v for k, v in before.items() if k != "1"
}
operation["after"] = actual
if primary == operation["target"] and preserved:
operation.update(state="verified", verified_at=time.time(), server1=primary)
elif actual == before:
operation.update(state="not_applied", reason="settings_unchanged")
else:
operation.update(state="uncertain", reason="readback_mismatch")
return True
def payload(operation):
if operation["stage"] == "write":
target = operation["target"]
return f"{operation['password']}*SETP*#1={target['host']},{target['port']}"
return operation["password"] + "*GETP"
+109
View File
@@ -0,0 +1,109 @@
"""Bound the lifetime of command bytes in a Linux TCP send queue.
TCP acknowledgement is transport evidence only, never command confirmation.
All writes on the guarded stream must pass through write(), including ACKs.
"""
import asyncio
import fcntl
import socket
import struct
import sys
import termios
import time
from collections import deque
MAX_DELIVERY_SECONDS = 30
def queued_bytes(sock):
if sys.platform != "linux":
# Production is qualified on Ubuntu only. Other platforms conservatively
# retain the deadline, without claiming TCP acknowledgement evidence.
return None
return struct.unpack("i", fcntl.ioctl(sock, termios.TIOCOUTQ, struct.pack("i", 0)))[0]
class Delivery:
def __init__(self, writer):
self.writer = writer
self.sock = writer.get_extra_info("socket")
# Also abort queued kernel data on EOF, task cancellation and shutdown.
# transport.abort() alone discards only asyncio's own write buffer.
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
if sys.platform == "linux":
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, 30000)
self.written = 0
self.pending = deque()
self.timer = None
def ready(self):
"""Do not enqueue a new command behind an unacknowledged stream prefix.
This is Linux transport admission, not device execution confirmation.
Non-Linux engineering tests retain their conservative expiry watchdog.
"""
if self.writer.is_closing() or self.writer.transport.get_write_buffer_size():
return False
try:
queued = queued_bytes(self.sock)
return queued is None or queued == 0
except OSError:
return False
def write(self, data, deadline=None, observe=None):
started = time.monotonic()
def note(phase, reason=None):
if observe is not None:
observe(phase, time.time(), time.monotonic() - started, reason)
if deadline is not None and deadline <= time.monotonic():
note("unconfirmed", "expired_before_write")
self.abort()
raise TimeoutError("command delivery expired before write")
try:
self.writer.write(data)
except (OSError, RuntimeError):
note("unconfirmed", "write_failed")
raise
note("written")
self.written += len(data)
if deadline is not None:
self.pending.append((self.written, deadline, note))
self.check()
def check(self):
self.cancel_timer()
if not self.pending:
return
if self.writer.is_closing():
self.abort()
return
try:
queued = queued_bytes(self.sock)
if queued is not None:
acknowledged = self.written - queued - self.writer.transport.get_write_buffer_size()
while self.pending and self.pending[0][0] <= acknowledged:
self.pending.popleft()[2]("tcp_acknowledged")
if self.pending:
remaining = min(deadline for _, deadline, _ in self.pending) - time.monotonic()
if remaining <= 0:
self.abort("delivery_deadline")
else:
self.timer = asyncio.get_running_loop().call_later(
min(0.25, remaining), self.check
)
except OSError:
self.abort("socket_error")
def cancel_timer(self):
if self.timer is not None:
self.timer.cancel()
self.timer = None
def abort(self, reason="connection_closed"):
self.cancel_timer()
while self.pending:
self.pending.popleft()[2]("unconfirmed", reason)
self.writer.transport.abort()
+113
View File
@@ -0,0 +1,113 @@
"""Whole-image B2 transactions: fresh preflight, one write, independent readback."""
import hashlib
import re
import time
from . import sim_guard, sim_selection
from .usb_protocol import decode_configuration
from .web_protocol import settings_reply
KINDS = {"read-configuration", "configure-all", "select-sim"}
def prepare(body):
allowed = {"id", "imei", "kind", "password", "model", "firmware"}
if body.get("model") != 231 or body.get("firmware") != "0.01":
raise ValueError("unqualified configuration firmware")
result = {"stage": "preflight"}
if body["kind"] in ("configure-all", "select-sim"):
allowed |= {"expected_sha256", "target_configuration"}
if not re.fullmatch(r"[a-f0-9]{64}", body["expected_sha256"]):
raise ValueError("invalid predecessor")
raw = bytes.fromhex(body["target_configuration"])
config = decode_configuration(raw)
settings_reply(config) # transport-size admission, without a write
result.update(expected_sha256=body["expected_sha256"], target_configuration=raw.hex())
if "sim_guard" in body:
allowed.add("sim_guard")
result["sim_guard"] = sim_guard.prepare(body["sim_guard"])
if body["kind"] != "select-sim" or body.get("sim_slot") != result["sim_guard"]["slot"]:
raise ValueError("SIM guard requires exclusive selection of the same slot")
if body["kind"] == "select-sim":
allowed |= {"sim_slot", "sim_policy"}
mask = (1 << 10) | (1 << 20)
policy = body.get("sim_policy", "exclusive")
if policy == "both":
if "sim_slot" in body or config.integer(72, 4) & mask:
raise ValueError("both SIMs must be permitted without an exclusive slot")
result["sim_policy"] = policy
elif policy == "exclusive":
slot = body.get("sim_slot")
if type(slot) is not int or slot not in (1, 2):
raise ValueError("invalid SIM slot")
if config.integer(72, 4) & mask != 1 << (20 if slot == 1 else 10):
raise ValueError("SIM flags do not match requested slot")
result["sim_slot"] = slot
else:
raise ValueError("invalid SIM policy")
if set(body) - allowed:
raise ValueError("unknown configuration fields")
return result
def payload(value):
number = 8 if value["stage"] == "write" else 9
return value["password"] + f"*SERV*1.{number}"
def upload(value, raw):
config = decode_configuration(raw)
digest = hashlib.sha256(raw).hexdigest()
value.update(
configuration=raw.hex(), configuration_sha256=digest, configuration_received_at=time.time()
)
if value["kind"] == "read-configuration":
value.update(state="observed", verified_at=time.time())
elif value["stage"] == "preflight":
value["before_configuration"] = raw.hex()
target = decode_configuration(bytes.fromhex(value["target_configuration"]))
# Preserve every unknown field and the recovery channels. Core controls
# the reviewed profile fields; network migration of these requires its
# own destination-admission transaction, not a blind full-image write.
critical = (3, 4, 5, 8, 70, 71)
if (
digest != value["expected_sha256"]
or [r.number for r in config.records] != [r.number for r in target.records]
or any(config.value(n) != target.value(n) for n in critical)
):
value.update(state="rejected", reason="configuration_predecessor_mismatch")
elif raw.hex() == value["target_configuration"]:
value.update(state="verified", verified_at=time.time(), unchanged=True)
if value["kind"] == "select-sim":
sim_selection.queue_restart(value)
else:
value.update(state="queued", stage="write", not_before=time.time() + 15)
value.pop("session", None)
elif value["stage"] == "verify":
state = (
"verified"
if raw.hex() == value["target_configuration"]
else "not_applied"
if raw.hex() == value["before_configuration"]
else "uncertain"
)
value.update(state=state, verified_at=time.time())
if state == "verified" and value["kind"] == "select-sim":
sim_selection.queue_restart(value)
def download(value):
"""Call only inside the durable transaction, before writing the HTTP socket."""
if value.get("write_reply_sent_at"):
return None
raw = settings_reply(decode_configuration(bytes.fromhex(value["target_configuration"])))
value.update(
write_reply_sent_at=time.time(),
write_reply_sha256=hashlib.sha256(raw).hexdigest(),
stage="verify",
state="queued",
not_before=time.time() + 15,
)
value.pop("session", None)
return raw
+246
View File
@@ -0,0 +1,246 @@
"""Explicit, bounded interoperability evidence on the owned socket.
Disabled unless the authenticated owner arms a 180-second lease. Unknown traffic
is never treated as telemetry. A captured identity reply may be replayed once,
only to the byte-identical request of an admitted device. No vendor connection.
"""
import hashlib
import json
import re
import time
from .web_protocol import decode_request, decode_settings_reply
class Observation:
@staticmethod
def diagnostic_lease(db, identifier, command_id, *, bind_imei=None):
"""One fixed diagnostic command per explicitly armed evidence window.
Expiry bounds our dispatch/capture, not the device's service mode.
No repeated toggle, arbitrary payload, or automatic device restart.
"""
if not db.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='observations'"
).fetchone():
raise ValueError("diagnostic observation unavailable")
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
if not row:
raise ValueError("diagnostic observation unavailable")
value = json.loads(row[0])
if value["expires_at"] <= time.time() or value.get("reference"):
raise ValueError("diagnostic observation unavailable")
bound = value.get("diagnostic_command_id")
if bound not in (None, command_id) or bind_imei is None and bound != command_id:
raise ValueError("diagnostic observation already used")
if bind_imei is not None:
value.update(diagnostic_command_id=command_id, diagnostic_imei=bind_imei)
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), identifier))
return value["expires_at"]
def __init__(self, store):
self.store = store
with store.db() as db:
db.execute("CREATE TABLE IF NOT EXISTS observations(id TEXT PRIMARY KEY, body TEXT)")
db.execute(
"CREATE TABLE IF NOT EXISTS observation_data(lease TEXT, sequence INTEGER, "
"raw BLOB, metadata TEXT, PRIMARY KEY(lease,sequence))"
)
def arm(self, body):
if set(body) not in ({"id"}, {"id", "reference"}) or not re.fullmatch(
r"[a-f0-9]{32}", body["id"]
):
raise ValueError("invalid observation")
reference = body.get("reference")
if "reference" in body:
if not isinstance(reference, dict) or set(reference) != {"request", "response"}:
raise ValueError("invalid reference")
request = bytes.fromhex(reference["request"])
response = bytes.fromhex(reference["response"])
imei, command, _ = decode_request(request, observe_empty_check=True)
if not self.store.admitted(imei):
raise ValueError("unqualified reference exchange")
if command == 6 and response == bytes.fromhex("5b00030006025d"):
pass
elif command == 1 and (
response == bytes.fromhex("5b000200015d")
or (
len(response) == 10
and response[:5] == bytes.fromhex("5b00060001")
and response[-1:] == b"]"
and int.from_bytes(response[5:9], "big") > 0
)
):
# The captured four-byte response equals the bench's numeric
# device ID. Qualify its exact replay once; no image payload.
pass
elif command == 2:
if response != bytes.fromhex("5b000200025d"):
decode_settings_reply(response)
# Bounded qualification of a zero-payload no-image response.
# Not admitted in the normal product channel until physically
# verified; no CRC image or device configuration is supplied.
elif command == 5 and response == bytes.fromhex("5b00030005015d"):
# Byte-exact command-5 reply captured from the manufacturer
# for the owner-approved return of its own configuration.
pass
else:
raise ValueError("unqualified reference exchange")
now = time.time()
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
if db.execute("SELECT 1 FROM observations WHERE id=?", (body["id"],)).fetchone():
previous = json.loads(
db.execute(
"SELECT body FROM observations WHERE id=?", (body["id"],)
).fetchone()[0]
)
if previous.get("reference") != reference:
raise ValueError("observation idempotency conflict")
return self.get(body["id"])
if any(
json.loads(r[0])["expires_at"] > now
for r in db.execute("SELECT body FROM observations")
):
raise ValueError("observation already armed")
if db.execute("SELECT COUNT(*) FROM observations").fetchone()[0] >= 64:
raise ValueError("observation evidence capacity reached")
value = {"id": body["id"], "created_at": now, "expires_at": now + 180}
if reference is not None:
value["reference"] = reference
db.execute("INSERT INTO observations VALUES(?,?)", (body["id"], json.dumps(value)))
return self.get(body["id"])
def get(self, identifier):
with self.store.db() as db:
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
if not row:
raise ValueError("unknown observation")
value = json.loads(row[0])
value.pop("reference", None)
value.pop("diagnostic_imei", None)
value["captures"] = [
json.loads(r[0])
for r in db.execute(
"SELECT metadata FROM observation_data WHERE lease=? ORDER BY sequence",
(identifier,),
)
]
return value
def close(self, identifier):
"""Disarm without deleting private evidence or retrying a dispatch."""
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT body FROM observations WHERE id=?", (identifier,)).fetchone()
if not row:
raise ValueError("unknown observation")
value = json.loads(row[0])
value["expires_at"] = min(value["expires_at"], time.time())
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), identifier))
return self.get(identifier)
def reply(self, ticket, raw):
"""Persist one dispatch before writing, including across service restarts."""
request = http_body(raw)
if request is None:
return None
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT body FROM observations WHERE id=?", (ticket[0],)).fetchone()
if not row:
return None
value = json.loads(row[0])
reference = value.get("reference")
if (
not reference
or value["expires_at"] <= time.time()
or value.get("reply_dispatched_at")
or request != bytes.fromhex(reference["request"])
or not self.store.admitted(str(int.from_bytes(request[4:12], "little")))
or not db.execute(
"SELECT 1 FROM observation_data WHERE lease=? AND sequence=?", ticket
).fetchone()
):
return None
response = bytes.fromhex(reference["response"])
value.update(
reply_dispatched_at=time.time(),
reply_monotonic=time.monotonic(),
reply_sha256=hashlib.sha256(response).hexdigest(),
reply_sequence=ticket[1],
)
db.execute("UPDATE observations SET body=? WHERE id=?", (json.dumps(value), ticket[0]))
return response
def claim(self):
with self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
for identifier, body in db.execute("SELECT id,body FROM observations"):
if json.loads(body)["expires_at"] <= time.time():
continue
sequence = db.execute(
"SELECT COUNT(*) FROM observation_data WHERE lease=?", (identifier,)
).fetchone()[0]
if sequence >= 4:
return None
metadata = {
"sequence": sequence,
"started_at": time.time(),
"monotonic": time.monotonic(),
"state": "receiving",
}
db.execute(
"INSERT INTO observation_data VALUES(?,?,?,?)",
(identifier, sequence, b"", json.dumps(metadata)),
)
return identifier, sequence
return None
def finish(self, ticket, raw, events):
if len(raw) > 16384:
raise ValueError("observation limit")
with self.store.db() as db:
row = db.execute(
"SELECT metadata FROM observation_data WHERE lease=? AND sequence=?", ticket
).fetchone()
if not row:
raise ValueError("unknown capture")
value = json.loads(row[0])
value.update(
state="captured",
completed_at=time.time(),
bytes=len(raw),
sha256=hashlib.sha256(raw).hexdigest(),
events=events,
)
db.execute(
"UPDATE observation_data SET raw=?,metadata=? WHERE lease=? AND sequence=?",
(raw, json.dumps(value), *ticket),
)
def http_body(raw):
"""First complete, bounded B2 POST only; reject ambiguous HTTP framing."""
header, separator, body = raw.partition(b"\r\n\r\n")
if not separator or len(header) > 2048:
return None
lines = header.split(b"\r\n")
if lines[0] != b"POST /c/index.php HTTP/1.1":
return None
headers = {}
for line in lines[1:]:
key, colon, value = line.partition(b":")
key = key.lower()
if not colon or key in headers:
return None
headers[key] = value.strip()
size = headers.get(b"content-length", b"")
if b"transfer-encoding" in headers or not size.isdigit():
return None
size = int(size)
if not 1 <= size <= 16384 or len(body) < size:
return None
return bytes(body[:size])
+492
View File
@@ -0,0 +1,492 @@
"""Durable tracker-maintenance intents; bounded attempts belong to Commands.
An outage ends an attempt, not its owning intent. No downstream output action
is admitted here. State changes reconcile the actual B2 image before retrying.
"""
import hashlib
import json
import re
import threading
import time
import uuid
from . import actions, full_configuration, sim_selection
KINDS = {"request-position", "restart", "read-configuration", "configure-all", "select-sim"}
PENDING = {"queued", "dispatched"}
RETRY = {"expired", "unconfirmed", "uncertain", "not_applied"}
FACTS = {
"transport",
"stage",
"dispatched_at",
"received_at",
"device_accepted_at",
"device_code",
"roundtrip_seconds",
"reconnected_at",
"reconnect_seconds",
"verified_at",
"configuration",
"configuration_sha256",
"configuration_received_at",
"write_reply_sent_at",
"active_sim",
"telemetry_measured_at",
"unchanged",
"sim_guard_verified",
}
class Operations:
def __init__(self, store, commands):
self.store, self.commands = store, commands
# Only local SQLite work under this lock; never sockets, sleeps or device I/O.
self.lock = threading.RLock()
with store.db() as db:
db.executescript("""
CREATE TABLE IF NOT EXISTS operations(
seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT UNIQUE NOT NULL,
imei TEXT NOT NULL,state TEXT NOT NULL,digest TEXT NOT NULL,body TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS operations_pending ON operations(imei,state,seq);
CREATE TABLE IF NOT EXISTS operation_attempts(
operation TEXT NOT NULL,number INTEGER NOT NULL,id TEXT UNIQUE NOT NULL,
body TEXT NOT NULL,PRIMARY KEY(operation,number));
CREATE TABLE IF NOT EXISTS operation_modem(
imei TEXT PRIMARY KEY,body TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS operation_stops(id TEXT PRIMARY KEY,kind TEXT NOT NULL);
""")
def save(self, value):
with self.store.db() as db:
encoded = json.dumps(value)
db.execute(
"UPDATE operations SET state=?,body=? WHERE id=? AND body<>?",
(value["state"], encoded, value["id"], encoded),
)
def submit(self, body):
body = dict(body)
if (
not re.fullmatch(r"[a-f0-9]{32}", body.get("id", ""))
or body.get("kind") not in KINDS
or not self.store.admitted(body.get("imei"))
):
raise ValueError("unsupported operation")
if body["kind"] in full_configuration.KINDS:
if not re.fullmatch(r"[0-9]{6}", body.get("password", "")):
raise ValueError("invalid password")
full_configuration.prepare(body)
else:
actions.prepare(body)
digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
with self.lock, self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
stopped = db.execute(
"SELECT kind FROM operation_stops WHERE id=?", (body["id"],)
).fetchone()
if stopped:
return {
"id": body["id"],
"kind": stopped[0],
"state": "stopped",
"durable": True,
"runtime_phase": "stopped",
"stop_requested": True,
"attempt_count": 0,
}
old = db.execute(
"SELECT digest,body FROM operations WHERE id=?", (body["id"],)
).fetchone()
if old:
if old[0] != digest:
raise ValueError("idempotency conflict")
return self.public(json.loads(old[1]))
count = db.execute(
"SELECT count(*) FROM operations WHERE imei=? AND state IN ('queued','dispatched')",
(body["imei"],),
).fetchone()[0]
if count >= 32:
raise ValueError("operation queue full")
value = {
"id": body["id"],
"imei": body["imei"],
"kind": body["kind"],
"request": body,
"created_at": time.time(),
"state": "queued",
"runtime_phase": "waiting-link",
"attempt_count": 0,
"next_attempt_at": 0,
"phase": "execute",
"result": {},
}
db.execute(
"INSERT INTO operations(id,imei,state,digest,body) VALUES(?,?,?,?,?)",
(body["id"], body["imei"], value["state"], digest, json.dumps(value)),
)
return self.public(value)
@staticmethod
def public(value):
result = {k: v for k, v in value.get("result", {}).items() if k in FACTS}
result.update(
{
k: value[k]
for k in (
"id",
"kind",
"state",
"created_at",
"attempt_count",
"runtime_phase",
"next_attempt_at",
"stop_requested",
"reason",
)
if k in value
}
)
result["durable"] = True
if value.get("attempt"):
result["attempt_id"] = value["attempt"]["id"]
result["attempt_expires_at"] = value["attempt"]["not_after"]
return result
def pending(self, imei):
with self.store.db() as db:
return (
db.execute(
"SELECT 1 FROM operations WHERE imei=? AND state IN "
"('queued','dispatched') LIMIT 1",
(imei,),
).fetchone()
is not None
)
def fresh(self, imei):
return any(
0 <= time.monotonic() - self.commands.session_activity.get((imei, s), 0) <= 30
for s in tuple(self.commands.sessions.get(imei, ()))
)
def wait_delay(self, imei):
with self.store.db() as db:
row = db.execute(
"SELECT body FROM operations WHERE imei=? AND state IN "
"('queued','dispatched') ORDER BY seq LIMIT 1",
(imei,),
).fetchone()
if not row:
return None
value = json.loads(row[0])
if value.get("attempt"):
return 1
return max(1, value["next_attempt_at"] - time.time()) if self.fresh(imei) else None
def get(self, identifier):
with self.store.db() as db:
row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()
if not row:
with self.store.db() as db:
stopped = db.execute(
"SELECT kind FROM operation_stops WHERE id=?", (identifier,)
).fetchone()
if stopped:
return {
"id": identifier,
"kind": stopped[0],
"state": "stopped",
"durable": True,
"runtime_phase": "stopped",
"stop_requested": True,
"attempt_count": 0,
}
raise ValueError("unknown operation")
self.advance(json.loads(row[0])["imei"])
with self.store.db() as db:
value = json.loads(
db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()[0]
)
result = self.public(value)
attempt = value.get("attempt", value.get("result", {})).get("id")
if attempt:
result["transport"] = self.commands.transport.read(db, attempt)
return result
def cancel(self, identifier, kind=None):
if not re.fullmatch(r"[a-f0-9]{32}", identifier):
raise ValueError("invalid operation identity")
with self.lock, self.store.db() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT body FROM operations WHERE id=?", (identifier,)).fetchone()
if not row:
if kind not in KINDS:
raise ValueError("unknown operation")
db.execute("INSERT OR IGNORE INTO operation_stops VALUES(?,?)", (identifier, kind))
return {
"id": identifier,
"kind": kind,
"state": "stopped",
"durable": True,
"runtime_phase": "stopped",
"stop_requested": True,
"attempt_count": 0,
}
value = json.loads(row[0])
if value["state"] in PENDING:
value["stop_requested"] = True
if not value.get("attempt"):
value.update(state="stopped", runtime_phase="stopped")
db.execute(
"UPDATE operations SET state=?,body=? WHERE id=?",
(value["state"], json.dumps(value), identifier),
)
return self.get(identifier)
def history(self, identifier, before=2**63 - 1):
with self.store.db() as db:
rows = db.execute(
"SELECT number,body FROM operation_attempts WHERE operation=? "
"AND number<? ORDER BY number DESC LIMIT 21",
(identifier, before),
).fetchall()
items = [json.loads(r[1]) for r in rows[:20]]
for item in items:
# Transport observations may be persisted just after the device
# reply already completed this attempt. Read their current facts.
item["transport"] = self.commands.transport.read(db, item["id"])
return {
"items": items,
"next_before": rows[19][0] if len(rows) > 20 else None,
}
def note_attempt(self, value, result):
item = {k: result[k] for k in FACTS - {"configuration"} if k in result}
item.update(
id=value["attempt"]["id"],
number=value["attempt_count"],
phase=value["phase"],
state=result["state"],
)
with self.store.db() as db:
old = db.execute(
"SELECT body FROM operation_attempts WHERE id=?", (item["id"],)
).fetchone()
if old:
previous = json.loads(old[0])
previous.pop("observed_at", None)
if previous == item:
return
item["observed_at"] = time.time()
db.execute(
"INSERT INTO operation_attempts VALUES(?,?,?,?) ON CONFLICT(operation,number) "
"DO UPDATE SET body=excluded.body",
(value["id"], value["attempt_count"], item["id"], json.dumps(item)),
)
def observe(self, imei, raw):
offset = 2
while offset < len(raw) - 1:
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
payload = raw[offset + 7 : offset + 7 + size]
if raw[offset] == 1 and 0 <= time.time() - measured <= 30:
for index in range(0, len(payload) - 4, 5):
if payload[index] != 99:
continue
ds2 = int.from_bytes(payload[index + 1 : index + 5], "little")
value = {
"active_sim": 1 + ((ds2 >> 5) & 1),
"gprs": (ds2 >> 2) & 7,
"measured_at": measured,
}
with self.store.db() as db:
db.execute(
"INSERT INTO operation_modem VALUES(?,?) ON CONFLICT(imei) "
"DO UPDATE SET body=excluded.body WHERE "
"json_extract(excluded.body, '$.measured_at') >= "
"json_extract(operation_modem.body, '$.measured_at')",
(imei, json.dumps(value)),
)
offset += size + 8
def selected(self, value):
if (
self.commands.sim_guard.check(
value["imei"], value["request"].get("sim_guard"), after=value["created_at"]
)
!= "matched"
):
return None
with self.store.db() as db:
row = db.execute(
"SELECT body FROM operation_modem WHERE imei=?", (value["imei"],)
).fetchone()
data = json.loads(row[0]) if row else {}
return (
data
if sim_selection.matches(value["request"], data.get("active_sim"))
and data.get("gprs") == 4
and data.get("measured_at", 0) > value["created_at"]
and 0 <= time.time() - data["measured_at"] <= 30
else None
)
def reconcile(self, value, result):
request = value["request"]
digest = result.get("configuration_sha256")
target = hashlib.sha256(bytes.fromhex(request["target_configuration"])).hexdigest()
if digest == target:
if value["kind"] == "configure-all":
value.update(state="verified", runtime_phase="complete", result=result)
elif selected := self.selected(value):
value.update(
state="sim_selected",
runtime_phase="complete",
result={
**result,
"active_sim": selected["active_sim"],
"telemetry_measured_at": selected["measured_at"],
"sim_guard_verified": bool(request.get("sim_guard")),
},
)
else:
value.update(phase="execute", retry_predecessor=target)
elif digest == request["expected_sha256"]:
value.update(phase="execute", retry_predecessor=digest)
else:
value.update(
state="rejected",
reason="configuration_conflict",
runtime_phase="complete",
result=result,
)
def advance(self, imei):
with self.lock:
with self.store.db() as db:
row = db.execute(
"SELECT body FROM operations WHERE imei=? AND state IN "
"('queued','dispatched') ORDER BY seq LIMIT 1",
(imei,),
).fetchone()
if not row:
return
value = json.loads(row[0])
if not self.store.admitted(imei):
value.update(state="rejected", reason="device_revoked", runtime_phase="complete")
self.save(value)
return
if value.get("attempt"):
# Idempotent submission covers a crash before/after attempt admission.
# Read first: the accepted attempt may have completed while Core was away.
try:
result = self.commands.get(value["attempt"]["id"])
except ValueError:
if value.get("stop_requested"):
value.pop("attempt", None)
value.update(state="stopped", runtime_phase="stopped")
self.save(value)
return
try:
result = self.commands.submit(value["attempt"])
except ValueError:
return # A legacy operation/session admission still owns the channel.
value["result"] = result
self.note_attempt(value, result)
if result["state"] in PENDING:
value.update(
state=result["state"],
runtime_phase="checking-result"
if value["phase"] == "inspect"
else "executing",
)
self.save(value)
return
if value["phase"] == "inspect" and result["state"] == "observed":
self.reconcile(value, result)
elif result["state"] in {
"device_confirmed",
"observed",
"verified",
"sim_selected",
"reconnected",
}:
value.update(state=result["state"], runtime_phase="complete")
elif (
value["kind"] == "restart"
and result.get("device_code") == 0
and result.get("device_accepted_at")
):
value.update(state="accepted", runtime_phase="complete")
elif (
result["state"] in RETRY
or result.get("device_code") == 7
or result.get("reason") == "configuration_predecessor_mismatch"
):
if value["kind"] in {"configure-all", "select-sim"}:
value["phase"] = "inspect"
else:
value.update(state=result["state"], runtime_phase="complete")
if result.get("reason") == "sim_card_changed":
value["reason"] = "sim_card_changed"
value.pop("attempt", None)
if value["state"] in PENDING:
value.update(
state="stopped" if value.get("stop_requested") else "queued",
runtime_phase="stopped" if value.get("stop_requested") else "retry-wait",
next_attempt_at=time.time()
+ min(300, 5 * 2 ** min(value["attempt_count"] - 1, 6)),
)
self.save(value)
return
if value.get("stop_requested"):
value.update(state="stopped", runtime_phase="stopped")
self.save(value)
return
if value["next_attempt_at"] > time.time():
return
if not self.fresh(imei):
if value["runtime_phase"] != "waiting-link":
value.update(runtime_phase="waiting-link")
self.save(value)
return
if value["phase"] == "execute" and value["request"].get("sim_guard"):
guard = self.commands.sim_guard.check(imei, value["request"]["sim_guard"])
if guard != "matched":
if guard == "changed":
value.update(
state="rejected", runtime_phase="complete", reason="sim_card_changed"
)
else:
value.update(runtime_phase="waiting-identity")
self.save(value)
return
attempt = {**value["request"], "id": uuid.uuid4().hex}
if value["phase"] == "inspect":
attempt = {
k: v
for k, v in attempt.items()
if k in {"id", "imei", "password", "model", "firmware"}
}
attempt["kind"] = "read-configuration"
elif value.get("retry_predecessor"):
attempt["expected_sha256"] = value["retry_predecessor"]
lifetime = (
360
if attempt["kind"] == "select-sim"
else 30
if attempt["kind"] == "request-position"
else 180
)
attempt["not_after"] = time.time() + lifetime
value.update(
attempt=attempt,
attempt_count=value["attempt_count"] + 1,
result={},
runtime_phase="checking-result" if value["phase"] == "inspect" else "executing",
)
# The plan is durable before the attempt's separate transaction.
self.save(value)
self.advance(imei)
+30
View File
@@ -0,0 +1,30 @@
"""Observe return after a restart request without claiming CPU/power-cycle proof."""
import time
def observe(value, raw, session, started):
if (
value.get("kind") != "restart"
or value["state"] != "dispatched"
or value["expires_at"] < time.time()
or session in value["restart_sessions"]
or started <= value["monotonic"]
):
return False
# Only type-1 telemetry measured after dispatch establishes fresh return.
# A new header, old archive, text reply or token ACK cannot complete this.
offset = 2
while offset < len(raw) - 1:
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
if raw[offset] == 1 and value["dispatched_at"] < measured <= time.time() + 5:
value.update(
state="reconnected",
reconnected_at=time.time(),
reconnect_seconds=time.monotonic() - value["monotonic"],
telemetry_measured_at=measured,
)
return True
offset += size + 8
return False
+402
View File
@@ -0,0 +1,402 @@
"""Bounded asyncio TCP receiver and pinned-TLS API; no shell/device control API."""
import asyncio
import json
import sqlite3
import ssl
import time
import uuid
from contextlib import suppress
from urllib.parse import parse_qs, urlsplit
from . import arnavi
from .commands import COMMAND_SESSION_MAX_IDLE, Commands
from .delivery import Delivery
from .observation import Observation, http_body
from .operations import Operations
class Service:
def __init__(self, store):
self.store = store
self.connections = 0
self.commands = Commands(store)
self.operations = Operations(store, self.commands)
self.observation = Observation(store)
self.wake = {}
async def tracker(self, reader, writer):
self.connections += 1
session = uuid.uuid4().hex
sender = None
delivery = None
imei = None
try:
if self.connections > 256:
return
async with asyncio.timeout(10):
header = await reader.readexactly(10)
if header[:2] != b"\xff\x23":
if (
not await self.observe_configuration(reader, header, writer)
and header == b"POST /c/in"
):
delivery = Delivery(writer)
await self.configuration_http(reader, writer, header, delivery)
return
imei = arnavi.identity(header)
if not await asyncio.to_thread(self.store.admitted, imei):
return
delivery = Delivery(writer)
self.commands.sessions.setdefault(imei, set()).add(session)
self.commands.session_started[imei, session] = time.monotonic()
self.commands.session_activity[imei, session] = time.monotonic()
self.commands.session_peers[imei, session] = writer.get_extra_info("peername")[0]
self.commands.session_ready[imei, session] = False
delivery.write(arnavi.header_ack(int(time.time())))
await writer.drain()
sender = asyncio.create_task(self.send_commands(imei, writer, session, delivery))
buffer = b""
while True:
async with asyncio.timeout(180):
chunk = await reader.read(min(4096, arnavi.MAX_PACKAGE - len(buffer)))
if not chunk:
return
buffer += chunk
while buffer:
parsed = arnavi.parse_package(buffer)
if parsed is None:
break
length, packets = parsed
self.commands.session_activity[imei, session] = time.monotonic()
await asyncio.to_thread(
self.accept_package, imei, buffer[:length], packets, session
)
self.notify(imei)
delivery.write(arnavi.package_ack(buffer[1]))
await writer.drain()
buffer = buffer[length:]
except (
ValueError,
KeyError,
OSError,
sqlite3.Error,
TimeoutError,
asyncio.IncompleteReadError,
asyncio.LimitOverrunError,
):
pass # Deliberately no raw identity/data/credentials in logs.
finally:
if imei:
self.commands.sessions.get(imei, set()).discard(session)
self.commands.session_started.pop((imei, session), None)
self.commands.session_activity.pop((imei, session), None)
self.commands.session_peers.pop((imei, session), None)
self.commands.session_ready.pop((imei, session), None)
if not self.commands.sessions.get(imei):
self.commands.sessions.pop(imei, None)
if sender:
sender.cancel()
await asyncio.gather(sender, return_exceptions=True)
self.connections -= 1
if delivery:
delivery.abort()
else:
writer.close()
def accept_package(self, imei, raw, packets, session):
# Core may fetch/ack packages concurrently. Publish the packet and its
# command evidence together before either Core or B2 can consume it.
with self.store.packet_transaction():
self.store.append(imei, raw, packets)
self.commands.receive(imei, raw, session)
self.operations.observe(imei, raw)
async def observe_configuration(self, reader, header, writer=None):
ticket = await asyncio.to_thread(self.observation.claim)
if ticket is None:
return False
raw = bytearray(header)
events = [
{"offset": 0, "bytes": len(header), "at": time.time(), "monotonic": time.monotonic()}
]
try:
async with asyncio.timeout(8):
while len(raw) < 16384:
chunk = await reader.read(min(4096, 16384 - len(raw)))
if not chunk:
break
events.append(
{
"offset": len(raw),
"bytes": len(chunk),
"at": time.time(),
"monotonic": time.monotonic(),
}
)
raw.extend(chunk)
if writer is not None:
reply = await asyncio.to_thread(self.observation.reply, ticket, bytes(raw))
if reply is not None:
writer.write(
b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n"
+ f"Content-Length: {len(reply)}\r\n".encode()
+ b"Connection: keep-alive\r\n\r\n"
+ reply
)
await writer.drain()
except (TimeoutError, OSError):
pass
finally:
await asyncio.to_thread(self.observation.finish, ticket, bytes(raw), events)
return True
async def configuration_http(self, reader, writer, initial, delivery):
if initial != b"POST /c/in":
return
peer = writer.get_extra_info("peername")[0]
for _ in range(8):
async with asyncio.timeout(12):
header = initial + await reader.readuntil(b"\r\n\r\n")
initial = b""
if len(header) > 2048:
return
lengths = [
line.split(b":", 1)[1].strip()
for line in header.split(b"\r\n")
if line.lower().startswith(b"content-length:")
]
if len(lengths) != 1 or not lengths[0].isdigit():
return
size = int(lengths[0])
if not 20 <= size <= 16384:
return
body = http_body(header + await reader.readexactly(size))
if body is None:
return
response = await asyncio.to_thread(
self.commands.web_receive, body, peer, with_deadline=True
)
self.notify(str(int.from_bytes(body[4:12], "little")))
if response is None:
return
reply, deadline = response
delivery.write(
b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n"
+ f"Content-Length: {len(reply)}\r\n".encode()
+ b"Connection: keep-alive\r\n\r\n"
+ reply,
deadline,
)
await writer.drain()
async def send_commands(self, imei, writer, session, delivery):
event = asyncio.Event()
observations = []
def observe(ticket, phase, at, elapsed, reason):
# The socket timer never opens SQLite or waits for filesystem I/O.
observations.append((ticket, phase, at, elapsed, reason))
event.set()
async def persist():
if observations:
batch = observations[:]
observations.clear()
commit = asyncio.create_task(
asyncio.to_thread(self.commands.transport.record, batch)
)
try:
await asyncio.shield(commit)
except asyncio.CancelledError:
# EOF cancels this sender. Finish the extracted batch before
# the finally block records closure of its remaining bytes.
await commit
raise
self.wake.setdefault(imei, set()).add(event)
try:
while not writer.is_closing():
event.clear()
await persist()
last_input = self.commands.session_activity.get((imei, session))
self.commands.session_ready[imei, session] = (
delivery.ready()
and last_input is not None
and 0 <= time.monotonic() - last_input <= COMMAND_SESSION_MAX_IDLE
)
await asyncio.to_thread(self.operations.advance, imei)
dispatch = await asyncio.to_thread(
self.commands.take_delivery, imei, session, with_receipt=True
)
if dispatch:
data, deadline, ticket = dispatch
delivery.write(
data,
deadline,
lambda phase, at, elapsed, reason, ticket=ticket: observe(
ticket, phase, at, elapsed, reason
),
)
await writer.drain()
await persist()
delay = await asyncio.to_thread(self.commands.wait_delay, imei)
operation_delay = await asyncio.to_thread(self.operations.wait_delay, imei)
delay = (
min(d for d in (delay, operation_delay) if d is not None)
if (delay is not None or operation_delay is not None)
else None
)
with suppress(TimeoutError):
await asyncio.wait_for(event.wait(), delay)
finally:
self.wake.get(imei, set()).discard(event)
if not self.wake.get(imei):
self.wake.pop(imei, None)
delivery.abort()
await persist()
def notify(self, imei):
for event in self.wake.get(imei, ()):
event.set()
async def api(self, reader, writer):
status, value = 400, {"error": "invalid_request"}
try:
async with asyncio.timeout(15):
header = await reader.readuntil(b"\r\n\r\n")
if len(header) > 8192:
raise ValueError
lines = header.decode("ascii").split("\r\n")
method, target, _ = lines[0].split(" ")
headers = dict(line.lower().split(": ", 1) for line in lines[1:] if line)
size = int(headers.get("content-length", "0"))
if not 0 <= size <= 1024 * 1024 or "transfer-encoding" in headers:
raise ValueError
payload = await reader.readexactly(size) if size else b"{}"
body = json.loads(payload)
route = urlsplit(target)
token = headers.get("authorization", "").removeprefix("bearer ")
# Header values must retain case for bearer credentials.
for line in lines[1:]:
if line.lower().startswith("authorization: bearer "):
token = line[len("authorization: bearer ") :]
if method == "GET" and route.path == "/health":
value = {"ok": True, "service": "ndc-mission-vps-host"}
elif method == "POST" and route.path == "/v1/pair":
value = await asyncio.to_thread(self.store.pair, body)
else:
if not await asyncio.to_thread(self.store.authorize, token):
raise PermissionError
if method == "GET" and route.path == "/v1/status":
value = await asyncio.to_thread(self.store.status)
elif method == "PUT" and route.path == "/v1/devices":
await asyncio.to_thread(self.store.set_devices, body["items"])
value = {"ok": True}
elif method == "GET" and route.path == "/v1/packets":
after = int(parse_qs(route.query).get("after", ["0"])[0])
value = await asyncio.to_thread(self.store.fetch, max(0, after))
elif method == "POST" and route.path == "/v1/commands":
if await asyncio.to_thread(self.operations.pending, body["imei"]):
raise ValueError("durable operation owns device queue")
value = await asyncio.to_thread(self.commands.submit, body)
self.notify(body["imei"])
elif method == "POST" and route.path == "/v1/operations":
value = await asyncio.to_thread(self.operations.submit, body)
self.notify(body["imei"])
elif (
method == "POST"
and route.path.startswith("/v1/operations/")
and route.path.endswith("/cancel")
):
value = await asyncio.to_thread(
self.operations.cancel, route.path.split("/")[-2], body.get("kind")
)
elif (
method == "GET"
and route.path.startswith("/v1/operations/")
and route.path.endswith("/attempts")
):
before = int(parse_qs(route.query).get("before", [str(2**63 - 1)])[0])
value = await asyncio.to_thread(
self.operations.history, route.path.split("/")[-2], before
)
elif method == "GET" and route.path.startswith("/v1/operations/"):
value = await asyncio.to_thread(
self.operations.get, route.path.rsplit("/", 1)[1]
)
elif method == "POST" and route.path == "/v1/configuration-observations":
value = await asyncio.to_thread(self.observation.arm, body)
elif (
method == "POST"
and route.path.startswith("/v1/configuration-observations/")
and route.path.endswith("/close")
):
value = await asyncio.to_thread(
self.observation.close, route.path.split("/")[-2]
)
elif method == "GET" and route.path.startswith(
"/v1/configuration-observations/"
):
value = await asyncio.to_thread(
self.observation.get, route.path.rsplit("/", 1)[1]
)
elif method == "GET" and route.path.startswith("/v1/commands/"):
value = await asyncio.to_thread(
self.commands.get, route.path.rsplit("/", 1)[1]
)
elif method == "POST" and route.path == "/v1/ack":
if type(body["through"]) is not int or body["through"] < 0:
raise ValueError
await asyncio.to_thread(self.store.acknowledge, body["through"])
value = {"ok": True}
else:
raise ValueError
status = 200
except PermissionError:
status, value = 403, {"error": "not_authorized"}
except (
ValueError,
KeyError,
TypeError,
UnicodeError,
asyncio.IncompleteReadError,
asyncio.LimitOverrunError,
TimeoutError,
):
pass
except (OSError, sqlite3.Error):
status, value = 503, {"error": "storage_unavailable"}
try:
payload = json.dumps(value).encode()
writer.write(
(
f"HTTP/1.1 {status} Result\r\nContent-Type: application/json\r\n"
f"Content-Length: {len(payload)}\r\nConnection: close\r\n"
"Cache-Control: no-store\r\n\r\n"
).encode()
+ payload
)
await writer.drain()
except OSError:
pass
finally:
writer.close()
async def run(self):
tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
tls.minimum_version = ssl.TLSVersion.TLSv1_3
tls.load_cert_chain(self.store.root / "tls.crt", self.store.root / "tls.key")
api = await asyncio.start_server(
self.api,
"0.0.0.0",
self.store.config["api_port"],
ssl=tls,
ssl_handshake_timeout=8,
limit=8192,
)
tracker = await asyncio.start_server(
self.tracker, "0.0.0.0", self.store.config["tracker"]["port"]
)
async with api, tracker:
await asyncio.gather(api.serve_forever(), tracker.serve_forever())
+83
View File
@@ -0,0 +1,83 @@
"""Durable firmware SID bindings, checked at the last configuration write boundary."""
import json
import re
import time
from .sim_network import binding, decode_pairs, merge
def prepare(value):
if (
not isinstance(value, dict)
or set(value) != {"slot", "sid"}
or type(value["slot"]) is not int
or value["slot"] not in (1, 2)
or not isinstance(value["sid"], str)
or not re.fullmatch(r"89[0-9]{18}", value["sid"])
):
raise ValueError("invalid SIM identity guard")
return dict(value)
class SimGuard:
def __init__(self, store):
self.store = store
with store.db() as db:
db.execute(
"CREATE TABLE IF NOT EXISTS sim_bindings(imei TEXT PRIMARY KEY,body TEXT NOT NULL)"
)
def observe(self, imei, raw):
# Called only for validated INTERNAL frames in the packet commit transaction.
with self.store.db(write=True) as db:
old = db.execute("SELECT body FROM sim_bindings WHERE imei=?", (imei,)).fetchone()
value = json.loads(old[0]) if old else None
offset, now = 2, time.time()
while offset < len(raw) - 1:
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
payload = raw[offset + 7 : offset + 7 + size]
if raw[offset] == 1:
tags = {}
for i in range(0, len(payload) - 4, 5):
tags.setdefault(payload[i], set()).add(payload[i + 1 : i + 5])
status = {}
if len(tags.get(99, ())) == 1:
ds = int.from_bytes(next(iter(tags[99])), "little")
status = {"sim_states": {"1": (ds >> 6) & 7, "2": (ds >> 9) & 7}}
value = merge(
value,
{
"measured_at": measured,
"cellular": {"status": status},
"sim_identifiers": decode_pairs(tags),
},
host_id="local",
sequence=0,
received=now,
tracker=imei,
)
offset += size + 8
if value:
db.execute(
"INSERT OR REPLACE INTO sim_bindings VALUES(?,?)", (imei, json.dumps(value))
)
def check(self, imei, guard, *, after=None, db=None):
if guard is None:
return "matched"
if db is None:
with self.store.db() as connection:
return self.check(imei, guard, after=after, db=connection)
row = db.execute("SELECT body FROM sim_bindings WHERE imei=?", (imei,)).fetchone()
value = json.loads(row[0]) if row else None
sid = binding(value, str(guard["slot"]), now=time.time())
if sid is None:
return "waiting"
if sid != guard["sid"]:
return "changed"
observed = value["slots"][str(guard["slot"])]["observation"]
if after is not None and observed["measured_at"] <= after:
return "waiting"
return "matched"
+55
View File
@@ -0,0 +1,55 @@
"""SIM permissions: verified flags, one restart, fresh modem evidence."""
import time
from . import actions
def matches(value, slot):
return (
type(slot) is int
and slot in (1, 2)
and (value.get("sim_policy") == "both" or slot == value.get("sim_slot"))
)
def queue_restart(value):
value.update(actions.prepare({"kind": "restart", "model": 231, "firmware": "0.01"}))
value.update(stage="restart", state="queued", not_before=time.time())
value.pop("session", None)
def observe(value, raw, session, started):
if (
value.get("kind") != "select-sim"
or value.get("stage") != "restart"
or value["state"] != "dispatched"
or value["expires_at"] <= time.time()
or session in value["restart_sessions"]
or started <= value["monotonic"]
):
return False
# Validated INTERNAL packages only. ACKs, archives, old sockets, old and
# future measurements, and GPRS on the wrong SIM cannot confirm selection.
offset = 2
while offset < len(raw) - 1:
size = int.from_bytes(raw[offset + 1 : offset + 3], "little")
measured = int.from_bytes(raw[offset + 3 : offset + 7], "little")
payload = raw[offset + 7 : offset + 7 + size]
if raw[offset] == 1 and value["dispatched_at"] < measured <= time.time() + 5:
for index in range(0, len(payload) - 4, 5):
if payload[index] != 99:
continue
ds2 = int.from_bytes(payload[index + 1 : index + 5], "little")
slot = 1 + ((ds2 >> 5) & 1)
if matches(value, slot) and (ds2 >> 2) & 7 == 4:
value.update(
state="sim_selected",
active_sim=slot,
verified_at=time.time(),
telemetry_measured_at=measured,
reconnect_seconds=time.monotonic() - value["monotonic"],
)
return True
offset += size + 8
return False
+262
View File
@@ -0,0 +1,262 @@
"""Durable receiver journal. Acknowledgements follow SQLite FULL commits."""
import base64
import hashlib
import hmac
import json
import os
import secrets
import sqlite3
import threading
import time
from contextlib import contextmanager
from pathlib import Path
def private_write(path, data):
temporary = path.with_name(path.name + ".new")
with open(temporary, "wb") as stream:
os.chmod(temporary, 0o600)
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
fd = os.open(path.parent, os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
class Store:
def __init__(self, root):
self.root = Path(root)
self.config = json.loads((self.root / "host.json").read_text())
self.path = self.root / "journal.sqlite3"
self._packet = threading.local()
with self.db() as db:
db.executescript("""
CREATE TABLE IF NOT EXISTS state(key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS devices(imei TEXT PRIMARY KEY, instance TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS device_ids(
imei TEXT PRIMARY KEY, number INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS packages(id INTEGER PRIMARY KEY AUTOINCREMENT,
imei TEXT NOT NULL, instance TEXT NOT NULL, digest TEXT UNIQUE NOT NULL,
received REAL NOT NULL, raw BLOB NOT NULL, packets TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS receipts(digest TEXT PRIMARY KEY, at REAL NOT NULL);
""")
self.path.chmod(0o600)
@contextmanager
def db(self, *, write=False):
# Packet consumers run together on one worker thread. No partial
# receipt or modem state may become visible to Core or the sender.
current = getattr(self._packet, "connection", None)
if current is not None:
yield current
return
connection = sqlite3.connect(self.path, timeout=10)
try:
connection.execute("PRAGMA synchronous=FULL")
with connection:
if write:
connection.execute("BEGIN IMMEDIATE")
yield connection
finally:
connection.close()
@contextmanager
def packet_transaction(self):
"""Synchronous packet ingestion only: no sockets, awaits or API work."""
if getattr(self._packet, "connection", None) is not None:
raise RuntimeError("nested packet transaction")
with self.db(write=True) as connection:
self._packet.connection = connection
try:
yield
finally:
del self._packet.connection
def invitation(self):
secret = secrets.token_urlsafe(32)
expires = int(time.time()) + 86400
with self.db() as db:
if db.execute("SELECT 1 FROM state WHERE key='owner'").fetchone():
raise ValueError("host already paired; restore its Core identity instead")
db.execute(
"INSERT OR REPLACE INTO state VALUES('invitation',?)",
(
json.dumps(
{"hash": hashlib.sha256(secret.encode()).hexdigest(), "expires_at": expires}
),
),
)
code = {
"schema": "missioncore.vps-pairing/v1",
"host_id": self.config["host_id"],
"endpoint": self.config["endpoint"],
"fingerprint": self.config["fingerprint"],
"secret": secret,
"expires_at": expires,
}
encoded = "MCV1." + base64.urlsafe_b64encode(json.dumps(code).encode()).decode().rstrip("=")
private_write(self.root / "connect.key", (encoded + "\n").encode())
def pair(self, body):
core, token, secret = body["core_id"], body["token"], body["secret"]
if not all(isinstance(v, str) and 32 <= len(v) <= 100 for v in (core, token, secret)):
raise ValueError("invalid pairing")
digest = hashlib.sha256(token.encode()).hexdigest()
with self.db() as db:
db.execute("BEGIN IMMEDIATE")
current = db.execute("SELECT value FROM state WHERE key='owner'").fetchone()
if current:
owner = json.loads(current[0])
if owner["core_id"] != core or not hmac.compare_digest(owner["token"], digest):
raise PermissionError("already paired")
else:
row = db.execute("SELECT value FROM state WHERE key='invitation'").fetchone()
invite = json.loads(row[0]) if row else {}
if invite.get("expires_at", 0) <= time.time() or not hmac.compare_digest(
invite.get("hash", ""), hashlib.sha256(secret.encode()).hexdigest()
):
raise PermissionError("invalid invitation")
db.execute(
"INSERT INTO state VALUES('owner',?)",
(json.dumps({"core_id": core, "token": digest}),),
)
db.execute("DELETE FROM state WHERE key='invitation'")
private_write(
self.root / "connect.key", b"PAIRED: key consumed; use the connected Mission Core.\n"
)
return self.status()
def authorize(self, token):
with self.db() as db:
row = db.execute("SELECT value FROM state WHERE key='owner'").fetchone()
return bool(
row
and hmac.compare_digest(
json.loads(row[0])["token"], hashlib.sha256(token.encode()).hexdigest()
)
)
def status(self):
from . import VERSION
with self.db() as db:
count, latest = db.execute("SELECT COUNT(*),MAX(received) FROM packages").fetchone()
devices = db.execute("SELECT COUNT(*) FROM devices").fetchone()[0]
return {
"schema": "missioncore.vps-host/v1",
"host_id": self.config["host_id"],
"version": VERSION,
"tracker": self.config["tracker"],
"pending_packages": count,
"last_packet_at": latest,
"devices": devices,
"capabilities": [
"arnavi-b2-internal",
"arnavi-b2-durable-operations-v1",
"arnavi-b2-sim-guard-v1",
],
}
def set_devices(self, items):
if not isinstance(items, list) or len(items) > 10000:
raise ValueError("invalid devices")
rows, identities = [], []
for item in items:
imei, instance = item["imei"], item["instance_id"]
if (
not isinstance(imei, str)
or not imei.isascii()
or not imei.isdigit()
or len(imei) != 15
):
raise ValueError("invalid identity")
if not isinstance(instance, str) or len(instance) != 32:
raise ValueError("invalid instance")
rows.append((imei, instance))
if "device_id" in item:
number = item["device_id"]
if type(number) is not int or not 1 <= number <= 0xFFFFFFFF:
raise ValueError("invalid numeric device identity")
identities.append((imei, number))
if len({r[0] for r in rows}) != len(rows):
raise ValueError("duplicate identity")
with self.db() as db:
db.execute("BEGIN IMMEDIATE")
for imei, number in identities:
previous = db.execute(
"SELECT number FROM device_ids WHERE imei=?", (imei,)
).fetchone()
if previous and previous[0] != number:
raise ValueError("numeric device identity conflict")
db.execute("INSERT OR IGNORE INTO device_ids VALUES(?,?)", (imei, number))
db.execute("DELETE FROM devices")
db.executemany("INSERT INTO devices VALUES(?,?)", rows)
def numeric_id(self, imei):
with self.db() as db:
row = db.execute(
"SELECT number FROM device_ids JOIN devices USING(imei) WHERE imei=?", (imei,)
).fetchone()
return row[0] if row else None
def admitted(self, imei):
with self.db() as db:
row = db.execute("SELECT instance FROM devices WHERE imei=?", (imei,)).fetchone()
return row[0] if row else None
def append(self, imei, raw, packets):
# Reserve disk for system services. Refuse ACK when durable storage cannot accept data.
if os.statvfs(self.root).f_bavail * os.statvfs(self.root).f_frsize < 256 * 1024**2:
raise OSError("journal storage reserve")
digest = hashlib.sha256(imei.encode() + raw).hexdigest()
with self.db(write=True) as db:
device = db.execute("SELECT instance FROM devices WHERE imei=?", (imei,)).fetchone()
if not device:
raise PermissionError("device not admitted")
if db.execute("SELECT 1 FROM receipts WHERE digest=?", (digest,)).fetchone():
return
# Fixed 512 MiB journal budget; backpressure, never drop unacknowledged data.
pages = db.execute("PRAGMA page_count").fetchone()[0]
free = db.execute("PRAGMA freelist_count").fetchone()[0]
page_size = db.execute("PRAGMA page_size").fetchone()[0]
if (pages - free) * page_size > 512 * 1024**2:
raise OSError("journal full")
db.execute(
"INSERT OR IGNORE INTO packages(imei,instance,digest,received,raw,packets) "
"VALUES(?,?,?,?,?,?)",
(imei, device[0], digest, time.time(), raw, json.dumps(packets)),
)
def fetch(self, after):
with self.db() as db:
rows = db.execute(
"SELECT id,instance,digest,received,raw,packets FROM packages "
"WHERE id>? ORDER BY id LIMIT 20",
(after,),
).fetchall()
return {
"items": [
{
"id": r[0],
"instance_id": r[1],
"digest": r[2],
"received_at": r[3],
"raw": base64.b64encode(r[4]).decode(),
}
for r in rows
]
}
def acknowledge(self, through):
with self.db() as db:
db.execute(
"INSERT OR IGNORE INTO receipts SELECT digest,received FROM packages WHERE id<=?",
(through,),
)
db.execute("DELETE FROM packages WHERE id<=?", (through,))
db.execute("DELETE FROM receipts WHERE at<?", (time.time() - 7 * 86400,))
@@ -0,0 +1,71 @@
"""Private-free transport observations, independent of device execution state."""
import json
import time
import uuid
class TransportEvidence:
def __init__(self, store):
self.store = store
with store.db(write=True) as db:
db.execute(
"CREATE TABLE IF NOT EXISTS command_transport("
"seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT UNIQUE NOT NULL,"
"command TEXT NOT NULL,state TEXT NOT NULL,body TEXT NOT NULL)"
)
db.execute(
"CREATE INDEX IF NOT EXISTS transport_command ON command_transport(command,seq)"
)
db.execute("CREATE INDEX IF NOT EXISTS transport_pending ON command_transport(state)")
# A process crash cannot tell us whether buffered bytes reached B2.
# It must never synthesize a TCP ACK or alter command retry policy.
for identifier, body in db.execute(
"SELECT id,body FROM command_transport WHERE state IN ('prepared','written')"
).fetchall():
value = json.loads(body)
value.update(state="unconfirmed", reason="host_restarted", closed_at=time.time())
db.execute(
"UPDATE command_transport SET state=?,body=? WHERE id=?",
(value["state"], json.dumps(value), identifier),
)
@staticmethod
def prepare(db, command, stage):
value = dict(id=uuid.uuid4().hex, stage=stage, state="prepared", prepared_at=time.time())
db.execute(
"INSERT INTO command_transport(id,command,state,body) VALUES(?,?,?,?)",
(value["id"], command, value["state"], json.dumps(value)),
)
return value["id"]
def record(self, events):
with self.store.db(write=True) as db:
for identifier, phase, at, elapsed, reason in events:
row = db.execute(
"SELECT body FROM command_transport WHERE id=?", (identifier,)
).fetchone()
if not row or phase not in {"written", "tcp_acknowledged", "unconfirmed"}:
continue
value = json.loads(row[0])
if value["state"] in {"tcp_acknowledged", "unconfirmed"}:
continue
if phase == "written":
value.setdefault("written_at", at)
elif phase == "tcp_acknowledged":
value.update(tcp_acknowledged_at=at, tcp_ack_seconds=elapsed)
else:
value.update(closed_at=at, reason=reason)
value["state"] = phase
db.execute(
"UPDATE command_transport SET state=?,body=? WHERE id=?",
(phase, json.dumps(value), identifier),
)
@staticmethod
def read(db, command):
rows = db.execute(
"SELECT body FROM command_transport WHERE command=? ORDER BY seq DESC LIMIT 32",
(command,),
).fetchall()
return [json.loads(row[0]) for row in reversed(rows)]