- kurgan/hw/install.py (run elevated by setup.ps1): checks the base interpreter can run hw_service.py, creates %ProgramData%\Kurgan or resets its owner and access (Administrators own it; SYSTEM and Administrators full control, users read), moves the fan and RAM settings there, then creates or updates KurganHw through the service manager API (pywin32; sc.exe's quoting from Windows PowerShell 5.1 isn't reliable): LocalSystem, automatic start, restart after 5 s, 10 s and 60 s, the user's SID for the pipe. A running service is stopped first; then it's started and must reach "running". - kurgan/hw/migrate.py: "copy" (elevated) creates hw-settings.json from the user's cooling and lighting.memory, never overwriting an existing file; "strip" (as the user) removes them from settings.json once hw-settings.json exists, keeping a dated backup. An invalid file on either side stops it. - setup.ps1: creates the .venv if needed (the service runs from it), passes the base interpreter, the user's SID and settings path to the elevated part, which installs the service; then strips settings.json, registers and starts the app's task, and prints the service's status. - uninstall.ps1: also stops and deletes the service. - python -m kurgan.hw.client prints the service's status (setup runs it). - The pipe's "isn't running", "refused this user" and "closed the connection" errors no longer repeat the Windows error text. - Tests: migration (move, re-run, defaults, invalid files) and the install module's parts that don't need admin rights. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
479 lines
21 KiB
Python
479 lines
21 KiB
Python
"""The named pipe between the hardware service and the app: server and client, with timeouts.
|
|
|
|
Server (the service): every connection gets its own thread, so a slow or hostile client can
|
|
only waste its own slot, never the fan loop's time. A connection that sends nothing, or leaves
|
|
a line unfinished, for READ_TIMEOUT seconds is dropped, and so is one that won't read its
|
|
replies. The pipe refuses remote clients, and its access list (pipe_sddl) allows SYSTEM and
|
|
Administrators full access and the installing user read/write only: no
|
|
FILE_CREATE_PIPE_INSTANCE, so the user's other programs can't add an instance of their own and
|
|
answer in the service's name. The first instance is created with FILE_FLAG_FIRST_PIPE_INSTANCE,
|
|
so a program that took the name first makes the service fail loudly instead of sharing it.
|
|
|
|
Client (the app): connects at identification level only (the service can't act as the user),
|
|
and refuses a pipe whose owner isn't SYSTEM or Administrators, i.e. one that some unelevated
|
|
program created while the service was down.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ctypes
|
|
import ctypes.wintypes as wt
|
|
import logging
|
|
import re
|
|
import threading
|
|
import time
|
|
from typing import Callable
|
|
|
|
from kurgan.hw.protocol import READ_TIMEOUT, TOO_LARGE, LineBuffer, ProtocolError, encode_error
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
_adv = ctypes.WinDLL("advapi32", use_last_error=True)
|
|
|
|
ERROR_FILE_NOT_FOUND = 2
|
|
ERROR_ACCESS_DENIED = 5
|
|
ERROR_BROKEN_PIPE = 109
|
|
ERROR_PIPE_BUSY = 231
|
|
ERROR_NO_DATA = 232
|
|
ERROR_MORE_DATA = 234
|
|
ERROR_PIPE_CONNECTED = 535
|
|
ERROR_OPERATION_ABORTED = 995
|
|
ERROR_IO_PENDING = 997
|
|
WAIT_OBJECT_0, WAIT_TIMEOUT = 0, 0x102
|
|
INFINITE = 0xFFFFFFFF
|
|
INVALID_HANDLE = wt.HANDLE(-1).value
|
|
|
|
PIPE_ACCESS_DUPLEX = 0x3
|
|
FILE_FLAG_OVERLAPPED = 0x40000000
|
|
FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000
|
|
PIPE_TYPE_BYTE = PIPE_READMODE_BYTE = PIPE_WAIT = 0
|
|
PIPE_REJECT_REMOTE_CLIENTS = 0x8
|
|
GENERIC_READ = 0x80000000
|
|
FILE_WRITE_DATA = 0x2
|
|
OPEN_EXISTING = 3
|
|
SECURITY_SQOS_PRESENT = 0x00100000
|
|
SECURITY_IDENTIFICATION = 0x00010000
|
|
SE_KERNEL_OBJECT = 6
|
|
OWNER_SECURITY_INFORMATION = 0x1
|
|
TOKEN_QUERY, TOKEN_USER = 0x8, 1
|
|
|
|
# What the installing user gets on the pipe: FILE_GENERIC_READ | FILE_WRITE_DATA |
|
|
# FILE_WRITE_ATTRIBUTES. Deliberately not GENERIC_WRITE, which includes FILE_APPEND_DATA, i.e.
|
|
# FILE_CREATE_PIPE_INSTANCE for a pipe.
|
|
USER_ACCESS = 0x0012018B
|
|
SYSTEM_SID, ADMINISTRATORS_SID = "S-1-5-18", "S-1-5-32-544"
|
|
TRUSTED_OWNERS = (SYSTEM_SID, ADMINISTRATORS_SID)
|
|
BUFFER_SIZE = 128 * 1024
|
|
_SID = re.compile(r"S-1-\d+(-\d+)+")
|
|
|
|
|
|
class _Overlapped(ctypes.Structure):
|
|
_fields_ = [("Internal", ctypes.c_size_t), ("InternalHigh", ctypes.c_size_t),
|
|
("Offset", wt.DWORD), ("OffsetHigh", wt.DWORD), ("hEvent", wt.HANDLE)]
|
|
|
|
|
|
class _SecurityAttributes(ctypes.Structure):
|
|
_fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p), ("bInheritHandle", wt.BOOL)]
|
|
|
|
|
|
class _SidAndAttributes(ctypes.Structure):
|
|
_fields_ = [("Sid", ctypes.c_void_p), ("Attributes", wt.DWORD)]
|
|
|
|
|
|
_k32.CreateNamedPipeW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD,
|
|
ctypes.POINTER(_SecurityAttributes)]
|
|
_k32.CreateNamedPipeW.restype = wt.HANDLE
|
|
_k32.ConnectNamedPipe.argtypes = [wt.HANDLE, ctypes.POINTER(_Overlapped)]
|
|
_k32.ConnectNamedPipe.restype = wt.BOOL
|
|
_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE]
|
|
_k32.CreateFileW.restype = wt.HANDLE
|
|
_k32.WaitNamedPipeW.argtypes = [wt.LPCWSTR, wt.DWORD]
|
|
_k32.WaitNamedPipeW.restype = wt.BOOL
|
|
_k32.ReadFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_Overlapped)]
|
|
_k32.ReadFile.restype = wt.BOOL
|
|
_k32.WriteFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_Overlapped)]
|
|
_k32.WriteFile.restype = wt.BOOL
|
|
_k32.GetOverlappedResult.argtypes = [wt.HANDLE, ctypes.POINTER(_Overlapped), ctypes.POINTER(wt.DWORD), wt.BOOL]
|
|
_k32.GetOverlappedResult.restype = wt.BOOL
|
|
_k32.CancelIoEx.argtypes = [wt.HANDLE, ctypes.POINTER(_Overlapped)]
|
|
_k32.CancelIoEx.restype = wt.BOOL
|
|
_k32.CreateEventW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.BOOL, wt.LPCWSTR]
|
|
_k32.CreateEventW.restype = wt.HANDLE
|
|
_k32.SetEvent.argtypes = [wt.HANDLE]
|
|
_k32.SetEvent.restype = wt.BOOL
|
|
_k32.ResetEvent.argtypes = [wt.HANDLE]
|
|
_k32.ResetEvent.restype = wt.BOOL
|
|
_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD]
|
|
_k32.WaitForSingleObject.restype = wt.DWORD
|
|
_k32.WaitForMultipleObjects.argtypes = [wt.DWORD, ctypes.POINTER(wt.HANDLE), wt.BOOL, wt.DWORD]
|
|
_k32.WaitForMultipleObjects.restype = wt.DWORD
|
|
_k32.CloseHandle.argtypes = [wt.HANDLE]
|
|
_k32.CloseHandle.restype = wt.BOOL
|
|
_k32.LocalFree.argtypes = [ctypes.c_void_p]
|
|
_k32.LocalFree.restype = ctypes.c_void_p
|
|
_k32.GetCurrentProcess.restype = wt.HANDLE
|
|
_adv.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
|
|
wt.LPCWSTR, wt.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wt.ULONG)]
|
|
_adv.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wt.BOOL
|
|
_adv.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.LPWSTR)]
|
|
_adv.ConvertSidToStringSidW.restype = wt.BOOL
|
|
_adv.GetSecurityInfo.argtypes = [wt.HANDLE, ctypes.c_int, wt.DWORD, ctypes.POINTER(ctypes.c_void_p),
|
|
ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_void_p),
|
|
ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_void_p)]
|
|
_adv.GetSecurityInfo.restype = wt.DWORD
|
|
_adv.OpenProcessToken.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.HANDLE)]
|
|
_adv.OpenProcessToken.restype = wt.BOOL
|
|
_adv.GetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD)]
|
|
_adv.GetTokenInformation.restype = wt.BOOL
|
|
|
|
|
|
class PipeError(OSError):
|
|
"""The pipe couldn't be opened, read or written; .code is the Windows error, when there was one."""
|
|
|
|
def __init__(self, message: str, code: int | None = None):
|
|
super().__init__(message)
|
|
self.code = code
|
|
|
|
|
|
def _error(what: str, code: int | None = None) -> PipeError:
|
|
code = ctypes.get_last_error() if code is None else code
|
|
return PipeError(f"{what}: [{code}] {ctypes.FormatError(code).strip()}", code)
|
|
|
|
|
|
def _sid_string(sid: int) -> str:
|
|
text = wt.LPWSTR()
|
|
if not _adv.ConvertSidToStringSidW(sid, ctypes.byref(text)):
|
|
raise _error("ConvertSidToStringSid")
|
|
try:
|
|
return text.value
|
|
finally:
|
|
_k32.LocalFree(text)
|
|
|
|
|
|
def current_user_sid() -> str:
|
|
"""This process's user SID, e.g. S-1-5-21-...-1001."""
|
|
token = wt.HANDLE()
|
|
if not _adv.OpenProcessToken(_k32.GetCurrentProcess(), TOKEN_QUERY, ctypes.byref(token)):
|
|
raise _error("OpenProcessToken")
|
|
try:
|
|
size = wt.DWORD()
|
|
_adv.GetTokenInformation(token, TOKEN_USER, None, 0, ctypes.byref(size))
|
|
buf = ctypes.create_string_buffer(size.value)
|
|
if not _adv.GetTokenInformation(token, TOKEN_USER, buf, size, ctypes.byref(size)):
|
|
raise _error("GetTokenInformation(TokenUser)")
|
|
return _sid_string(_SidAndAttributes.from_buffer(buf).Sid)
|
|
finally:
|
|
_k32.CloseHandle(token)
|
|
|
|
|
|
def valid_sid(text: object) -> bool:
|
|
return isinstance(text, str) and _SID.fullmatch(text) is not None
|
|
|
|
|
|
def pipe_sddl(user_sid: str | None, server_sid: str | None = None) -> str:
|
|
"""The pipe's access list: SYSTEM and Administrators full, `user_sid` read/write, nobody else.
|
|
|
|
server_sid also gets full access; only for a server that isn't SYSTEM or an elevated admin
|
|
(tests), since creating each further instance of the pipe needs FILE_CREATE_PIPE_INSTANCE."""
|
|
aces = ["(A;;GA;;;SY)", "(A;;GA;;;BA)"]
|
|
for sid, access in ((server_sid, "GA"), (user_sid, f"0x{USER_ACCESS:x}")):
|
|
if sid is not None:
|
|
if not valid_sid(sid):
|
|
raise ValueError(f"not a SID: {sid!r}")
|
|
aces.append(f"(A;;{access};;;{sid})")
|
|
return "D:P" + "".join(aces)
|
|
|
|
|
|
def pipe_owner(handle) -> str:
|
|
owner, descriptor = ctypes.c_void_p(), ctypes.c_void_p()
|
|
code = _adv.GetSecurityInfo(handle, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION, ctypes.byref(owner),
|
|
None, None, None, ctypes.byref(descriptor))
|
|
if code != 0:
|
|
raise _error("GetSecurityInfo", code)
|
|
try:
|
|
return _sid_string(owner.value)
|
|
finally:
|
|
_k32.LocalFree(descriptor)
|
|
|
|
|
|
def _event() -> wt.HANDLE:
|
|
event = _k32.CreateEventW(None, True, False, None)
|
|
if not event:
|
|
raise _error("CreateEvent")
|
|
return event
|
|
|
|
|
|
def _ms(seconds: float | None) -> int:
|
|
return INFINITE if seconds is None else max(0, min(int(seconds * 1000), INFINITE - 1))
|
|
|
|
|
|
def _finish(handle, ov: _Overlapped, events: list, timeout: float | None) -> int | None:
|
|
"""Wait for a pending overlapped call: bytes transferred, or None if it timed out or another
|
|
event (a stop request) fired first, in which case the call is cancelled and waited for, so
|
|
its buffer and OVERLAPPED can be freed. Raises PipeError if the call failed."""
|
|
handles = (wt.HANDLE * (1 + len(events)))(ov.hEvent, *events)
|
|
which = _k32.WaitForMultipleObjects(len(handles), handles, False, _ms(timeout))
|
|
done = wt.DWORD()
|
|
if which != WAIT_OBJECT_0:
|
|
_k32.CancelIoEx(handle, ctypes.byref(ov))
|
|
if _k32.GetOverlappedResult(handle, ctypes.byref(ov), ctypes.byref(done), True):
|
|
return done.value # it completed before the cancel landed
|
|
return None
|
|
if not _k32.GetOverlappedResult(handle, ctypes.byref(ov), ctypes.byref(done), False):
|
|
code = ctypes.get_last_error()
|
|
if code == ERROR_MORE_DATA:
|
|
return done.value
|
|
raise _error("pipe I/O", code)
|
|
return done.value
|
|
|
|
|
|
def _read(handle, event, timeout: float | None, stop_events=(), size: int = 65536) -> bytes | None:
|
|
"""Up to `size` bytes; b"" when the other end has closed; None on timeout or stop."""
|
|
buf = ctypes.create_string_buffer(size)
|
|
ov = _Overlapped(hEvent=event)
|
|
_k32.ResetEvent(event)
|
|
if not _k32.ReadFile(handle, buf, size, None, ctypes.byref(ov)):
|
|
code = ctypes.get_last_error()
|
|
if code in (ERROR_BROKEN_PIPE, ERROR_NO_DATA):
|
|
return b""
|
|
if code not in (ERROR_IO_PENDING, ERROR_MORE_DATA):
|
|
raise _error("ReadFile", code)
|
|
try:
|
|
got = _finish(handle, ov, list(stop_events), timeout)
|
|
except PipeError as e:
|
|
if e.code in (ERROR_BROKEN_PIPE, ERROR_NO_DATA, ERROR_OPERATION_ABORTED):
|
|
return b""
|
|
raise
|
|
return None if got is None else buf.raw[:got]
|
|
|
|
|
|
def _write(handle, event, data: bytes, timeout: float, stop_events=()) -> None:
|
|
buf = ctypes.create_string_buffer(data, len(data))
|
|
ov = _Overlapped(hEvent=event)
|
|
_k32.ResetEvent(event)
|
|
if not _k32.WriteFile(handle, buf, len(data), None, ctypes.byref(ov)):
|
|
code = ctypes.get_last_error()
|
|
if code != ERROR_IO_PENDING:
|
|
raise _error("WriteFile", code)
|
|
sent = _finish(handle, ov, list(stop_events), timeout)
|
|
if sent is None:
|
|
raise PipeError("pipe write timed out (the other end isn't reading)")
|
|
if sent != len(data):
|
|
raise PipeError(f"pipe write sent {sent} of {len(data)} bytes")
|
|
|
|
|
|
# ----------------------------------------------------------------------------- server
|
|
|
|
class PipeServer:
|
|
"""Serves `session_factory()` sessions (protocol.Session) on a named pipe, one thread each."""
|
|
|
|
def __init__(self, name: str, sddl: str, session_factory: Callable, *, max_clients: int = 8,
|
|
read_timeout: float = READ_TIMEOUT, write_timeout: float = 5.0):
|
|
self.name = name
|
|
self.max_clients = max_clients
|
|
self.read_timeout = read_timeout
|
|
self.write_timeout = write_timeout
|
|
self._sessions = session_factory
|
|
self._descriptor = ctypes.c_void_p()
|
|
if not _adv.ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, 1, ctypes.byref(self._descriptor),
|
|
None):
|
|
raise _error(f"Invalid pipe security descriptor {sddl!r}")
|
|
self._attributes = _SecurityAttributes(ctypes.sizeof(_SecurityAttributes), self._descriptor, False)
|
|
self._stop = _event()
|
|
self._stopping = False
|
|
self._lock = threading.Condition()
|
|
self._clients = 0
|
|
self._threads: list[threading.Thread] = []
|
|
self._listener: threading.Thread | None = None
|
|
self.error: str | None = None # why the pipe can't be created right now, for the snapshot
|
|
|
|
def start(self) -> None:
|
|
self._listener = threading.Thread(target=self._listen, name="hw-pipe", daemon=True)
|
|
self._listener.start()
|
|
|
|
def close(self, timeout: float = 5.0) -> None:
|
|
self._stopping = True
|
|
_k32.SetEvent(self._stop)
|
|
with self._lock:
|
|
self._lock.notify_all()
|
|
deadline = time.monotonic() + timeout
|
|
for thread in [self._listener, *list(self._threads)]:
|
|
if thread is not None:
|
|
thread.join(max(0.0, deadline - time.monotonic()))
|
|
if self._descriptor and not (self._listener is not None and self._listener.is_alive()):
|
|
_k32.LocalFree(self._descriptor)
|
|
self._descriptor = ctypes.c_void_p()
|
|
|
|
@property
|
|
def clients(self) -> int:
|
|
with self._lock:
|
|
return self._clients
|
|
|
|
def _create(self) -> wt.HANDLE | None:
|
|
with self._lock:
|
|
first = self._clients == 0
|
|
mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | (FILE_FLAG_FIRST_PIPE_INSTANCE if first else 0)
|
|
handle = _k32.CreateNamedPipeW(self.name, mode, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT
|
|
| PIPE_REJECT_REMOTE_CLIENTS, self.max_clients, BUFFER_SIZE, BUFFER_SIZE,
|
|
0, ctypes.byref(self._attributes))
|
|
if handle == INVALID_HANDLE or not handle:
|
|
code = ctypes.get_last_error()
|
|
hint = (" (another program holds the pipe's name)" if code == ERROR_ACCESS_DENIED and first
|
|
else "")
|
|
message = f"can't create {self.name}: [{code}] {ctypes.FormatError(code).strip()}{hint}"
|
|
if message != self.error:
|
|
log.error("Pipe server %s; retrying", message)
|
|
self.error = message
|
|
return None
|
|
if self.error is not None:
|
|
log.info("Pipe server listening on %s again", self.name)
|
|
self.error = None
|
|
return handle
|
|
|
|
def _listen(self) -> None:
|
|
event = _event()
|
|
try:
|
|
while not self._stopping:
|
|
with self._lock:
|
|
if self._clients >= self.max_clients: # wait for a slot (each times out eventually)
|
|
self._lock.wait(0.5)
|
|
continue
|
|
handle = self._create()
|
|
if handle is None:
|
|
if _k32.WaitForSingleObject(self._stop, 5000) == WAIT_OBJECT_0:
|
|
break
|
|
continue
|
|
ov = _Overlapped(hEvent=event)
|
|
_k32.ResetEvent(event)
|
|
connected = bool(_k32.ConnectNamedPipe(handle, ctypes.byref(ov)))
|
|
if not connected:
|
|
code = ctypes.get_last_error()
|
|
if code == ERROR_PIPE_CONNECTED:
|
|
connected = True
|
|
elif code == ERROR_IO_PENDING:
|
|
try:
|
|
connected = _finish(handle, ov, [self._stop], None) is not None
|
|
except PipeError as e:
|
|
log.debug("Pipe connect failed: %s", e)
|
|
else:
|
|
log.debug("ConnectNamedPipe failed: [%d]", code)
|
|
if not connected or self._stopping:
|
|
_k32.CloseHandle(handle)
|
|
continue
|
|
with self._lock:
|
|
self._clients += 1
|
|
thread = threading.Thread(target=self._serve, args=(handle,), name="hw-pipe-client", daemon=True)
|
|
self._threads = [t for t in self._threads if t.is_alive()] + [thread]
|
|
thread.start()
|
|
except Exception:
|
|
log.exception("Pipe listener failed")
|
|
self.error = "pipe listener failed; see the service log"
|
|
finally:
|
|
_k32.CloseHandle(event)
|
|
|
|
def _serve(self, handle) -> None:
|
|
read_event, write_event = _event(), _event()
|
|
session = self._sessions()
|
|
buffer = LineBuffer()
|
|
line_started: float | None = None
|
|
try:
|
|
while not self._stopping:
|
|
now = time.monotonic()
|
|
deadline = (line_started or now) + self.read_timeout
|
|
data = _read(handle, read_event, max(0.0, deadline - now), [self._stop])
|
|
if not data: # closed, timed out (silent too long, or a line left unfinished), or stopping
|
|
if data is None and not self._stopping:
|
|
log.debug("Dropping a pipe client that sent nothing for %.0f s", self.read_timeout)
|
|
return
|
|
try:
|
|
lines = buffer.feed(data)
|
|
except ProtocolError as e:
|
|
_write(handle, write_event, encode_error(None, TOO_LARGE, str(e)), self.write_timeout,
|
|
[self._stop])
|
|
return
|
|
line_started = (line_started or time.monotonic()) if buffer.partial else None
|
|
for line in lines:
|
|
reply, close = session.handle(line)
|
|
_write(handle, write_event, reply, self.write_timeout, [self._stop])
|
|
if close:
|
|
return
|
|
except PipeError as e:
|
|
log.debug("Pipe client dropped: %s", e)
|
|
except Exception:
|
|
log.exception("Pipe client failed")
|
|
finally:
|
|
# No DisconnectNamedPipe: it would discard a last reply the client hasn't read yet.
|
|
_k32.CloseHandle(handle)
|
|
for event in (read_event, write_event):
|
|
_k32.CloseHandle(event)
|
|
with self._lock:
|
|
self._clients -= 1
|
|
self._lock.notify_all()
|
|
|
|
|
|
# ----------------------------------------------------------------------------- client
|
|
|
|
class PipeClient:
|
|
"""One connection to the service. Not thread-safe: callers serialise request()."""
|
|
|
|
def __init__(self, name: str, timeout: float = 2.0, trusted_owners: tuple[str, ...] | None = TRUSTED_OWNERS):
|
|
deadline = time.monotonic() + timeout
|
|
while True:
|
|
handle = _k32.CreateFileW(name, GENERIC_READ | FILE_WRITE_DATA, 0, None, OPEN_EXISTING,
|
|
FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, None)
|
|
if handle != INVALID_HANDLE and handle:
|
|
break
|
|
code = ctypes.get_last_error()
|
|
left = deadline - time.monotonic()
|
|
if code == ERROR_PIPE_BUSY and left > 0:
|
|
_k32.WaitNamedPipeW(name, max(1, int(left * 1000)))
|
|
continue
|
|
if code == ERROR_FILE_NOT_FOUND:
|
|
raise PipeError("the hardware service isn't running (no pipe)", code)
|
|
if code == ERROR_ACCESS_DENIED:
|
|
raise PipeError("the hardware service's pipe refused this user", code)
|
|
raise _error(f"can't open {name}", code)
|
|
self._handle = handle
|
|
self._read_event, self._write_event = _event(), _event()
|
|
self._buffer = LineBuffer()
|
|
self._lines: list[bytes] = []
|
|
if trusted_owners is not None:
|
|
try:
|
|
owner = pipe_owner(handle)
|
|
except OSError:
|
|
self.close()
|
|
raise
|
|
if owner not in trusted_owners:
|
|
self.close()
|
|
raise PipeError(f"{name} belongs to {owner}, not the hardware service; not using it")
|
|
|
|
def request(self, data: bytes, timeout: float) -> bytes:
|
|
"""Send one line, return the next line received (without its newline)."""
|
|
if self._handle is None:
|
|
raise PipeError("pipe closed")
|
|
deadline = time.monotonic() + timeout
|
|
_write(self._handle, self._write_event, data, timeout)
|
|
while not self._lines:
|
|
left = deadline - time.monotonic()
|
|
chunk = _read(self._handle, self._read_event, max(0.0, left)) if left > 0 else None
|
|
if chunk is None:
|
|
raise PipeError(f"no reply from the hardware service within {timeout:g} s")
|
|
if not chunk:
|
|
raise PipeError("the hardware service closed the connection", ERROR_BROKEN_PIPE)
|
|
self._lines += self._buffer.feed(chunk)
|
|
return self._lines.pop(0)
|
|
|
|
def close(self) -> None:
|
|
for name in ("_handle", "_read_event", "_write_event"):
|
|
handle = getattr(self, name, None)
|
|
if handle:
|
|
_k32.CloseHandle(handle)
|
|
setattr(self, name, None)
|
|
|
|
def __del__(self):
|
|
try:
|
|
self.close()
|
|
except Exception:
|
|
pass
|