diff --git a/kurgan/hw/__init__.py b/kurgan/hw/__init__.py new file mode 100644 index 0000000..7806227 --- /dev/null +++ b/kurgan/hw/__init__.py @@ -0,0 +1,13 @@ +"""The hardware service: the only part of The Kurgan that runs with admin rights. + +`kurgan.hw` is a Windows service (LocalSystem, started at boot) that owns the hardware the +unelevated app must not touch: + + fan control Commander PRO case fans and motherboard top fans, profiles and fail-safes, + with its own CPU (PawnIO MSR) and GPU (NVML) temperature readings + RAM lighting the Dominator DDR5 sticks over the SMBus (PawnIO) + +The app (web UI, proxy, AI servers, telemetry, LCD, the other lighting, tray) talks to it over +the named pipe \\\\.\\pipe\\kurgan-hw (protocol.py). The service never depends on the app: with +no client connected it keeps controlling the fans. +""" diff --git a/kurgan/hw/protocol.py b/kurgan/hw/protocol.py new file mode 100644 index 0000000..acbe861 --- /dev/null +++ b/kurgan/hw/protocol.py @@ -0,0 +1,315 @@ +"""The hardware service's pipe protocol: newline-delimited JSON between the app and kurgan.hw. + + request {"op": "state", "args": {}, "id": 7} + reply {"id": 7, "ok": true, "result": {...}} + {"id": 7, "ok": false, "error": {"code": "invalid", "message": "..."}} + +Operations and their arguments: + + hello {"protocol": 1, "client": "..."} the first request on every connection + state {} the service's latest snapshot + set_profile {"profile": "quiet"|"balanced"|"performance"|"full"} + set_ram_lighting {"mode": "off"|"temperature"|"chase"} + ram_chase {"phase": n, "rate": n, "power": n|null} + the app's chase clock, about once a second while the RAM chases, so the + RAM stays in step with the case fan and GPU chases + +Each message is one line of UTF-8 JSON, at most MAX_MESSAGE bytes. Rejected: unknown +operations, unknown, missing or mistyped fields, NaN and Infinity, duplicate keys, and any +request before a successful hello. A protocol version mismatch is answered and the connection +closed. A line over MAX_MESSAGE closes the connection, since the stream can't be trusted after it. +""" + +from __future__ import annotations + +import json +import logging +import math +from dataclasses import dataclass, field +from typing import Callable + +from kurgan.cooling.profiles import PROFILES +from kurgan.settings import LIGHTING_MODES + +log = logging.getLogger(__name__) + +PIPE_NAME = r"\\.\pipe\kurgan-hw" +PROTOCOL_VERSION = 1 +MAX_MESSAGE = 64 * 1024 +READ_TIMEOUT = 30.0 # seconds a connection may stay silent (or mid-line) before the service drops it + +# Error codes +BAD_REQUEST = "bad_request" # not a well-formed request +UNKNOWN_OP = "unknown_op" +INVALID = "invalid" # well-formed, but the arguments are wrong +HELLO_FIRST = "hello_first" +VERSION = "version" +TOO_LARGE = "too_large" +UNAVAILABLE = "unavailable" # the service can't do that right now +INTERNAL = "internal" + +_MAX_ID = 2 ** 53 +_MAX_TEXT = 64 + + +class ProtocolError(Exception): + def __init__(self, code: str, message: str, request_id: int | str | None = None): + super().__init__(message) + self.code = code + self.request_id = request_id + + +class RemoteError(Exception): + """The service answered with an error.""" + + def __init__(self, code: str, message: str): + super().__init__(message) + self.code = code + + +class Unavailable(OSError): + """Raised by the service's operations when they can't run now (answered as UNAVAILABLE).""" + + +# ----------------------------------------------------------------------------- argument checks + +def _integer(low: int, high: int): + def check(name: str, value) -> int: + if type(value) is not int or not low <= value <= high: + raise ValueError(f"{name} must be a whole number from {low} to {high}") + return value + return check + + +def _number(low: float, high: float, nullable: bool = False): + def check(name: str, value) -> float | None: + if value is None and nullable: + return None + if type(value) not in (int, float) or not math.isfinite(value) or not low <= value <= high: + raise ValueError(f"{name} must be a number from {low:g} to {high:g}" + (" or null" if nullable else "")) + return float(value) + return check + + +def _text(max_length: int = _MAX_TEXT): + def check(name: str, value) -> str: + if not isinstance(value, str) or len(value) > max_length: + raise ValueError(f"{name} must be a string of at most {max_length} characters") + return value + return check + + +def _choice(choices): + choices = tuple(choices) + + def check(name: str, value) -> str: + if value not in choices or not isinstance(value, str): + raise ValueError(f"{name} must be one of {', '.join(choices)}") + return value + return check + + +# op -> {field: (check, required)} +OPERATIONS: dict[str, dict[str, tuple[Callable, bool]]] = { + "hello": {"protocol": (_integer(0, 1_000_000), True), "client": (_text(), False)}, + "state": {}, + "set_profile": {"profile": (_choice(PROFILES), True)}, + "set_ram_lighting": {"mode": (_choice(LIGHTING_MODES["memory"]), True)}, + "ram_chase": {"phase": (_number(-1e12, 1e12), True), "rate": (_number(0, 1000), True), + "power": (_number(0, 100_000, nullable=True), True)}, +} + + +def check_args(op: str, args: object) -> dict: + """The arguments, normalised, or ValueError.""" + if not isinstance(args, dict): + raise ValueError("args must be an object") + schema = OPERATIONS[op] + unknown = set(args) - set(schema) + if unknown: + raise ValueError(f"{op}: unknown field(s): {', '.join(sorted(map(str, unknown)))}") + out = {} + for name, (check, required) in schema.items(): + if name in args: + out[name] = check(name, args[name]) + elif required: + raise ValueError(f"{op}: {name} is required") + return out + + +# ----------------------------------------------------------------------------- encoding + +def _no_duplicates(pairs): + out = {} + for key, value in pairs: + if key in out: + raise ValueError(f"duplicate key {key!r}") + out[key] = value + return out + + +def _reject_constant(name: str): + raise ValueError(f"{name} is not valid JSON") + + +def _loads(line: bytes): + if len(line) > MAX_MESSAGE: + raise ProtocolError(TOO_LARGE, f"message over {MAX_MESSAGE} bytes") + try: + return json.loads(line.decode("utf-8"), object_pairs_hook=_no_duplicates, parse_constant=_reject_constant) + except (UnicodeDecodeError, ValueError, RecursionError) as e: + raise ProtocolError(BAD_REQUEST, f"not valid JSON: {e}") from None + + +def encode(message: dict) -> bytes: + """One line of JSON, newline included. ValueError if it can't be sent.""" + data = json.dumps(message, separators=(",", ":"), allow_nan=False).encode("utf-8") + if len(data) > MAX_MESSAGE: + raise ValueError(f"message over {MAX_MESSAGE} bytes") + return data + b"\n" + + +@dataclass +class Request: + op: str + args: dict = field(default_factory=dict) + id: int | str = 0 + + +def _check_id(value) -> int | str: + if type(value) is int and -_MAX_ID < value < _MAX_ID: + return value + if isinstance(value, str) and len(value) <= _MAX_TEXT: + return value + raise ValueError("id must be an integer or a short string") + + +def decode_request(line: bytes) -> Request: + data = _loads(line) + if not isinstance(data, dict): + raise ProtocolError(BAD_REQUEST, "a request must be a JSON object") + request_id = None + if "id" in data: + try: + request_id = _check_id(data["id"]) + except ValueError as e: + raise ProtocolError(BAD_REQUEST, str(e)) from None + unknown = set(data) - {"op", "args", "id"} + if unknown: + raise ProtocolError(BAD_REQUEST, f"unknown field(s): {', '.join(sorted(unknown))}", request_id) + if request_id is None: + raise ProtocolError(BAD_REQUEST, "id is required") + op = data.get("op") + if not isinstance(op, str): + raise ProtocolError(BAD_REQUEST, "op is required", request_id) + if op not in OPERATIONS: + raise ProtocolError(UNKNOWN_OP, f"unknown operation {op[:_MAX_TEXT]!r}", request_id) + try: + args = check_args(op, data.get("args", {})) + except ValueError as e: + raise ProtocolError(INVALID, str(e), request_id) from None + return Request(op, args, request_id) + + +def encode_request(op: str, args: dict | None, request_id: int | str) -> bytes: + """Checked like the service checks it, so a bad call fails here, before anything is sent.""" + if op not in OPERATIONS: + raise ValueError(f"unknown operation {op!r}") + return encode({"op": op, "args": check_args(op, args or {}), "id": _check_id(request_id)}) + + +def encode_reply(request_id, result) -> bytes: + return encode({"id": request_id, "ok": True, "result": result}) + + +def encode_error(request_id, code: str, message: str) -> bytes: + return encode({"id": request_id, "ok": False, "error": {"code": code, "message": message[:1000]}}) + + +def decode_reply(line: bytes, request_id: int | str): + """The result of the reply to `request_id`; RemoteError for an error reply, ProtocolError + (BAD_REQUEST) for anything that isn't a well-formed reply to that request.""" + data = _loads(line) + if not isinstance(data, dict) or data.get("id") != request_id or type(data.get("ok")) is not bool: + raise ProtocolError(BAD_REQUEST, "not a reply to this request") + if data["ok"]: + if set(data) != {"id", "ok", "result"}: + raise ProtocolError(BAD_REQUEST, "malformed reply") + return data["result"] + error = data.get("error") + if (set(data) != {"id", "ok", "error"} or not isinstance(error, dict) or set(error) != {"code", "message"} + or not all(isinstance(v, str) for v in error.values())): + raise ProtocolError(BAD_REQUEST, "malformed error reply") + raise RemoteError(error["code"], error["message"]) + + +# ----------------------------------------------------------------------------- framing and sessions + +class LineBuffer: + """Splits a byte stream into lines; ProtocolError(TOO_LARGE) once a line can't fit.""" + + def __init__(self, limit: int = MAX_MESSAGE): + self.limit = limit + self._pending = bytearray() + + def feed(self, data: bytes) -> list[bytes]: + self._pending += data + lines = [] + while True: + end = self._pending.find(b"\n") + if end < 0: + break + line = bytes(self._pending[:end]) + del self._pending[:end + 1] + if len(line) > self.limit: + raise ProtocolError(TOO_LARGE, f"message over {self.limit} bytes") + lines.append(line[:-1] if line.endswith(b"\r") else line) + if len(self._pending) > self.limit: + raise ProtocolError(TOO_LARGE, f"message over {self.limit} bytes") + return lines + + @property + def partial(self) -> bool: + return bool(self._pending) + + +class Session: + """One connection's side of the protocol, in the service. + + dispatch(op, args) runs an operation: ValueError is answered as INVALID, Unavailable as + UNAVAILABLE, anything else as INTERNAL (and logged).""" + + def __init__(self, dispatch: Callable[[str, dict], object], service_version: str): + self._dispatch = dispatch + self._version = service_version + self.greeted = False + + def handle(self, line: bytes) -> tuple[bytes, bool]: + """(reply, close the connection after sending it).""" + try: + request = decode_request(line) + except ProtocolError as e: + return encode_error(e.request_id, e.code, str(e)), e.code == TOO_LARGE + if request.op == "hello": + theirs = request.args["protocol"] + if theirs != PROTOCOL_VERSION: + return encode_error(request.id, VERSION, f"the service speaks protocol {PROTOCOL_VERSION}, " + f"the client {theirs}"), True + self.greeted = True + return encode_reply(request.id, {"protocol": PROTOCOL_VERSION, "service": self._version}), False + if not self.greeted: + return encode_error(request.id, HELLO_FIRST, "send hello first"), False + try: + result = self._dispatch(request.op, request.args) + except Unavailable as e: + return encode_error(request.id, UNAVAILABLE, str(e)), False + except ValueError as e: + return encode_error(request.id, INVALID, str(e)), False + except Exception: + log.exception("%s failed", request.op) + return encode_error(request.id, INTERNAL, f"{request.op} failed; see the service log"), False + try: + return encode_reply(request.id, result), False + except (TypeError, ValueError): + log.exception("%s: the reply can't be encoded", request.op) + return encode_error(request.id, INTERNAL, f"{request.op}: the reply can't be sent; see the service log"), False diff --git a/tests/test_hw_protocol.py b/tests/test_hw_protocol.py new file mode 100644 index 0000000..e0ccbb2 --- /dev/null +++ b/tests/test_hw_protocol.py @@ -0,0 +1,189 @@ +import json +import unittest + +from kurgan.hw import protocol +from kurgan.hw.protocol import ( + BAD_REQUEST, HELLO_FIRST, INTERNAL, INVALID, MAX_MESSAGE, PROTOCOL_VERSION, TOO_LARGE, UNAVAILABLE, + UNKNOWN_OP, VERSION, LineBuffer, ProtocolError, RemoteError, Session, Unavailable, + decode_reply, decode_request, encode_request, +) + + +def line(obj) -> bytes: + return json.dumps(obj).encode() + + +class DecodeRequestTest(unittest.TestCase): + def assertRejected(self, raw: bytes, code: str): + with self.assertRaises(ProtocolError) as caught: + decode_request(raw) + self.assertEqual(caught.exception.code, code, str(caught.exception)) + return caught.exception + + def test_well_formed_requests(self): + request = decode_request(line({"op": "set_profile", "args": {"profile": "quiet"}, "id": 3})) + self.assertEqual((request.op, request.args, request.id), ("set_profile", {"profile": "quiet"}, 3)) + self.assertEqual(decode_request(line({"op": "state", "id": "a"})).args, {}) # args may be left out + chase = decode_request(line({"op": "ram_chase", "id": 1, "args": {"phase": 6, "rate": 6.7, "power": None}})) + self.assertEqual(chase.args, {"phase": 6.0, "rate": 6.7, "power": None}) + + def test_malformed_input_is_rejected(self): + for raw in (b"", b"not json", b"[1, 2]", b'"state"', b"\xff\xfe{}", b'{"op": "state"', + b'{"op": "state", "id": 1, "id": 2}', # duplicate key + b'{"op": "ram_chase", "id": 1, "args": {"phase": NaN, "rate": 1, "power": null}}', + b'{"op": "ram_chase", "id": 1, "args": {"phase": Infinity, "rate": 1, "power": null}}', + b"[" * 30_000 + b"]" * 30_000, # deep nesting + line({"op": "state"}), # no id + line({"op": "state", "id": True}), # bool is not an id + line({"op": "state", "id": 1.5}), + line({"op": "state", "id": "x" * 65}), + line({"op": 7, "id": 1}), + line({"id": 1})): + with self.subTest(raw=raw[:60]): + self.assertRejected(raw, BAD_REQUEST) + + def test_errors_echo_the_id_when_it_was_readable(self): + self.assertEqual(self.assertRejected(line({"op": "reboot", "id": 9}), UNKNOWN_OP).request_id, 9) + self.assertIsNone(self.assertRejected(line({"op": "state", "id": [1]}), BAD_REQUEST).request_id) + + def test_unknown_ops_and_fields_are_rejected(self): + self.assertRejected(line({"op": "reboot", "id": 1}), UNKNOWN_OP) + self.assertRejected(line({"op": "__class__", "id": 1}), UNKNOWN_OP) + self.assertRejected(line({"op": "state", "id": 1, "extra": 1}), BAD_REQUEST) + self.assertRejected(line({"op": "state", "id": 1, "args": {"verbose": True}}), INVALID) + self.assertRejected(line({"op": "set_profile", "id": 1, "args": {"profile": "quiet", "x": 1}}), INVALID) + + def test_arguments_are_checked_like_the_api_checks_them(self): + for args in ({}, {"profile": "turbo"}, {"profile": 1}, {"profile": ["quiet"]}): + with self.subTest(args=args): + self.assertRejected(line({"op": "set_profile", "id": 1, "args": args}), INVALID) + for mode in ("rainbow", "", None, True): + with self.subTest(mode=mode): + self.assertRejected(line({"op": "set_ram_lighting", "id": 1, "args": {"mode": mode}}), INVALID) + for args in ({"phase": 1, "rate": -1, "power": None}, {"phase": "1", "rate": 1, "power": None}, + {"phase": 1, "rate": True, "power": None}, {"phase": 1, "rate": 1}, + {"phase": 1, "rate": 1, "power": 1e9}): + with self.subTest(args=args): + self.assertRejected(line({"op": "ram_chase", "id": 1, "args": args}), INVALID) + self.assertRejected(line({"op": "state", "id": 1, "args": []}), INVALID) + self.assertRejected(line({"op": "hello", "id": 1, "args": {"protocol": "1"}}), INVALID) + self.assertRejected(line({"op": "hello", "id": 1, "args": {"protocol": 1, "client": "x" * 65}}), INVALID) + + def test_oversized_messages_are_rejected(self): + padding = "x" * MAX_MESSAGE + self.assertRejected(line({"op": "state", "id": padding}), TOO_LARGE) + with self.assertRaises(ValueError): + protocol.encode({"padding": padding}) + + def test_client_side_encoding_uses_the_same_checks(self): + self.assertEqual(json.loads(encode_request("set_profile", {"profile": "full"}, 2)), + {"op": "set_profile", "args": {"profile": "full"}, "id": 2}) + for op, args in (("set_profile", {"profile": "turbo"}), ("reboot", {}), ("state", {"x": 1})): + with self.subTest(op=op): + with self.assertRaises(ValueError): + encode_request(op, args, 1) + + +class DecodeReplyTest(unittest.TestCase): + def test_results_errors_and_mismatches(self): + self.assertEqual(decode_reply(line({"id": 4, "ok": True, "result": {"a": 1}}), 4), {"a": 1}) + with self.assertRaises(RemoteError) as caught: + decode_reply(line({"id": 4, "ok": False, "error": {"code": INVALID, "message": "bad"}}), 4) + self.assertEqual((caught.exception.code, str(caught.exception)), (INVALID, "bad")) + for reply in ({"id": 5, "ok": True, "result": 1}, # someone else's reply + {"id": 4, "ok": 1, "result": 1}, + {"id": 4, "ok": True}, + {"id": 4, "ok": True, "result": 1, "extra": 2}, + {"id": 4, "ok": False, "error": "bad"}, + {"id": 4, "ok": False, "error": {"code": "x"}}, + [4, True]): + with self.subTest(reply=reply): + with self.assertRaises(ProtocolError): + decode_reply(line(reply), 4) + + +class LineBufferTest(unittest.TestCase): + def test_lines_split_across_reads_and_crlf(self): + buffer = LineBuffer() + self.assertEqual(buffer.feed(b'{"a"'), []) + self.assertTrue(buffer.partial) + self.assertEqual(buffer.feed(b':1}\r\n{"b":2}\n{"c"'), [b'{"a":1}', b'{"b":2}']) + self.assertEqual(buffer.feed(b":3}\n"), [b'{"c":3}']) + self.assertFalse(buffer.partial) + + def test_a_line_over_the_limit_is_refused_before_it_ends(self): + buffer = LineBuffer(limit=10) + self.assertEqual(buffer.feed(b"x" * 10 + b"\n"), [b"x" * 10]) + with self.assertRaises(ProtocolError) as caught: + buffer.feed(b"y" * 11) # no newline yet: refused without waiting for the rest + self.assertEqual(caught.exception.code, TOO_LARGE) + with self.assertRaises(ProtocolError): + LineBuffer(limit=10).feed(b"z" * 11 + b"\n") + + +class SessionTest(unittest.TestCase): + def setUp(self): + self.calls = [] + + def dispatch(op, args): + self.calls.append((op, args)) + if args.get("profile") == "quiet": + raise ValueError("can't today") + if args.get("profile") == "full": + raise Unavailable("settings are invalid") + if args.get("profile") == "performance": + raise RuntimeError("bug") + if op == "state": + return {"temp": float("nan")} + return {"done": op} + + self.session = Session(dispatch, "9.9.9") + + def send(self, obj): + reply, close = self.session.handle(line(obj) if not isinstance(obj, bytes) else obj) + return json.loads(reply), close + + def hello(self, version=PROTOCOL_VERSION): + return self.send({"op": "hello", "id": 0, "args": {"protocol": version, "client": "test"}}) + + def test_hello_first_then_operations(self): + reply, close = self.send({"op": "set_profile", "id": 1, "args": {"profile": "balanced"}}) + self.assertEqual((reply["error"]["code"], close), (HELLO_FIRST, False)) + self.assertEqual(self.calls, []) + reply, close = self.hello() + self.assertEqual((reply["result"], close), ({"protocol": PROTOCOL_VERSION, "service": "9.9.9"}, False)) + reply, _ = self.send({"op": "set_profile", "id": 2, "args": {"profile": "balanced"}}) + self.assertEqual(reply, {"id": 2, "ok": True, "result": {"done": "set_profile"}}) + + def test_version_mismatch_is_answered_then_the_connection_closes(self): + reply, close = self.hello(PROTOCOL_VERSION + 1) + self.assertEqual((reply["error"]["code"], close), (VERSION, True)) + self.assertIn(str(PROTOCOL_VERSION), reply["error"]["message"]) + self.assertFalse(self.session.greeted) + + def test_operation_failures_map_to_error_codes(self): + self.hello() + for profile, code in (("quiet", INVALID), ("full", UNAVAILABLE), ("performance", INTERNAL)): + with self.subTest(profile=profile): + if code == INTERNAL: + with self.assertLogs("kurgan.hw.protocol", level="ERROR"): + reply, close = self.send({"op": "set_profile", "id": 3, "args": {"profile": profile}}) + else: + reply, close = self.send({"op": "set_profile", "id": 3, "args": {"profile": profile}}) + self.assertEqual((reply["id"], reply["error"]["code"], close), (3, code, False)) + + def test_a_reply_that_cannot_be_encoded_is_an_internal_error(self): + self.hello() + with self.assertLogs("kurgan.hw.protocol", level="ERROR"): + reply, close = self.send({"op": "state", "id": 4}) + self.assertEqual((reply["error"]["code"], close), (INTERNAL, False)) + + def test_bad_lines_keep_the_connection_but_oversized_ones_close_it(self): + reply, close = self.send(b"garbage") + self.assertEqual((reply["error"]["code"], close), (BAD_REQUEST, False)) + reply, close = self.send(b"x" * (MAX_MESSAGE + 1)) + self.assertEqual((reply["error"]["code"], close), (TOO_LARGE, True)) + + +if __name__ == "__main__": + unittest.main()