diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml
index 7c5e93592c81f74fcc5a179eeae10f29b12ff2c0..f147fea63f24032246efe23fd65b67337065ca47 100644
--- a/.github/workflows/linux.yml
+++ b/.github/workflows/linux.yml
@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-name: Linux client
+name: Desktop device SDK
on:
pull_request:
@@ -34,6 +34,10 @@ jobs:
fail-fast: false
matrix:
include:
+ - name: windows
+ os: windows-latest
+ python: "3.13"
+ pins: ""
- name: newest
os: ubuntu-latest
python: "3.x"
@@ -59,9 +63,11 @@ jobs:
# libopus for the video call tests (they skip without it).
- name: Install libopus
+ if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y libopus0
- name: Install
+ shell: bash
env:
PINS: ${{ matrix.pins }}
run: python -m pip install pytest . $PINS
@@ -78,9 +84,11 @@ jobs:
# The wake word's native library (the ESP32 runner, built from pinned
# registry archives), then the detector tests against it.
- name: Wake-word library
+ if: runner.os == 'Linux'
run: bash wakeword/build.sh --out "$RUNNER_TEMP/wakeword"
- name: Wake-word tests
+ if: runner.os == 'Linux'
run: MUSE_WAKEWORD_LIBRARY="$RUNNER_TEMP/wakeword/libmuse_wakeword.so" python -m pytest -q wakeword/tests
shellcheck:
diff --git a/README.md b/README.md
index a8f39e4799bbe39c78eb55dae3342d33c78365af..b0f81a817a5c74fe1d1d4d03efad8fe0d70e87db 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,131 @@
+# Muse Gadget SDK for Windows (experimental fork)
+
+This experimental fork runs the Linux Muse Gadget SDK on Windows. Pair the
+gadget on Linux, then transfer its identity to the Windows PC. The PC connects
+to Muse over the network. [Upstream project](https://github.com/facebookincubator/muse-gadget-sdk) · [Original README](#muse-gadgets)
+
+On Windows, we tested sending and receiving chat messages, attaching images,
+sending voice notes and receiving spoken replies, running shell and custom
+commands, and transferring files against a production Muse VM. The “Hey Muse”
+detector also recognized the wake word through a PC microphone. The VM returned
+HTTP 404 when starting real-time voice and video calls, so we could not verify
+either call end to end.
+
+
+Install on Windows, transfer a pairing, and connect
+
+1. Install Python 3.9 or later. From the root of this checkout, open a regular
+ PowerShell window as the Windows user whose files and programs Muse should
+ be able to access.
+
+ ```powershell
+ python -m venv .venv
+ .\.venv\Scripts\python.exe -m pip install .\linux
+ ```
+
+ With `uv`, run `uv venv --python 3.13 .venv` followed by
+ `uv pip install --python .\.venv\Scripts\python.exe .\linux`.
+
+2. Complete the [Linux pairing steps](linux/README.md#set-it-up-with-muse).
+ Run `sudo musegadget info`, check for `paired: yes`, and note the node ID.
+ Stop the Linux service and disable automatic startup before the transfer.
+ Only one device can use the pairing at a time.
+
+ ```sh
+ sudo systemctl disable --now musegadget
+ ```
+
+3. Transfer `identity.json`, `pairing.json`, and `sdk_token` together from
+ `/var/lib/musegadget/` on Linux to `%LOCALAPPDATA%\MuseGadget\` on Windows
+ over an encrypted connection such as SSH. Keep this directory private and
+ writable by the Windows user running the SDK. For a fresh setup, create it
+ with `New-Item -ItemType Directory -Path "$env:LOCALAPPDATA\MuseGadget"`.
+ If it already holds another gadget's files, use a separate directory and set
+ `MUSEGADGET_STATE_DIR` to its absolute path in each PowerShell session.
+
+4. Check that `info` reports the same node ID as on Linux, then run the
+ diagnostics and start the client.
+
+ ```powershell
+ .\.venv\Scripts\musegadget.exe info
+ .\.venv\Scripts\musegadget.exe doctor
+ .\.venv\Scripts\musegadget.exe run
+ ```
+
+ When the log says `registered with the Muse`, the PC is connected.
+ Press Ctrl+C to stop it. For automatic startup, create a Windows Task
+ Scheduler task under the same user account. Set the program to the absolute
+ path of `.venv\Scripts\musegadget.exe` and the argument to `run`.
+
+To chat through the running client, open another PowerShell window as the
+same user.
+
+```powershell
+.\.venv\Scripts\musegadget.exe send-user-msg --wait 30 "Hello from Windows"
+.\.venv\Scripts\musegadget.exe chat
+```
+
+`system.run` uses `cmd.exe` by default. To run a PowerShell command, use
+`powershell.exe -NoProfile -Command ...`. To register a
+[custom command](linux/README.md#add-your-own-commands), place its JSON
+definition in `commands.d` under the state directory and restart the client.
+Set the first item in `exec` to the absolute path of the executable. For a
+script, use the interpreter as the executable and pass the script path as an
+argument.
+
+In Python, `musegadget.identity.load_existing()` reads the transferred
+identity. It raises `IdentityError` if the identity is missing, invalid, or
+inconsistent with the paired node ID. The default Windows model ID is
+`muse-gadget-windows` and the model name is `Windows gadget`. To pair again,
+stop the Windows client, pair on Linux, and transfer the three files again.
+
+
+
+
+Set up audio, video, and “Hey Muse” on Windows x64
+
+The base installation supports WAV input and output for
+[voice calls](linux/README.md#realtime-voice-wav-first). For a microphone
+and speakers, install the voice extra from PowerShell.
+
+```powershell
+.\.venv\Scripts\python.exe -m pip install ".\linux[voice]"
+```
+
+With `uv`, use `uv pip install --python .\.venv\Scripts\python.exe ".\linux[voice]"`.
+For video calls, add the directory containing an Opus DLL that matches your
+Python architecture to `PATH`.
+
+“Hey Muse” detection uses `muse_wakeword.dll`. Install Git for Windows, extract
+the Windows x86-64 UCRT archive from the
+[llvm-mingw releases](https://github.com/mstorsjo/llvm-mingw/releases), and add
+its `bin` directory to `PATH`. From the repository root in Git Bash, run
+
+```sh
+CC=clang CXX=clang++ bash linux/wakeword/build.sh
+```
+
+The build writes `muse_wakeword.dll` and `ww-run.exe` to `linux/wakeword/build/`.
+In PowerShell, check that the detector handles a synthetic test signal and
+that `sounddevice` and PortAudio load.
+
+```powershell
+$env:MUSE_WAKEWORD_LIBRARY = (Resolve-Path .\linux\wakeword\build\muse_wakeword.dll).Path
+.\.venv\Scripts\python.exe -m musegadget.wakeword_check --check-audio
+```
+
+To listen on the microphone, run the following in the same PowerShell window.
+Replace `YOUR_VM_ID` with the ID of your Muse VM. Detecting the wake word
+starts a voice call attempt.
+
+```powershell
+.\.venv\Scripts\musegadget.exe voice-call --vm-id YOUR_VM_ID --live --wake-word
+```
+
+
+
+---
+
+
+# Windows gadget
+
+This PC runs the Muse Gadget SDK. Its encrypted connection uses the PC's
+network. Muse can use the commands listed by this gadget while the owner
+keeps the client running.
+
+- Shell commands run in cmd.exe under the Windows account that started the
+ client. Use Windows paths and non-interactive commands. The working
+ directory defaults to that account's home directory.
+- Up to four commands can run at once. Files and programs are accessible
+ with the same permissions as the client.
diff --git a/linux/src/musegadget/device_guide.py b/linux/src/musegadget/device_guide.py
index 464d247a30b614b6ac2cb0d2bf0c417fc02c7a2a..22845d052dd2f3306113ca98bd3ca1bac2919463 100644
--- a/linux/src/musegadget/device_guide.py
+++ b/linux/src/musegadget/device_guide.py
@@ -17,6 +17,7 @@
from __future__ import annotations
import functools
+import os
import re
from importlib import resources
@@ -32,8 +33,9 @@ _LEADING_COMMENT = re.compile(r"\A\n*", re.S)
@functools.lru_cache(maxsize=1)
def default_guide() -> str:
- """The Linux client's own guide, from ``data/guide.md`` without its license header."""
- text = resources.files("musegadget").joinpath("data/guide.md").read_text(encoding="utf-8")
+ """The guide for the host running the device commands."""
+ name = "guide-windows.md" if os.name == "nt" else "guide.md"
+ text = resources.files("musegadget").joinpath("data").joinpath(name).read_text(encoding="utf-8")
return check(_LEADING_COMMENT.sub("", text, count=1))
diff --git a/linux/src/musegadget/doctor.py b/linux/src/musegadget/doctor.py
index af45a83479658dca009cfe56ae07a9c0685a9c38..323785d688fdbdb0626db3c012e91b9b84b3c157 100644
--- a/linux/src/musegadget/doctor.py
+++ b/linux/src/musegadget/doctor.py
@@ -23,7 +23,7 @@ import subprocess
from pathlib import Path
from typing import Literal, TypedDict
-from musegadget import config, network, tls
+from musegadget import config, identity, network, tls
from musegadget.muse_api import API_BASE
@@ -37,17 +37,19 @@ class CheckResult(TypedDict):
def check_pairing(directory: Path) -> CheckResult:
"""Check saved credential structure without displaying or validating secrets online."""
path: Path = directory / config.PAIRING_FILE
+ repair = (f"Please {config.PAIRING_HINT}." if os.name == "nt"
+ else "Run sudo musegadget pair --force to pair again.")
try:
saved: object = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return {"name": "Pairing", "status": "FAIL", "detail": "No saved pairing.",
- "hint": "Run sudo musegadget pair, then add the device in the Muse app."}
+ "hint": repair if os.name == "nt" else "Run sudo musegadget pair, then add the device in the Muse app."}
except PermissionError:
return {"name": "Pairing", "status": "FAIL", "detail": "Cannot read saved pairing.",
- "hint": "Run sudo musegadget doctor to read the root-owned state directory."}
+ "hint": _read_hint(directory)}
except ValueError:
return {"name": "Pairing", "status": "FAIL", "detail": "Saved pairing is not valid JSON.",
- "hint": "Run sudo musegadget pair --force to pair again."}
+ "hint": repair}
except OSError as exc:
return {"name": "Pairing", "status": "FAIL",
"detail": f"Cannot read saved pairing (OS error {exc.errno}).",
@@ -55,22 +57,36 @@ def check_pairing(directory: Path) -> CheckResult:
problem = config.pairing_problem(saved)
if problem is not None:
return {"name": "Pairing", "status": "FAIL", "detail": problem,
- "hint": "Run sudo musegadget pair --force to pair again."}
+ "hint": repair}
+ if os.name == "nt":
+ try:
+ identity.load_existing(directory)
+ except (identity.IdentityError, PermissionError):
+ return {"name": "Pairing", "status": "FAIL", "detail": "Cannot use the saved device identity.",
+ "hint": repair}
return {"name": "Pairing", "status": "OK", "detail": "Device tokens are saved.",
"hint": "This checks local structure, not whether Muse accepts the tokens."}
+def _read_hint(directory: Path) -> str:
+ if os.name == "nt":
+ return f"Check that your Windows account has access to {directory}."
+ return "Run sudo musegadget doctor to read the root-owned state directory."
+
+
def check_sdk_token(directory: Path) -> CheckResult:
"""Reuse SDK token validation, checking file access before its optional-file reader."""
+ install = ("Copy sdk_token from the paired Linux gadget." if os.name == "nt"
+ else "Run bash install.sh --sdk-token TOKEN with a token from gadgets.muse.ai.")
if not os.environ.get(config.SDK_TOKEN_ENV):
try:
(directory / config.SDK_TOKEN_FILE).read_bytes()
except FileNotFoundError:
return {"name": "SDK token", "status": "FAIL", "detail": "No SDK token file.",
- "hint": "Run bash install.sh --sdk-token TOKEN with a token from gadgets.muse.ai."}
+ "hint": install}
except PermissionError:
return {"name": "SDK token", "status": "FAIL", "detail": "Cannot read SDK token file.",
- "hint": "Run sudo musegadget doctor to read the root-owned state directory."}
+ "hint": _read_hint(directory)}
except OSError as exc:
return {"name": "SDK token", "status": "FAIL",
"detail": f"Cannot read SDK token file (OS error {exc.errno}).",
@@ -82,7 +98,7 @@ def check_sdk_token(directory: Path) -> CheckResult:
"hint": "Copy a fresh token from gadgets.muse.ai; check MUSEGADGET_SDK_TOKEN too."}
if token is None:
return {"name": "SDK token", "status": "FAIL", "detail": "SDK token is empty.",
- "hint": "Run bash install.sh --sdk-token TOKEN with a token from gadgets.muse.ai."}
+ "hint": install}
return {"name": "SDK token", "status": "OK", "detail": "SDK token format is valid.",
"hint": "This does not check expiry or revocation online."}
@@ -189,15 +205,18 @@ def check_trust_store() -> CheckResult:
"hint": f"{_sentence(tls.RETIRED_FIX)}."}
return {"name": "Root CAs", "status": "OK",
"detail": "The system trust store has none of the distrusted root CAs.",
- "hint": "Keep the ca-certificates package up to date."}
+ "hint": "Keep the system's trusted root certificates up to date."}
def run_checks() -> tuple[CheckResult, ...]:
"""Collect independent checks, leaving device files and services unchanged."""
- if platform.system() != "Linux":
- return ({"name": "Platform", "status": "FAIL", "detail": "Doctor requires Linux.",
- "hint": "Run sudo musegadget doctor on the Linux gadget itself."},)
directory: Path = config.state_dir()
+ system = platform.system()
+ if system == "Windows":
+ return (check_pairing(directory), check_sdk_token(directory), check_network(), check_trust_store())
+ if system != "Linux":
+ return ({"name": "Platform", "status": "FAIL", "detail": "Doctor requires Linux or Windows.",
+ "hint": "Run musegadget doctor on the gadget itself."},)
return (check_pairing(directory), check_sdk_token(directory), check_service(),
check_bluetooth(), check_network(), check_trust_store())
diff --git a/linux/src/musegadget/executor.py b/linux/src/musegadget/executor.py
index c24773b15ae834cefe6648c30f52f6d167e57c26..20798c8998ebcd28b41f69987554d860246e5130 100644
--- a/linux/src/musegadget/executor.py
+++ b/linux/src/musegadget/executor.py
@@ -16,8 +16,8 @@
Shell commands, file operations and the owner's drop-in commands
(``musegadget.commands``) run in child processes as a separate,
-unprivileged account (``run_as``), never as the service account, which owns
-the device credentials. A command gets exactly the access that account has.
+unprivileged account (``run_as``) on Linux. Windows commands run under
+the account running the SDK.
"""
from __future__ import annotations
@@ -25,7 +25,6 @@ from __future__ import annotations
import json
import logging
import os
-import pwd
import select
import shutil
import signal
@@ -36,6 +35,11 @@ import time
from dataclasses import dataclass
from typing import Iterable
+if os.name == "nt":
+ from musegadget import windows_executor
+else:
+ import pwd
+
from musegadget import __version__, device_guide, reaper
from musegadget.commands import DropInCommand, InvalidCommand
from musegadget.link_client import (
@@ -61,7 +65,8 @@ SAFE_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
COMMAND_SPECS = {
"system.run": {
"description": (
- "Run a shell command on this Linux device with bash and return its "
+ f"Run a shell command on this {'Windows device with cmd.exe' if os.name == 'nt' else 'Linux device with bash'} "
+ "and return its "
"stdout, stderr and exit code. Output over 96 KiB per stream is "
"truncated."
),
@@ -113,17 +118,21 @@ COMMAND_SPECS = {
@dataclass(frozen=True)
class Account:
name: str
- uid: int
- gid: int
+ uid: int | None
+ gid: int | None
home: str
@classmethod
def lookup(cls, name: str) -> "Account":
+ if os.name == "nt":
+ raise ValueError("Windows commands run as the current account")
entry = pwd.getpwnam(name)
return cls(entry.pw_name, entry.pw_uid, entry.pw_gid, entry.pw_dir)
@classmethod
def current(cls) -> "Account":
+ if os.name == "nt":
+ return cls(windows_executor.current_user(), None, None, os.path.expanduser("~"))
entry = pwd.getpwuid(os.getuid())
return cls(entry.pw_name, entry.pw_uid, entry.pw_gid, entry.pw_dir)
@@ -191,6 +200,8 @@ class Executor:
# -- Child processes ------------------------------------------------------
def _child_options(self) -> dict:
+ if os.name == "nt":
+ return {"env": windows_executor.child_environment(self.account.home)}
env = {
"HOME": self.account.home,
"USER": self.account.name,
@@ -214,12 +225,14 @@ class Executor:
log.info("system.run as %s (timeout %ss)", self.account.name, timeout_s)
started = time.monotonic()
try:
- stdout, stderr, exit_code, timed_out = self._run_child(
- ["/bin/bash", "-c", command], cwd, timeout_s)
+ argv = (windows_executor.shell_command(command) if os.name == "nt"
+ else ["/bin/bash", "-c", command])
+ stdout, stderr, exit_code, timed_out = self._run_child(argv, cwd, timeout_s)
except OSError as exc:
return error(f"could not start command: {exc}")
- out, out_cut = _clip(stdout)
- err, err_cut = _clip(stderr)
+ encoding = "oem" if os.name == "nt" else "utf-8"
+ out, out_cut = _clip(stdout, encoding)
+ err, err_cut = _clip(stderr, encoding)
return ok({
"stdout": out,
"stderr": err,
@@ -257,13 +270,18 @@ class Executor:
return ok(payload)
return ok({"output": out, "truncated": True} if cut else {"output": out})
- def _run_child(self, argv: list, cwd: str, timeout_s: float,
+ def _run_child(self, argv: list | str, cwd: str, timeout_s: float,
stdin: bytes | None = None) -> tuple[bytes, bytes, int, bool]:
"""Run ``argv`` as the account. Returns stdout, stderr, exit code, timed out.
On timeout the whole process group is killed. Raises OSError if it
can't start.
"""
+ if os.name == "nt":
+ return windows_executor.run_child(
+ argv, cwd, self._child_options()["env"], stdin, timeout_s,
+ MAX_OUTPUT_BYTES + 1, DRAIN_S, KILL_GRACE_S,
+ )
proc = reaper.ReapingPopen(
argv, cwd=cwd,
stdin=subprocess.DEVNULL if stdin is None else subprocess.PIPE,
@@ -307,7 +325,7 @@ class Executor:
options["env"] = env
proc = reaper.run(
[sys.executable, "-m", "musegadget.fileops"], input=request.encode(),
- capture_output=True, timeout=60, cwd="/", **options,
+ capture_output=True, timeout=60, cwd=package_root if os.name == "nt" else "/", **options,
)
try:
return json.loads(proc.stdout)
@@ -402,9 +420,9 @@ def _kill_group(proc) -> None:
pass
-def _clip(data: bytes) -> tuple[str, bool]:
+def _clip(data: bytes, encoding: str = "utf-8") -> tuple[str, bool]:
cut = len(data) > MAX_OUTPUT_BYTES
- text = data[:MAX_OUTPUT_BYTES].decode("utf-8", errors="replace")
+ text = data[:MAX_OUTPUT_BYTES].decode(encoding, errors="replace")
# The budget is for the message, where json.dumps writes every non-ASCII
# character as a 6- or 12-byte escape and each undecodable byte became
# U+FFFD, so binary or non-Latin output can grow sixfold.
@@ -416,6 +434,8 @@ def _clip(data: bytes) -> tuple[str, bool]:
def device_health() -> dict:
health: dict = {"version": __version__, "hostname": socket.gethostname()}
+ if os.name == "nt":
+ return {**health, **windows_executor.health()}
try:
health["uptime_s"] = int(float(open("/proc/uptime").read().split()[0]))
except OSError:
diff --git a/linux/src/musegadget/fileops.py b/linux/src/musegadget/fileops.py
index a179843d228450fb3e32de5f60def4105a102b45..cf812aa80835bcccef9aa23c03541d2ce914f9f8 100644
--- a/linux/src/musegadget/fileops.py
+++ b/linux/src/musegadget/fileops.py
@@ -19,7 +19,7 @@ account that runs commands, so file access is limited by that account's
permissions rather than the service's. Takes a JSON request on stdin and
prints a JSON result.
-Writes land in a hidden partial file next to the target and publish it
+Writes land beside the target (in an owner-only directory on Windows) and publish
atomically once the final chunk arrives and its SHA-256 matches. Without
overwrite, publication refuses any existing destination directory entry; on a
filesystem without hard links, see ``_publish_without_link`` for the limit.
@@ -35,6 +35,7 @@ import json
import os
import stat
import sys
+from pathlib import Path
MAX_CHUNK_BYTES = 64 * 1024
@@ -56,7 +57,7 @@ def _partial_path(path: str) -> str:
def _require_absolute(path: object) -> str:
- if not isinstance(path, str) or not os.path.isabs(path):
+ if not isinstance(path, str) or not Path(path).is_absolute():
raise FileOpError("path must be an absolute path")
return path
@@ -119,13 +120,27 @@ def write(request: dict) -> dict:
if len(data) > MAX_CHUNK_BYTES:
raise FileOpError(f"chunk larger than {MAX_CHUNK_BYTES} bytes")
partial = _partial_path(path)
+ if offset == 0 and request.get("create_parents"):
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ if os.name == "nt":
+ from musegadget.windows_files import private_partial
+ try:
+ with private_partial(partial, start=offset == 0) as content:
+ return _write_chunk(request, path, content, offset, data)
+ except FileNotFoundError:
+ if offset != 0:
+ raise FileOpError("no write in progress; start at offset 0") from None
+ raise
+ return _write_chunk(request, path, partial, offset, data)
+
+
+def _write_chunk(request: dict, path: str, partial: str, offset: int, data: bytes) -> dict:
if offset == 0:
- if request.get("create_parents"):
- os.makedirs(os.path.dirname(path), exist_ok=True)
# Keep the content private while it arrives: the final mode, which
# may be wider, is applied just before the rename.
fd = os.open(partial, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
- os.fchmod(fd, 0o600) # a partial left by an earlier write keeps its mode
+ if os.name != "nt":
+ os.fchmod(fd, 0o600) # a partial left by an earlier write keeps its mode
else:
try:
fd = os.open(partial, os.O_WRONLY)
@@ -148,6 +163,16 @@ def write(request: dict) -> dict:
if expected and expected.lower() != digest.hexdigest():
os.unlink(partial)
raise FileOpError("sha256 mismatch; write discarded")
+ complete = {"path": path, "size": written, "sha256": digest.hexdigest(), "complete": True}
+ if os.name == "nt":
+ from musegadget.windows_files import publish
+
+ try:
+ publish(partial, path, request.get("overwrite", True))
+ except FileExistsError:
+ os.unlink(partial)
+ raise FileOpError("file exists and overwrite is false") from None
+ return complete
# Keep the permission bits of the file being replaced, such as 0600 or
# 0755, but not its setuid, setgid or sticky bits. A new file gets 0644,
# less the umask.
@@ -178,7 +203,7 @@ def write(request: dict) -> dict:
finally:
with contextlib.suppress(FileNotFoundError):
os.unlink(partial)
- return {"path": path, "size": written, "sha256": digest.hexdigest(), "complete": True}
+ return complete
OPERATIONS = {"read": read, "write": write}
diff --git a/linux/src/musegadget/identity.py b/linux/src/musegadget/identity.py
index 38e9f07299e304d12e72a495d8c0a1e3b6f89744..b1633ef6083110f07eca336acfc1752e7cb0431b 100644
--- a/linux/src/musegadget/identity.py
+++ b/linux/src/musegadget/identity.py
@@ -105,6 +105,26 @@ def generate_mac(random_bytes: Callable[[int], bytes] = os.urandom) -> str:
return ":".join(f"{b:02x}" for b in octets)
+class IdentityError(ValueError):
+ """The transferred identity is missing or does not match its pairing."""
+
+
+def load_existing(directory: Path | None = None) -> Identity:
+ """Read the original identity when the pairing was provisioned on another host."""
+ stored = config.load_json(config.IDENTITY_FILE, directory) or {}
+ mac = stored.get("mac")
+ if not isinstance(mac, str) or not _MAC_RE.fullmatch(mac):
+ raise IdentityError(f"Missing or invalid identity.json; {config.PAIRING_HINT}.")
+ identity = Identity(mac)
+ pairing = config.load_json(config.PAIRING_FILE, directory)
+ if pairing and "node_id" in pairing:
+ node_id = pairing["node_id"]
+ if (not isinstance(node_id, str) or not _NODE_ID_RE.fullmatch(node_id)
+ or not node_id.endswith("-" + identity.suffix)):
+ raise IdentityError("identity.json and pairing.json do not identify the same gadget.")
+ return identity.for_pairing(pairing)
+
+
def load_or_create(
directory: Path | None = None,
random_bytes: Callable[[int], bytes] = os.urandom,
diff --git a/linux/src/musegadget/link_client.py b/linux/src/musegadget/link_client.py
index eab0d018da3d11ed465e2dbc4d065efb5c8e6e0a..a30033c142d7ea70973342adc783c88d0d29af2d 100644
--- a/linux/src/musegadget/link_client.py
+++ b/linux/src/musegadget/link_client.py
@@ -35,6 +35,7 @@ import base64
import enum
import json
import logging
+import os
import re
import struct
import time
@@ -79,8 +80,9 @@ REQUEST_CHUNK_BYTES = 16 * 1024
MAX_INLINE_REQUEST_BYTES = 64 * 1024
# Matches JavaScript's encodeURIComponent, as the firmware does.
_URI_COMPONENT_SAFE = "-_.!~*'()"
-DEFAULT_MODEL_ID = "muse-gadget-linux"
-DEFAULT_MODEL_NAME = "Linux gadget"
+HOST_PLATFORM = "windows" if os.name == "nt" else "linux"
+DEFAULT_MODEL_ID = "muse-gadget-" + HOST_PLATFORM
+DEFAULT_MODEL_NAME = HOST_PLATFORM.capitalize() + " gadget"
MAX_MODEL_NAME_BYTES = 128
_MODEL_ID = re.compile(r"[a-z0-9-]{1,64}")
# Printable ASCII without " or \, so link.register never escapes it.
@@ -126,7 +128,7 @@ class DeviceDescription:
return {
"node_id": self.node_id,
"display_name": self.display_name,
- "platform": "linux",
+ "platform": HOST_PLATFORM,
"version": self.version,
"device_family": "gadget",
"model_id": self.model_id,
diff --git a/linux/src/musegadget/local_ipc.py b/linux/src/musegadget/local_ipc.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d2a0a007cc6583680fb994cf5b6ffa665885d2f
--- /dev/null
+++ b/linux/src/musegadget/local_ipc.py
@@ -0,0 +1,146 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Local message streams for the service and its CLI clients."""
+
+from __future__ import annotations
+
+import asyncio
+import hmac
+import os
+import secrets
+import socket
+import struct
+from pathlib import Path
+
+# For each Windows service instance DPAPI seals the port and its random key
+# together for the current user. Both peers must prove possession before any
+# application data is sent. Fresh nonces and distinct tags bind both proofs
+# to one connection and direction.
+_ENDPOINT = struct.Struct("!H32s")
+_NONCE_BYTES = 32
+_AUTH_TIMEOUT = 5
+
+
+def _temporary(path, flags):
+ # The last handle removes the endpoint, including on process termination.
+ return os.open(path, flags | os.O_TEMPORARY)
+
+
+class _WindowsListener(socket.socket):
+ """Keep the exclusive endpoint file for exactly the listener's lifetime."""
+
+ endpoint = None
+
+ def close(self):
+ try:
+ super().close()
+ finally:
+ if self.endpoint is not None:
+ self.endpoint.close()
+
+
+async def _authenticate(reader, writer, key, *, server):
+ nonce = secrets.token_bytes(_NONCE_BYTES)
+ if server:
+ client_nonce = await reader.readexactly(_NONCE_BYTES)
+ transcript = client_nonce + nonce
+ writer.write(nonce + hmac.digest(key, b"server" + transcript, "sha256"))
+ await writer.drain()
+ tag = b"client"
+ else:
+ writer.write(nonce)
+ await writer.drain()
+ transcript = nonce + await reader.readexactly(_NONCE_BYTES)
+ tag = b"server"
+ proof = await reader.readexactly(32)
+ if not hmac.compare_digest(proof, hmac.digest(key, tag + transcript, "sha256")):
+ raise ConnectionError("Muse local service authentication failed")
+ if not server:
+ writer.write(hmac.digest(key, b"client" + transcript, "sha256"))
+ await writer.drain()
+
+
+async def open_connection(path: Path, *, limit: int = 65536):
+ if os.name != "nt":
+ return await asyncio.open_unix_connection(str(path), limit=limit)
+
+ import pywintypes
+ import win32con
+ import win32crypt
+ import win32file
+
+ try:
+ share = win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE
+ endpoint = win32file.CreateFile(str(path), win32con.GENERIC_READ, share, None,
+ win32con.OPEN_EXISTING, 0, None)
+ try:
+ _, sealed = win32file.ReadFile(endpoint, 4096)
+ finally:
+ endpoint.Close()
+ _, data = win32crypt.CryptUnprotectData(sealed, None, None, None, 1)
+ port, key = _ENDPOINT.unpack(data)
+ except (pywintypes.error, struct.error) as exc:
+ raise ConnectionError("Cannot read the local service endpoint for this Windows user") from exc
+ reader, writer = await asyncio.open_connection("127.0.0.1", port, limit=limit)
+ try:
+ await asyncio.wait_for(_authenticate(reader, writer, key, server=False), _AUTH_TIMEOUT)
+ except asyncio.IncompleteReadError as exc:
+ writer.close()
+ raise ConnectionError("Muse local service closed before authentication") from exc
+ except BaseException:
+ writer.close()
+ raise
+ return reader, writer
+
+
+async def start_server(handle, path: Path, *, limit: int, gid: int | None):
+ if os.name != "nt":
+ path.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
+ if path.exists():
+ path.unlink()
+ server = await asyncio.start_unix_server(handle, str(path), limit=limit)
+ if gid is not None:
+ os.chown(path, 0, gid)
+ os.chmod(path, 0o660)
+ return server
+
+ import win32crypt
+
+ key = secrets.token_bytes(32)
+
+ async def accept(reader, writer):
+ try:
+ await asyncio.wait_for(_authenticate(reader, writer, key, server=True), _AUTH_TIMEOUT)
+ except (OSError, EOFError, asyncio.TimeoutError):
+ return
+ else:
+ await handle(reader, writer)
+ finally:
+ writer.close()
+
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ listener = _WindowsListener(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen()
+ data = _ENDPOINT.pack(listener.getsockname()[1], key)
+ sealed = win32crypt.CryptProtectData(data, "Muse local service", None, None, None, 1)
+ listener.endpoint = open(path, "xb", buffering=0, opener=_temporary)
+ listener.endpoint.write(sealed)
+ return await asyncio.start_server(accept, sock=listener, limit=limit)
+ except BaseException:
+ listener.close()
+ raise
diff --git a/linux/src/musegadget/muse_api.py b/linux/src/musegadget/muse_api.py
index 799f54e27646e5f4b2f01c32f89e3e0132bc2289..48aae067064bf1612c01f2954776b5a5b227ce10 100644
--- a/linux/src/musegadget/muse_api.py
+++ b/linux/src/musegadget/muse_api.py
@@ -44,14 +44,16 @@ def api_root(api_url_v2: str = "") -> str:
def user_agent() -> str:
details = []
- try:
- model = Path("/proc/device-tree/model").read_text(errors="replace")
- model = model.replace("\x00", "").strip()
- if model:
- details.append(model)
- except OSError:
- pass
- details.append(f"{platform.system()} {platform.machine()}".strip())
+ system = platform.system()
+ if system == "Linux":
+ try:
+ model = Path("/proc/device-tree/model").read_text(errors="replace")
+ model = model.replace("\x00", "").strip()
+ if model:
+ details.append(model)
+ except OSError:
+ pass
+ details.append(f"{system} {platform.machine()}".strip())
return (
f"musegadget/{__version__} ({'; '.join(d for d in details if d)}) "
f"Python/{platform.python_version()}"
diff --git a/linux/src/musegadget/pair.py b/linux/src/musegadget/pair.py
index fd5e839426923f0d84491b65ae1786831d1310bc..2aae32113b481615842d1b4a3c58060f5ab34a39 100644
--- a/linux/src/musegadget/pair.py
+++ b/linux/src/musegadget/pair.py
@@ -18,6 +18,7 @@ from __future__ import annotations
import enum
import logging
+import os
import threading
import time
from dataclasses import dataclass
@@ -106,6 +107,8 @@ def pair(*, on_open: Callable[[SetupWindow], None], force: bool = False,
Raises ``tls.TrustStoreError`` first if the system trust store isn't
safe to use, since pairing checks the device token with the Muse API.
"""
+ if os.name == "nt":
+ raise NotImplementedError(f"Bluetooth pairing requires Linux; {config.PAIRING_HINT}.")
tls.client_context()
# BleServer needs D-Bus, which only a device that pairs has to install.
from musegadget.ble_server import BleServer
diff --git a/linux/src/musegadget/reaper.py b/linux/src/musegadget/reaper.py
index 68204b3b9dfd424433ff9d40aa34d2404f5e9402..dd597f4572cc514770ac435f338af6b122c8f254 100644
--- a/linux/src/musegadget/reaper.py
+++ b/linux/src/musegadget/reaper.py
@@ -194,7 +194,7 @@ _reaper: ChildReaper | None = None
def start_child_reaper() -> bool:
"""Start the orphan reaper if this process is PID 1. Returns started."""
global _reaper
- if os.getpid() != 1 or not hasattr(os, "waitpid"):
+ if os.name == "nt" or os.getpid() != 1 or not hasattr(os, "waitpid"):
return False
if _reaper is None:
_reaper = ChildReaper()
diff --git a/linux/src/musegadget/rtc/opus.py b/linux/src/musegadget/rtc/opus.py
index aca85acf1826ffd00295cf5b35d85161bd9fe3c1..08090c70a4a0f3edf1a28782c44fa906f2268408 100644
--- a/linux/src/musegadget/rtc/opus.py
+++ b/linux/src/musegadget/rtc/opus.py
@@ -18,6 +18,7 @@ from __future__ import annotations
import ctypes
import ctypes.util
+import sys
_APPLICATION_VOIP = 2048
_SET_BITRATE = 4002
@@ -38,7 +39,12 @@ class OpusUnavailable(RuntimeError):
def _load() -> ctypes.CDLL:
- candidates = [ctypes.util.find_library("opus"), "libopus.so.0", "libopus.dylib", *_SYSTEM_PATHS]
+ if sys.platform == "win32":
+ candidates = [ctypes.util.find_library(name) for name in ("opus", "libopus", "libopus-0")]
+ install_hint = "add the folder containing your matching Opus DLL to PATH"
+ else:
+ candidates = [ctypes.util.find_library("opus"), "libopus.so.0", "libopus.dylib", *_SYSTEM_PATHS]
+ install_hint = "install it (e.g. apt install libopus0)"
for name in filter(None, candidates):
try:
lib = ctypes.CDLL(name)
@@ -46,7 +52,7 @@ def _load() -> ctypes.CDLL:
except OSError:
continue
else:
- raise OpusUnavailable("libopus not found; install it (e.g. apt install libopus0)")
+ raise OpusUnavailable(f"libopus could not be loaded; {install_hint}")
lib.opus_encoder_create.restype = ctypes.c_void_p
lib.opus_encoder_create.argtypes = [ctypes.c_int32, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)]
lib.opus_encode.restype = ctypes.c_int32
diff --git a/linux/src/musegadget/service.py b/linux/src/musegadget/service.py
index 9325df4dcfe81c7fbb91488a62b0a934c84cc81a..c82cb6192b86b5e2584cf57372f59ed0576c134b 100644
--- a/linux/src/musegadget/service.py
+++ b/linux/src/musegadget/service.py
@@ -29,12 +29,11 @@ import json
import logging
import os
import re
-import signal
import socket
import time
from dataclasses import dataclass, field
-from musegadget import __version__, config, device_guide, muse_api, reaper, tls
+from musegadget import __version__, config, device_guide, local_ipc, muse_api, reaper, tls
from musegadget.executor import Executor
from musegadget.identity import Identity
from musegadget.link_client import (
@@ -42,6 +41,7 @@ from musegadget.link_client import (
LinkSession, Outcome, acknowledgement, check_image, check_model,
)
from musegadget.muse_turn import MuseTurn, _acknowledged_message_ids
+from musegadget.signals import stop_on_signals
log = logging.getLogger(__name__)
@@ -123,12 +123,13 @@ class Service:
while not self._stop.is_set():
pairing = config.load_json(config.PAIRING_FILE)
if not pairing:
- log.info("not paired; run `musegadget pair` to set up")
+ log.info("not paired; %s", config.PAIRING_HINT)
await self._sleep(UNPAIRED_POLL_S)
continue
problem = config.pairing_problem(pairing)
if problem is not None:
- log.warning("%s Run `musegadget pair --force` to pair again.", problem)
+ hint = config.PAIRING_HINT if os.name == "nt" else "run `musegadget pair --force` to pair again"
+ log.warning("%s %s.", problem, hint)
await self._sleep(UNPAIRED_POLL_S)
continue
# The node id this pairing was made for (identity.py): what
@@ -166,7 +167,7 @@ class Service:
return
if outcome is Outcome.UNPAIRED:
config.delete_json(config.PAIRING_FILE)
- log.warning("pairing removed; run `musegadget pair` to set up again")
+ log.warning("pairing removed; %s", config.PAIRING_HINT)
continue
healthy = lasted >= HEALTHY_SESSION_S
if healthy:
@@ -234,8 +235,8 @@ class Service:
return
if paired != config.sdk_token_hint(self.sdk_token):
self._sdk_token_change_warned = True
- log.warning("paired with SDK token %s, not this one; run `musegadget pair --force` "
- "to use it", paired)
+ hint = config.PAIRING_HINT if os.name == "nt" else "run `musegadget pair --force` to use it"
+ log.warning("paired with SDK token %s, not this one; %s", paired, hint)
async def _maybe_refresh(self, pairing: dict, force: bool = False) -> dict | None:
"""Return current pairing, rotating tokens first if they are due.
@@ -267,7 +268,7 @@ class Service:
return pairing
if status == 401:
config.delete_json(config.PAIRING_FILE)
- log.error("pairing revoked; run `musegadget pair` to set up again")
+ log.error("pairing revoked; %s", config.PAIRING_HINT)
return None
# Transient failure: keep using the current token while it still works.
return None if force else pairing
@@ -282,22 +283,17 @@ class Service:
(``{"mime_type", "data_base64", "filename"}``, see
``LinkSession.send_image``) and ``"wait"`` (seconds) to hold the
connection open for the Muse's answer, and gets one JSON line back
- (with ``"reply"`` when it waited). Only root and the command
- account's group can connect.
+ (with ``"reply"`` when it waited). Access is limited to the Windows
+ account running the service, or to root and the command account's
+ group on Linux.
``{"op": "subscribe_chat", "session_id": "..."}`` instead opens an
NDJSON stream of ``type: ready``, ``type: chat_event`` (with ``event``)
and terminal ``type: error`` (with ``error``) records. The session ID
is optional. A subscription ends on client or transport disconnect.
"""
- path.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
- if path.exists():
- path.unlink()
- server = await asyncio.start_unix_server(self._handle_local, str(path),
- limit=MAX_LOCAL_REQUEST)
- if os.geteuid() == 0:
- os.chown(path, 0, self.executor.account.gid)
- os.chmod(path, 0o660)
+ gid = self.executor.account.gid if os.name != "nt" and os.geteuid() == 0 else None
+ server = await local_ipc.start_server(self._handle_local, path, limit=MAX_LOCAL_REQUEST, gid=gid)
log.info("accepting messages on %s", path)
return server
@@ -714,14 +710,12 @@ async def _discard_line(reader, timeout_s: float = 10) -> None:
def run_service(identity: Identity, executor: Executor, sdk_token: str | None = None) -> None:
async def main() -> None:
service = Service(identity=identity, executor=executor, sdk_token=sdk_token)
- loop = asyncio.get_running_loop()
- for signum in (signal.SIGTERM, signal.SIGINT):
- loop.add_signal_handler(signum, service.stop)
- server = await service.serve_local(config.socket_path())
- try:
- await service.run()
- finally:
- server.close()
+ with stop_on_signals(service.stop):
+ server = await service.serve_local(config.socket_path())
+ try:
+ await service.run()
+ finally:
+ server.close()
reaper.start_child_reaper()
asyncio.run(main())
diff --git a/linux/src/musegadget/signals.py b/linux/src/musegadget/signals.py
new file mode 100644
index 0000000000000000000000000000000000000000..1215e2cce711d3dce88b4ba9c727bada75faa3a8
--- /dev/null
+++ b/linux/src/musegadget/signals.py
@@ -0,0 +1,38 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Deliver console interrupts to the running asyncio task and restore handlers on exit."""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import signal
+from contextlib import ExitStack, contextmanager
+from typing import Callable, Iterator
+
+
+@contextmanager
+def stop_on_signals(callback: Callable[[], None]) -> Iterator[None]:
+ loop = asyncio.get_running_loop()
+ with ExitStack() as cleanup:
+ for signum in (signal.SIGINT, signal.SIGTERM):
+ if os.name == "nt":
+ # ProactorEventLoop has no add_signal_handler.
+ previous = signal.signal(signum, lambda *_: loop.call_soon_threadsafe(callback))
+ cleanup.callback(signal.signal, signum, previous)
+ else:
+ loop.add_signal_handler(signum, callback)
+ cleanup.callback(loop.remove_signal_handler, signum)
+ yield
diff --git a/linux/src/musegadget/terminal_chat.py b/linux/src/musegadget/terminal_chat.py
index 6e042c5bf3703c9b157dc2f555d042859bfbd700..0e4491127405156b50b1e4172d80fb3df75755ae 100644
--- a/linux/src/musegadget/terminal_chat.py
+++ b/linux/src/musegadget/terminal_chat.py
@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""Unprivileged text chat through the running service's Unix socket."""
+"""Unprivileged text chat through the running service's local connection."""
from __future__ import annotations
import asyncio
@@ -24,7 +24,7 @@ import signal
import sys
import time
-from musegadget import config
+from musegadget import config, local_ipc
from musegadget.link_client import acknowledgement, printable
from musegadget.muse_turn import (AgentStatus, MuseTurn, Reply, _acknowledged_message_ids,
_strip_controls, _update_reply)
@@ -178,7 +178,7 @@ async def _record(reader):
async def _send(path, message, session_id):
- reader, writer = await asyncio.open_unix_connection(str(path), limit=MAX_RECORD)
+ reader, writer = await local_ipc.open_connection(path, limit=MAX_RECORD)
try:
request = {"message": message}
if session_id:
@@ -195,7 +195,7 @@ async def run_chat(session_id=None, *, input_reader=None, output=None):
"""Run until user exit or a connection error; never open credential files."""
output = output or sys.stdout
path = config.socket_path()
- reader, writer = await asyncio.open_unix_connection(str(path), limit=MAX_RECORD)
+ reader, writer = await local_ipc.open_connection(path, limit=MAX_RECORD)
tasks = []
messages = asyncio.Queue(maxsize=MAX_QUEUED_MESSAGES)
sending = False
@@ -240,14 +240,19 @@ async def run_chat(session_id=None, *, input_reader=None, output=None):
ready = await asyncio.wait_for(_record(reader), 90)
if ready.get("type") != "ready":
raise ConnectionError("Service does not support terminal chat; update and restart it")
+ term = os.environ.get("TERM")
+ use_screen = term != "dumb" and (term is not None or os.name == "nt")
if (input_reader is None and sys.stdin.isatty() and output is sys.stdout
- and output.isatty() and os.environ.get("TERM", "dumb") != "dumb"):
+ and output.isatty() and use_screen):
try:
display = TerminalDisplay()
except curses.error:
pass # Missing terminal capabilities: retain the plain-text client.
else:
show_status("Muse is ready · /quit or /exit · /clear")
+ if input_reader is None and isinstance(display, PlainDisplay) and os.name == "nt":
+ from musegadget.windows_input import WindowsInput
+ input_reader = WindowsInput(sys.stdin, MAX_INPUT)
if input_reader is None and isinstance(display, PlainDisplay):
input_reader = asyncio.StreamReader(limit=MAX_INPUT)
# The pipe transport makes stdin non-blocking (a terminal shares
@@ -406,6 +411,11 @@ async def run_until_interrupted(session_id=None):
"""
loop = asyncio.get_running_loop()
task = asyncio.current_task()
+ if os.name == "nt":
+ from musegadget.signals import stop_on_signals
+ with stop_on_signals(task.cancel):
+ await run_chat(session_id)
+ return
def interrupt():
loop.remove_signal_handler(signal.SIGINT)
diff --git a/linux/src/musegadget/tls.py b/linux/src/musegadget/tls.py
index 33efa4fd8d45e7173e4bb787555393090574c077..47c4241b20baef383380ebae0a1d7e54a9e3661f 100644
--- a/linux/src/musegadget/tls.py
+++ b/linux/src/musegadget/tls.py
@@ -102,7 +102,8 @@ _HASH_NAME = re.compile(r"[0-9a-f]{8}\.r?[0-9]+", re.I)
_URI = re.compile(r"(?:^|:)[A-Za-z][A-Za-z0-9+.-]*:/") # a scheme, as in file:///…
-FIX = "update your ca-certificates package, then restart musegadget"
+FIX = ("update the Windows trusted root certificates, then restart musegadget" if os.name == "nt"
+ else "update your ca-certificates package, then restart musegadget")
RETIRED_FIX = ("to stop trusting a retired root, deselect it in the system trust store "
"(see \"Root CAs\" in the musegadget README)")
@@ -114,7 +115,8 @@ class TrustStoreError(Exception):
def check_trust_store() -> list[str] | None:
"""Names of the distrusted roots in the system trust store, or None if it can't be read.
- Reads what OpenSSL uses by default: the CA file and the hash-named files
+ Checks the Windows CA and ROOT stores loaded by CPython on Windows.
+ Also reads what OpenSSL uses by default: the CA file and the hash-named files
of the CA directory (``SSL_CERT_FILE`` and ``SSL_CERT_DIR`` override
them; ``SSL_CERT_DIR`` may list several, separated as in ``PATH``).
Other files there, such as a distro's bundle with its own trust
@@ -128,6 +130,19 @@ def check_trust_store() -> list[str] | None:
paths = ssl.get_default_verify_paths()
store = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
readable = False
+ native_roots = set()
+ if os.name == "nt":
+ # CPython adds both Windows stores to its OpenSSL default locations.
+ try:
+ for location in ("CA", "ROOT"):
+ for der, encoding, trust in ssl.enum_certificates(location):
+ if encoding == "x509_asn" and (trust is True or ssl.Purpose.SERVER_AUTH.oid in trust):
+ readable = True
+ name = distrusted_name(der)
+ if name:
+ native_roots.add(name)
+ except OSError:
+ return None
if paths.cafile:
try:
store.load_verify_locations(cafile=paths.cafile)
@@ -136,7 +151,12 @@ def check_trust_store() -> list[str] | None:
readable = True
variable = getattr(paths, "openssl_capath_env", None)
listed = os.environ.get(variable) if variable else None
- if os.environ.get("SSL_CERT_URI") or (listed and _URI.search(listed)):
+ if os.name == "nt":
+ has_uri = any(_URI.match(part) and not os.path.splitdrive(part)[0]
+ for part in (listed or "").split(os.pathsep))
+ else:
+ has_uri = listed and _URI.search(listed)
+ if os.environ.get("SSL_CERT_URI") or has_uri:
return None # an OpenSSL store URI, which this doesn't read
directories = listed.split(os.pathsep) if listed else ([paths.capath] if paths.capath else [])
for directory in directories:
@@ -160,8 +180,8 @@ def check_trust_store() -> list[str] | None:
readable = True
if not readable:
return None
- return sorted({name for der in store.get_ca_certs(binary_form=True)
- if (name := distrusted_name(der))})
+ return sorted(native_roots | {name for der in store.get_ca_certs(binary_form=True)
+ if (name := distrusted_name(der))})
def trust_store_problem() -> str | None:
diff --git a/linux/src/musegadget/video_call.py b/linux/src/musegadget/video_call.py
index 24276bebb545c26cca2bbaabbba4d3855b445911..defacfa280864499a1975a69b8cf0e323fdf819b 100644
--- a/linux/src/musegadget/video_call.py
+++ b/linux/src/musegadget/video_call.py
@@ -43,8 +43,8 @@ from musegadget.rtc.join import ENDPOINT_TYPES, build_join, parse_join_response
from musegadget.rtc.media import MediaSession
from musegadget.rtc.opus import ensure_available as ensure_opus
from musegadget.voice_audio import Pcm48To24, _upsample24_to_48
-from musegadget.voice_call import (CATCH_UP_RATE, FRAME_BYTES, MAX_PLAYBACK_BYTES, READY_TIMEOUT_S,
- SAMPLE_RATE, SETTLE_SECONDS, pcm_rms, positive_seconds)
+from musegadget.voice_call import (CATCH_UP_RATE, FRAME_BYTES, MAX_PLAYBACK_BYTES, MAX_PLAYBACK_CATCH_UP_S,
+ READY_TIMEOUT_S, SAMPLE_RATE, SETTLE_SECONDS, pcm_rms, positive_seconds)
log = logging.getLogger(__name__)
FRAME_48K_BYTES = 1920 # 20 ms of mono 48 kHz PCM16
@@ -226,7 +226,7 @@ class VideoCall:
if audible:
self._playing_until = time.monotonic() + duration + SETTLE_SECONDS
self._activity = time.monotonic()
- deadline = max(deadline + duration, time.monotonic() - 0.2)
+ deadline = max(deadline + duration, time.monotonic() - MAX_PLAYBACK_CATCH_UP_S)
await asyncio.sleep(max(0.0, deadline - time.monotonic()))
def _video(self, unit: bytes, size) -> None:
diff --git a/linux/src/musegadget/voice_call.py b/linux/src/musegadget/voice_call.py
index 34cdf7b1f42a85cde2a986774bc809368e12d28a..cb8e81736599252df744b173f0f9058770b4a782 100644
--- a/linux/src/musegadget/voice_call.py
+++ b/linux/src/musegadget/voice_call.py
@@ -61,6 +61,7 @@ TRANSPORT_READY_TIMEOUT_S = 35
READY_TIMEOUT_S = 35
MAX_AUDIO_BYTES = SAMPLE_RATE * 2 * 4
MAX_PLAYBACK_BYTES = SAMPLE_RATE * 2 * 5
+MAX_PLAYBACK_CATCH_UP_S = 0.2 # Stay within the live sink's eight-frame queue after a stall.
# Words held with an unconfirmed reply have their own budget, so observing a
# call never shrinks its held audio, and a count bound covers tiny entries.
MAX_HELD_TEXT_BYTES = 64 * 1024
@@ -874,9 +875,7 @@ class VoiceCall:
self._quiet_left = None if not muted and rms >= 300 else self._quiet_left - len(pcm)
duration = len(pcm) / (SAMPLE_RATE * 2)
queued = getattr(source, "backlog_bytes", None)
- if queued is None:
- next_send = time.monotonic() + duration
- else:
+ if queued is not None:
# Queued capture (pre-roll and audio from before the call was
# ready) catches up instead of arriving later and later: pace
# against a wall-clock schedule, so send latency never adds up,
@@ -884,11 +883,19 @@ class VoiceCall:
# schedule keeps at most one frame of credit.
step = duration / CATCH_UP_RATE if queued > FRAME_BYTES else duration
next_send = max(next_send + step, time.monotonic() - duration)
+ elif realtime and not eof:
+ # Match the capture clock even when a timer wakes late. After
+ # a hold, discard timing credit for the microphone's dropped frames.
+ next_send = max(next_send + duration, time.monotonic())
+ else:
+ next_send = time.monotonic() + duration
async def _play(self) -> None:
+ deadline = time.monotonic()
while True:
if not self._playback:
await asyncio.sleep(0.01)
+ deadline = time.monotonic()
continue
pcm, audible, response_id = self._playback[0]
pending = self._output.write(pcm)
@@ -900,10 +907,13 @@ class VoiceCall:
self._pending_output.append((len(pcm), response_id))
self._trim_output(pending)
duration = len(pcm) / (SAMPLE_RATE * 2)
+ now = time.monotonic()
if audible:
- self._playing_until = time.monotonic() + duration + SETTLE_SECONDS
- self._activity = time.monotonic()
- await asyncio.sleep(duration)
+ self._playing_until = now + duration + SETTLE_SECONDS
+ self._activity = now
+ # Pace against sample time so timer rounding doesn't add latency to every frame.
+ deadline = max(deadline + duration, now - MAX_PLAYBACK_CATCH_UP_S)
+ await asyncio.sleep(max(0.0, deadline - now))
async def _watchdog(self) -> None:
while True:
diff --git a/linux/src/musegadget/voice_video.py b/linux/src/musegadget/voice_video.py
index cc4de30c67231327bbb8bf540fdb076644ede3ce..c306d852545495176c1c991b709e8d5772027b64 100644
--- a/linux/src/musegadget/voice_video.py
+++ b/linux/src/musegadget/voice_video.py
@@ -54,6 +54,9 @@ class VideoStream:
def __init__(self, fd: int, *, max_pending: int = 8, close_fd: bool = False) -> None:
if max_pending < 1:
raise ValueError("max_pending must be positive")
+ if os.name == "nt":
+ import msvcrt
+ msvcrt.setmode(fd, os.O_BINARY)
self._fd, self._close_fd = fd, close_fd
self._pending = queue.Queue(maxsize=max_pending)
self.written = 0
@@ -166,7 +169,7 @@ def player_command(name: str = "auto") -> list:
class VideoPlayer:
"""Runs a player that reads raw H.264 on standard input and streams units to it."""
- def __init__(self, command: list) -> None:
+ def __init__(self, command: list | str) -> None:
self._process = reaper.ReapingPopen(command, stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
diff --git a/linux/src/musegadget/wakeword.py b/linux/src/musegadget/wakeword.py
index cd98628bfc79bdddfc7390cfa81392e1b87705e6..da028d1cf42e1d983656245f5b7d8cf907ef43d3 100644
--- a/linux/src/musegadget/wakeword.py
+++ b/linux/src/musegadget/wakeword.py
@@ -16,7 +16,7 @@
feed() consumes 16 kHz mono signed-16-bit little-endian PCM, including split
samples, and reports any wake while consuming the entire chunk. The work is
-done by libmuse_wakeword.so (linux/wakeword/build.sh): TensorFlow Lite Micro's
+done by the native library built by linux/wakeword/build.sh: TensorFlow Lite Micro's
microfrontend, the int8 model through ExecuTorch's ESP-NN delegate, and the
detector, compiled from esp32/components/muse_wakeword. No Python packages,
threads or network: importing this module loads nothing; construction loads
@@ -47,6 +47,7 @@ _WAKE = 1 # WW_EVENT_WAKE
_SAMPLE_RATE = 16000
_MAX_FRAMES = 16000 # one second per native call
_MAX_MODEL_BYTES = 4 * 1024 * 1024
+_LIBRARY_NAME = "muse_wakeword.dll" if sys.platform == "win32" else "libmuse_wakeword.so"
class _Config(ctypes.Structure):
@@ -68,9 +69,9 @@ def _candidates() -> list[Path]:
return [Path(override).expanduser().absolute()]
return [
# The copy linux/wakeword/setup.sh installs into its environment.
- Path(sys.prefix) / "lib" / "musegadget" / "libmuse_wakeword.so",
+ Path(sys.prefix) / "lib" / "musegadget" / _LIBRARY_NAME,
# A source checkout run in place: what linux/wakeword/build.sh builds.
- Path(__file__).resolve().parents[2] / "wakeword" / "build" / "libmuse_wakeword.so",
+ Path(__file__).resolve().parents[2] / "wakeword" / "build" / _LIBRARY_NAME,
]
@@ -81,7 +82,8 @@ def _read_model(path: Path) -> bytes:
substitute it for a requested file."""
# Non-blocking open, so a FIFO or device can't stall it, and the type
# checked on that descriptor before anything is read.
- fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | getattr(os, "O_CLOEXEC", 0))
+ flags = os.O_BINARY if os.name == "nt" else os.O_NONBLOCK | getattr(os, "O_CLOEXEC", 0)
+ fd = os.open(path, os.O_RDONLY | flags)
with open(fd, "rb", closefd=True) as f:
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise OSError("not a regular file")
@@ -121,9 +123,10 @@ def _load_library() -> ctypes.CDLL:
return library
except (OSError, AttributeError) as exc:
failures.append(f"{path}: {exc}")
+ build_script = "build.sh in Git Bash" if sys.platform == "win32" else "setup.sh"
raise WakeWordUnavailableError(
- "Hey Muse library unavailable. Build it with linux/wakeword/setup.sh, "
- "or set MUSE_WAKEWORD_LIBRARY to libmuse_wakeword.so. " + "; ".join(failures)
+ f"Hey Muse library unavailable. Build it with linux/wakeword/{build_script}, "
+ f"or set MUSE_WAKEWORD_LIBRARY to {_LIBRARY_NAME}. " + "; ".join(failures)
)
diff --git a/linux/src/musegadget/wakeword_check.py b/linux/src/musegadget/wakeword_check.py
index 9017d41521a6923aa4eb17615d6832ebe38fced6..553f648d1f7610b01a097057d871d971584b574c 100644
--- a/linux/src/musegadget/wakeword_check.py
+++ b/linux/src/musegadget/wakeword_check.py
@@ -29,6 +29,7 @@ import json
import math
import platform
import struct
+import sys
import warnings
from importlib import metadata
@@ -43,9 +44,16 @@ def audio_prerequisites() -> dict:
except metadata.PackageNotFoundError as exc:
raise CompatibilityError("Install musegadget[voice] in this environment") from exc
try:
- library = ctypes.CDLL(ctypes.util.find_library("portaudio") or "libportaudio.so.2")
- library.Pa_GetVersion
- except (OSError, AttributeError) as exc:
+ if sys.platform == "win32":
+ # The Windows wheel selects a bundled PortAudio DLL matching Python.
+ import sounddevice
+ sounddevice.get_portaudio_version()
+ else:
+ library = ctypes.CDLL(ctypes.util.find_library("portaudio") or "libportaudio.so.2")
+ library.Pa_GetVersion
+ except (OSError, ImportError, AttributeError) as exc:
+ if sys.platform == "win32":
+ raise CompatibilityError("PortAudio is unavailable; install the sounddevice Windows wheel") from exc
raise CompatibilityError(
"PortAudio is unavailable; install the distro prerequisites explicitly "
"with setup.sh --install-system-packages"
diff --git a/linux/src/musegadget/windows_executor.py b/linux/src/musegadget/windows_executor.py
new file mode 100644
index 0000000000000000000000000000000000000000..bced1595aea3cfb98342aa02ba47d570a5bca7cb
--- /dev/null
+++ b/linux/src/musegadget/windows_executor.py
@@ -0,0 +1,129 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Windows command processes and device health."""
+
+from __future__ import annotations
+
+import msvcrt
+import os
+import shutil
+import subprocess
+import time
+
+import psutil
+import pywintypes
+import win32api
+import win32con
+import win32file
+import win32job
+import win32pipe
+import winerror
+
+
+def current_user() -> str:
+ return win32api.GetUserName()
+
+
+def child_environment(home: str) -> dict:
+ names = ("SYSTEMROOT", "WINDIR", "PATH", "PATHEXT", "COMSPEC", "TEMP", "TMP",
+ "APPDATA", "LOCALAPPDATA", "USERDOMAIN", "USERNAME", "HOMEDRIVE",
+ "HOMEPATH", "PROGRAMDATA", "PROGRAMFILES", "PROGRAMFILES(X86)")
+ return {**{key: os.environ[key] for key in names if key in os.environ},
+ "USERPROFILE": home, "HOME": home}
+
+
+def shell_command(command: str) -> str:
+ # cmd's /s /c consumes a raw command line. list2cmdline would escape its
+ # embedded quotes according to the C runtime's different argument rules.
+ shell = os.path.join(win32api.GetSystemDirectory(), "cmd.exe")
+ return f'"{shell}" /d /s /c "{command}"'
+
+
+def _read_pipe(pipe, buffer: bytearray, limit: int) -> bool:
+ try:
+ _, available, _ = win32pipe.PeekNamedPipe(msvcrt.get_osfhandle(pipe.fileno()), 0)
+ except pywintypes.error as exc:
+ if exc.winerror in (winerror.ERROR_BROKEN_PIPE, winerror.ERROR_NO_DATA):
+ return False
+ raise
+ if not available:
+ return False
+ data = os.read(pipe.fileno(), min(available, 65536))
+ buffer.extend(data[:limit - len(buffer)])
+ return bool(data)
+
+
+def run_child(argv: list | str, cwd: str, env: dict, stdin: bytes | None, timeout: float,
+ limit: int, drain_seconds: float, kill_seconds: float) -> tuple[bytes, bytes, int, bool]:
+ # Assign the suspended child before its first instruction so all descendants
+ # belong to the same timeout job. Popen restricts inherited handles to this
+ # child's stdio even when multiple commands are started concurrently.
+ job = win32job.CreateJobObject(None, "")
+ try:
+ with subprocess.Popen(
+ argv, cwd=cwd, env=env, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ stdin=subprocess.DEVNULL if stdin is None else subprocess.PIPE,
+ creationflags=win32con.CREATE_SUSPENDED | subprocess.CREATE_NO_WINDOW,
+ ) as proc:
+ try:
+ handle = win32api.OpenProcess(win32con.PROCESS_SET_QUOTA | win32con.PROCESS_TERMINATE,
+ False, proc.pid)
+ try:
+ win32job.AssignProcessToJobObject(job, handle)
+ finally:
+ handle.Close()
+ pending = memoryview(stdin or b"")
+ if proc.stdin:
+ input_handle = msvcrt.get_osfhandle(proc.stdin.fileno())
+ win32pipe.SetNamedPipeHandleState(input_handle, win32pipe.PIPE_NOWAIT, None, None)
+ psutil.Process(proc.pid).resume()
+ out, err = bytearray(), bytearray()
+ deadline = time.monotonic() + timeout
+ timed_out = False
+ while proc.poll() is None:
+ if time.monotonic() >= deadline:
+ timed_out = True
+ win32job.TerminateJobObject(job, 1)
+ proc.wait(kill_seconds)
+ break
+ got_out = _read_pipe(proc.stdout, out, limit)
+ got_err = _read_pipe(proc.stderr, err, limit)
+ sent = 0
+ if proc.stdin and not proc.stdin.closed:
+ if pending:
+ try:
+ _, sent = win32file.WriteFile(input_handle, pending[:4096])
+ pending = pending[sent:]
+ except pywintypes.error as exc:
+ if exc.winerror not in (winerror.ERROR_BROKEN_PIPE, winerror.ERROR_NO_DATA):
+ raise
+ pending = pending[:0]
+ if not pending:
+ proc.stdin.close()
+ if not (got_out or got_err or sent):
+ time.sleep(0.01)
+ # Background descendants can keep a pipe open after the command
+ # exits. Drain queued data without waiting on those descendants.
+ deadline = time.monotonic() + drain_seconds
+ while time.monotonic() < deadline:
+ got_out = _read_pipe(proc.stdout, out, limit)
+ got_err = _read_pipe(proc.stderr, err, limit)
+ if not (got_out or got_err):
+ break
+ return bytes(out), bytes(err), proc.returncode, timed_out
+ except BaseException:
+ proc.kill() # covers failure before job assignment as well
+ win32job.TerminateJobObject(job, 1)
+ proc.wait(kill_seconds)
+ raise
+ finally:
+ job.Close()
+
+
+def health() -> dict:
+ memory = psutil.virtual_memory()
+ disk = shutil.disk_usage(win32api.GetSystemDirectory())
+ return {"uptime_s": int(time.time() - psutil.boot_time()),
+ "memory_mb": {"total": memory.total // (1 << 20), "available": memory.available // (1 << 20)},
+ "disk_gb": {"total": round(disk.total / 1e9, 1), "free": round(disk.free / 1e9, 1)}}
diff --git a/linux/src/musegadget/windows_files.py b/linux/src/musegadget/windows_files.py
new file mode 100644
index 0000000000000000000000000000000000000000..902fd61ff283fcf49a540b4baec64358622881b1
--- /dev/null
+++ b/linux/src/musegadget/windows_files.py
@@ -0,0 +1,165 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Windows handles for command definitions and private file transfers."""
+
+from __future__ import annotations
+
+import msvcrt
+import os
+import secrets
+import stat
+from contextlib import contextmanager
+from pathlib import Path
+
+import ntsecuritycon
+import pywintypes
+import win32api
+import win32con
+import win32file
+import win32security
+import winerror
+
+
+def _current_sid():
+ token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
+ try:
+ return win32security.GetTokenInformation(token, win32security.TokenUser)[0]
+ finally:
+ token.Close()
+
+
+def _owner_only_security(sid, *, directory):
+ user = win32security.ConvertSidToStringSid(sid)
+ inherit = "OICI" if directory else ""
+ security = pywintypes.SECURITY_ATTRIBUTES()
+ security.SECURITY_DESCRIPTOR = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
+ f"O:{user}D:P(A;{inherit};FA;;;{user})", win32security.SDDL_REVISION_1)
+ return security
+
+
+def _check_owner_only(handle, sid, *, directory):
+ descriptor = win32security.GetSecurityInfo(
+ handle, win32security.SE_FILE_OBJECT,
+ win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION)
+ dacl = descriptor.GetSecurityDescriptorDacl()
+ flags = win32con.OBJECT_INHERIT_ACE | win32con.CONTAINER_INHERIT_ACE if directory else 0
+ ace = ((win32security.ACCESS_ALLOWED_ACE_TYPE, flags), ntsecuritycon.FILE_ALL_ACCESS, sid)
+ if (descriptor.GetSecurityDescriptorOwner() != sid or dacl is None
+ or not descriptor.GetSecurityDescriptorControl()[0] & win32security.SE_DACL_PROTECTED
+ or dacl.GetAceCount() != 1 or dacl.GetAce(0) != ace):
+ raise PermissionError("private storage requires an owner-only Windows ACL")
+
+
+def private_state_temp(directory: Path) -> tuple[int, str]:
+ """Create a unique, owner-only temporary file on the destination volume."""
+ sid = _current_sid()
+ path = str(directory / (".musegadget-" + secrets.token_hex(16) + ".tmp"))
+ access = win32con.GENERIC_WRITE | win32con.READ_CONTROL | win32con.DELETE
+ handle = win32file.CreateFile(path, access, 0, _owner_only_security(sid, directory=False),
+ win32file.CREATE_NEW, 0, None)
+ try:
+ # Reject filesystems that cannot enforce this DACL before writing any
+ # credentials. Set the ACL during creation so inheritance has no window.
+ _check_owner_only(handle, sid, directory=False)
+ fd = msvcrt.open_osfhandle(int(handle), os.O_WRONLY | os.O_BINARY)
+ handle.Detach()
+ return fd, path
+ except BaseException:
+ win32file.SetFileInformationByHandle(handle, win32file.FileDispositionInfo, True)
+ raise
+ finally:
+ handle.Close()
+
+
+@contextmanager
+def directory_handle(path, *, exclusive=False):
+ """Pin a directory entry while its children are opened by name."""
+ access = win32con.GENERIC_READ | (win32con.DELETE if exclusive else 0)
+ share = 0 if exclusive else win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE
+ flags = win32file.FILE_FLAG_BACKUP_SEMANTICS | win32file.FILE_FLAG_OPEN_REPARSE_POINT
+ try:
+ handle = win32file.CreateFile(str(path), access, share, None, win32file.OPEN_EXISTING, flags, None)
+ except pywintypes.error as exc:
+ if exc.winerror in (winerror.ERROR_FILE_NOT_FOUND, winerror.ERROR_PATH_NOT_FOUND):
+ raise FileNotFoundError(path) from exc
+ raise
+ try:
+ attributes = win32file.GetFileInformationByHandle(handle)[0]
+ if (not attributes & stat.FILE_ATTRIBUTE_DIRECTORY or
+ attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT):
+ raise OSError("expected a directory, reparse points are not accepted")
+ yield handle
+ finally:
+ handle.Close()
+
+
+def open_definition(path: Path) -> int:
+ handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_OPEN_REPARSE_POINT, None)
+ try:
+ if win32file.GetFileInformationByHandle(handle)[0] & stat.FILE_ATTRIBUTE_REPARSE_POINT:
+ raise OSError("command definitions cannot be reparse points")
+ fd = msvcrt.open_osfhandle(int(handle), os.O_RDONLY | os.O_BINARY)
+ handle.Detach() # the returned descriptor owns the handle
+ return fd
+ finally:
+ handle.Close()
+
+
+@contextmanager
+def private_partial(directory: str, start: bool):
+ """Resume the transfer only inside a directory accessible to this user.
+
+ The directory handle excludes renames and competing SDK writers through
+ validation, hashing and publication. Its DACL protects chunks between calls,
+ including when the destination is in a shared directory.
+ """
+ sid = _current_sid()
+ if start:
+ try:
+ win32file.CreateDirectory(directory, _owner_only_security(sid, directory=True))
+ except pywintypes.error as exc:
+ if exc.winerror != winerror.ERROR_ALREADY_EXISTS:
+ raise
+ with directory_handle(directory, exclusive=True) as handle:
+ _check_owner_only(handle, sid, directory=True)
+ partial = os.path.join(directory, "contents")
+ try:
+ entry = os.lstat(partial)
+ except FileNotFoundError:
+ pass
+ else:
+ if (entry.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
+ or not stat.S_ISREG(entry.st_mode) or entry.st_nlink != 1):
+ raise OSError("invalid partial file")
+ try:
+ yield partial
+ finally:
+ if not os.path.lexists(partial):
+ win32file.SetFileInformationByHandle(handle, win32file.FileDispositionInfo, True)
+
+
+def publish(partial: str, path: str, overwrite: bool) -> None:
+ # Windows rename atomically refuses an existing destination.
+ try:
+ os.rename(partial, path)
+ return
+ except FileExistsError:
+ if not overwrite:
+ raise
+ # Keep the staged contents exclusively open while copying the existing
+ # destination's DACL (including inherited entries) and publishing them.
+ flags = win32security.DACL_SECURITY_INFORMATION
+ security = win32security.GetNamedSecurityInfo(path, win32security.SE_FILE_OBJECT, flags)
+ handle = win32file.CreateFile(partial, win32con.DELETE | win32con.WRITE_DAC, 0,
+ None, win32file.OPEN_EXISTING, 0, None)
+ try:
+ win32security.SetKernelObjectSecurity(handle, flags, security)
+ win32file.SetFileInformationByHandle(handle, win32file.FileRenameInfo, {
+ "ReplaceIfExists": True, "RootDirectory": None, "FileName": path})
+ except BaseException:
+ win32file.SetFileInformationByHandle(handle, win32file.FileDispositionInfo, True)
+ raise
+ finally:
+ handle.Close()
diff --git a/linux/src/musegadget/windows_input.py b/linux/src/musegadget/windows_input.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb09402192000fdf46b3434c45b0135e41bca823
--- /dev/null
+++ b/linux/src/musegadget/windows_input.py
@@ -0,0 +1,71 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Cancellable plain-text input from the Windows console, a pipe or a file."""
+
+import asyncio
+import ctypes
+from ctypes import wintypes
+from concurrent.futures import Future
+import threading
+
+import win32api
+import win32con
+
+_cancel_read = ctypes.WinDLL("kernel32", use_last_error=True).CancelSynchronousIo
+_cancel_read.argtypes = [wintypes.HANDLE]
+_cancel_read.restype = wintypes.BOOL
+
+
+class WindowsInput:
+ """Read with the console's normal line editor, including redirected input.
+
+ Standard handles need not support overlapped I/O. Cancel the blocking
+ read when the chat closes, so the worker cannot consume subsequent input.
+ """
+
+ def __init__(self, stream, limit):
+ self.stream = stream.buffer
+ self.limit = limit
+
+ async def readline(self):
+ handle = Future()
+ completion = Future()
+
+ def read():
+ try:
+ handle.set_result(win32api.OpenThread(
+ win32con.THREAD_TERMINATE, False, threading.get_native_id()))
+ completion.set_result(self.stream.readline(self.limit + 1))
+ except BaseException as exc:
+ if not handle.done():
+ handle.set_result(None)
+ completion.set_exception(exc)
+
+ threading.Thread(target=read, name="muse-chat-stdin").start()
+ result = asyncio.wrap_future(completion)
+ try:
+ return await asyncio.shield(result)
+ finally:
+ thread = await asyncio.wrap_future(handle)
+ if thread is not None:
+ try:
+ while not result.done():
+ # The read may still be between getting its handle
+ # and entering the kernel when cancellation arrives.
+ _cancel_read(int(thread))
+ await asyncio.wait({result}, timeout=0.02)
+ result.exception() # a cancelled Windows read raises OSError
+ finally:
+ thread.Close()
diff --git a/linux/tests/conftest.py b/linux/tests/conftest.py
index 12f65e00cfb5b9f8740c3c3e57ff5d81f1bc6c17..b28efd28c4b68aef8158ae1337866f87b494db01 100644
--- a/linux/tests/conftest.py
+++ b/linux/tests/conftest.py
@@ -16,6 +16,14 @@
from __future__ import annotations
+import asyncio
+import json
+import os
+import tempfile
+import threading
+from concurrent.futures import Future
+from pathlib import Path
+
import pytest
from musegadget import tls
@@ -34,3 +42,47 @@ def _no_proxy_from_the_environment(monkeypatch):
for name in ("https_proxy", "HTTPS_PROXY", "http_proxy", "HTTP_PROXY",
"all_proxy", "ALL_PROXY", "no_proxy", "NO_PROXY"):
monkeypatch.delenv(name, raising=False)
+
+
+@pytest.fixture
+def local_reply(monkeypatch):
+ """Exercise the CLI against the platform's real local transport in another thread."""
+ from musegadget import config, local_ipc
+ from musegadget.service import MAX_LOCAL_REQUEST
+
+ received, reply = [], [{"ok": True}]
+ ready = Future()
+
+ async def handle(reader, writer):
+ try:
+ received.append(json.loads(await reader.readline()))
+ writer.write(json.dumps(reply[0]).encode() + b"\n")
+ await writer.drain()
+ finally:
+ writer.close()
+ await writer.wait_closed()
+
+ async def serve(path):
+ try:
+ server = await local_ipc.start_server(handle, path, limit=MAX_LOCAL_REQUEST, gid=None)
+ except Exception as exc:
+ ready.set_exception(exc)
+ return
+ async with server:
+ done = asyncio.Event()
+ ready.set_result((asyncio.get_running_loop(), done))
+ await done.wait()
+
+ # Use a short socket path on Unix.
+ with tempfile.TemporaryDirectory(dir=None if os.name == "nt" else "/tmp") as directory:
+ path = Path(directory) / "mg.sock"
+ monkeypatch.setenv(config.SOCKET_ENV, str(path))
+ thread = threading.Thread(target=asyncio.run, args=(serve(path),), daemon=True)
+ thread.start()
+ loop, done = ready.result(timeout=10)
+ try:
+ yield received, reply
+ finally:
+ loop.call_soon_threadsafe(done.set)
+ thread.join(10)
+ assert not thread.is_alive()
diff --git a/linux/tests/test_command_guard.py b/linux/tests/test_command_guard.py
index 15a4f409f911b84a9760e00a06e921154654b3ce..fe531065c2fe065bcb84ca7d2b3190a285cb9fc3 100644
--- a/linux/tests/test_command_guard.py
+++ b/linux/tests/test_command_guard.py
@@ -43,6 +43,7 @@ from command_guard.scope import NOT_EVALUATED, ScopeChecker # noqa: E402
from command_guard.service import GuardedService # noqa: E402
HOME = "/home/pi"
+pytestmark = pytest.mark.skipif(os.name == "nt", reason="example policy for bash and Linux paths")
@pytest.fixture
diff --git a/linux/tests/test_commands.py b/linux/tests/test_commands.py
index 830392b1e08963e90d588f6b702bc5d113a14713..4268a788e31f979b661e897dbc66abbca8d80e5c 100644
--- a/linux/tests/test_commands.py
+++ b/linux/tests/test_commands.py
@@ -30,9 +30,11 @@ from musegadget import commands, config
from musegadget.commands import InvalidCommand
from musegadget.executor import COMMAND_SPECS, Account, Executor
+posix_permissions = pytest.mark.skipif(os.name == "nt", reason="POSIX ownership and permission bits")
+
SPEC = {
"description": "Switch the pump.",
- "exec": ["/usr/local/bin/pump", "--quiet"],
+ "exec": [sys.executable, "--quiet"],
"required": {"on": {"type": "boolean", "description": "true for on."}},
"optional": {"minutes": {"type": "integer", "description": "Run time."}},
"timeout_ms": 10000,
@@ -41,7 +43,7 @@ SPEC = {
def write(directory, name: str, data, mode: int = 0o644):
path = directory / f"{name}.json"
- path.write_text(data if isinstance(data, str) else json.dumps(data))
+ path.write_text(data if isinstance(data, str) else json.dumps(data), encoding="utf-8")
path.chmod(mode)
return path
@@ -67,7 +69,7 @@ def drop_in(argv, **overrides):
def test_parse_registers_the_spec_without_exec():
command = commands.parse("pump.set", SPEC)
- assert command.argv == ("/usr/local/bin/pump", "--quiet")
+ assert command.argv == (sys.executable, "--quiet")
assert command.spec == {
"description": "Switch the pump.",
"required": SPEC["required"],
@@ -77,7 +79,7 @@ def test_parse_registers_the_spec_without_exec():
def test_parse_defaults():
- command = commands.parse("pump.set", {"description": "d", "exec": ["/bin/true"]})
+ command = commands.parse("pump.set", {"description": "d", "exec": [sys.executable]})
assert (command.required, command.optional) == ({}, {})
assert command.timeout_ms == commands.DEFAULT_TIMEOUT_MS
@@ -147,7 +149,7 @@ def test_check_params_rejects(params, message):
def test_number_accepts_integers_but_not_booleans():
- command = commands.parse("x.y", {"description": "d", "exec": ["/bin/true"],
+ command = commands.parse("x.y", {"description": "d", "exec": [sys.executable],
"required": {"n": {"type": "number", "description": "n"}}})
assert command.check_params({"n": 2}) == {"n": 2}
assert command.check_params({"n": 2.5}) == {"n": 2.5}
@@ -182,6 +184,7 @@ def test_load_skips_deeply_nested_json(tmp_path, caplog):
assert "pump.set.json: not valid JSON" in caplog.text
+@pytest.mark.skipif(os.name == "nt", reason="POSIX FIFO")
def test_load_skips_symlinks_and_special_files(tmp_path, caplog):
target = write(tmp_path, "real.target", SPEC)
(tmp_path / "pump.set.json").symlink_to(target)
@@ -198,6 +201,7 @@ def test_load_skips_oversize_files(tmp_path, caplog):
assert "larger than" in caplog.text
+@posix_permissions
def test_load_skips_files_root_does_not_own(tmp_path, monkeypatch, caplog):
# The service runs as root on a device; the files must be root's alone.
write(tmp_path, "pump.set", SPEC)
@@ -208,7 +212,7 @@ def test_load_skips_files_root_does_not_own(tmp_path, monkeypatch, caplog):
assert "owned by root" in caplog.text
-@pytest.mark.skipif(os.geteuid() != 0, reason="needs root to own the files")
+@pytest.mark.skipif(os.name == "nt" or os.geteuid() != 0, reason="needs root to own the files")
def test_load_as_root_checks_the_mode(tmp_path, caplog):
write(tmp_path, "pump.set", SPEC)
write(tmp_path, "lamp.set", SPEC, mode=0o664)
@@ -218,7 +222,10 @@ def test_load_as_root_checks_the_mode(tmp_path, caplog):
def test_commands_dir(monkeypatch, tmp_path):
monkeypatch.delenv(config.COMMANDS_DIR_ENV, raising=False)
- assert str(config.commands_dir()) == "/etc/musegadget/commands.d"
+ if os.name == "nt":
+ assert config.commands_dir() == config.state_dir() / "commands.d"
+ else:
+ assert str(config.commands_dir()) == "/etc/musegadget/commands.d"
monkeypatch.setenv(config.COMMANDS_DIR_ENV, str(tmp_path))
assert config.commands_dir() == tmp_path
@@ -261,13 +268,13 @@ def test_drop_in_runs_in_the_account_home_with_the_safe_environment(account, tmp
def test_drop_in_plain_text_output(account, tmp_path):
argv = script(tmp_path, "print('pump on')")
result = Executor(account, [drop_in(argv)]).run("pump.set", {"on": True})
- assert result == {"ok": True, "payload": {"output": "pump on\n"}}
+ assert result == {"ok": True, "payload": {"output": "pump on" + os.linesep}}
def test_drop_in_json_that_is_not_an_object_is_text(account, tmp_path):
argv = script(tmp_path, "print('[1, 2]')")
result = Executor(account, [drop_in(argv)]).run("pump.set", {"on": True})
- assert result["payload"] == {"output": "[1, 2]\n"}
+ assert result["payload"] == {"output": "[1, 2]" + os.linesep}
def test_drop_in_large_output_is_truncated(account, tmp_path):
@@ -304,7 +311,7 @@ def test_drop_in_bad_params_never_start_the_program(account, tmp_path):
def test_drop_in_times_out_and_kills_the_process_group(account, tmp_path):
argv = script(tmp_path, (
"import subprocess\n"
- "subprocess.Popen(['sleep', '30'])\n"
+ "subprocess.Popen([sys.executable, '-c', 'import time;time.sleep(30)'])\n"
"time.sleep(30)"
))
started = time.monotonic()
@@ -346,6 +353,10 @@ def test_unknown_commands_are_still_unsupported(account):
@pytest.fixture
def watchdog():
"""Bound regressions which intentionally put backpressure on child pipes."""
+ if os.name == "nt":
+ yield # Windows process tests use Job Object deadlines.
+ return
+
def expired(signum, frame):
raise AssertionError("child execution exceeded the outer 10s watchdog")
@@ -379,14 +390,19 @@ def test_bad_json_shapes_do_not_stop_loading(tmp_path, data):
def test_one_unreadable_file_does_not_stop_loading(tmp_path, monkeypatch, caplog):
bad = write(tmp_path, "aaa.bad", SPEC)
write(tmp_path, "pump.set", SPEC)
- original = commands.os.open
+ if os.name == "nt":
+ from musegadget import windows_files
+ module, name, target = windows_files, "open_definition", bad
+ else:
+ module, name, target = commands.os, "open", bad.name
+ original = getattr(module, name)
- def open_file(path, flags, **kwargs):
- if path == bad.name:
+ def open_file(path, *args, **kwargs):
+ if path == target:
raise PermissionError("secret contents must not be logged")
- return original(path, flags, **kwargs)
+ return original(path, *args, **kwargs)
- monkeypatch.setattr(commands.os, "open", open_file)
+ monkeypatch.setattr(module, name, open_file)
assert [c.name for c in commands.load(tmp_path)] == ["pump.set"]
assert "PermissionError" in caplog.text
assert "secret contents" not in caplog.text
@@ -440,6 +456,7 @@ def root_directory_seam(monkeypatch, *, uid=0, mode=0o755):
(0, 0o700, True), (0, 0o755, True), (12345, 0o755, False),
(0, 0o775, False), (0, 0o777, False), (0, 0o757, False),
])
+@posix_permissions
def test_directory_trust_boundary(tmp_path, monkeypatch, caplog, uid, mode, safe):
write(tmp_path, "pump.set", SPEC)
root_directory_seam(monkeypatch, uid=uid, mode=mode)
@@ -449,6 +466,7 @@ def test_directory_trust_boundary(tmp_path, monkeypatch, caplog, uid, mode, safe
assert "owned by root" in caplog.text
+@posix_permissions
def test_non_root_development_can_use_its_own_writable_directory(tmp_path, monkeypatch):
write(tmp_path, "pump.set", SPEC, mode=0o666)
tmp_path.chmod(0o777)
@@ -465,7 +483,12 @@ def test_load_refuses_non_directory_and_directory_symlink(tmp_path, kind, caplog
actual = tmp_path / "actual"
actual.mkdir()
write(actual, "pump.set", SPEC)
- path.symlink_to(actual, target_is_directory=True)
+ try:
+ path.symlink_to(actual, target_is_directory=True)
+ except OSError as exc:
+ if getattr(exc, "winerror", None) == 1314:
+ pytest.skip("creating symlinks needs Windows Developer Mode or a privilege")
+ raise
assert commands.load(path) == []
assert "can't read commands" in caplog.text
@@ -498,7 +521,7 @@ def test_run_child_handles_closed_stdin_before_request_is_written(account, tmp_p
argv = script(tmp_path, "sys.stdin.close(); print('done')")
stdout, stderr, code, timed_out = Executor(account)._run_child(
argv, str(tmp_path), 2, stdin=b"x" * 1_000_000)
- assert (stdout, stderr, code, timed_out) == (b"done\n", b"", 0, False)
+ assert (stdout, stderr, code, timed_out) == (("done" + os.linesep).encode(), b"", 0, False)
def test_run_child_bounds_continuous_output_and_timeout(account, tmp_path, watchdog):
@@ -510,7 +533,7 @@ def test_run_child_bounds_continuous_output_and_timeout(account, tmp_path, watch
))
started = time.monotonic()
out, err, code, timed_out = Executor(account)._run_child(argv, str(tmp_path), 0.3)
- assert timed_out and code == -signal.SIGKILL
+ assert timed_out and code == (1 if os.name == "nt" else -signal.SIGKILL)
assert len(out) == len(err) == 96 * 1024 + 1
assert time.monotonic() - started < 3
@@ -531,7 +554,7 @@ def test_drop_in_returns_when_parent_exits_with_descendant_holding_pipes(account
finally:
if pidfile.exists():
try:
- os.kill(int(pidfile.read_text()), signal.SIGKILL)
+ os.kill(int(pidfile.read_text()), signal.SIGTERM if os.name == "nt" else signal.SIGKILL)
except ProcessLookupError:
pass
@@ -591,8 +614,8 @@ def test_registration_accounts_for_escaping_and_metadata(account, tmp_path, capl
# This fits the file limit with literal UTF-8, but not the outgoing ensure_ascii JSON.
for name in ["aaa.large", "bbb.large", "ccc.large"]:
write(tmp_path, name, json.dumps({"description": "界" * 21000,
- "exec": ["/bin/true"]}, ensure_ascii=False))
- write(tmp_path, "zzz.small", {"description": 'say "hi"\n\t\\ 😀', "exec": ["/bin/true"]})
+ "exec": [sys.executable]}, ensure_ascii=False))
+ write(tmp_path, "zzz.small", {"description": 'say "hi"\n\t\\ 😀', "exec": [sys.executable]})
metadata = {**REGISTER_METADATA, "display_name": '界"\\' * 5000}
executor = Executor(account, commands.load(tmp_path))
specs = executor.specs(**metadata)
@@ -621,6 +644,7 @@ def test_no_drop_in_registration_remains_byte_identical(account):
@pytest.mark.parametrize("uid, mode", [(12345, 0o644), (0, 0o664), (0, 0o646)])
+@posix_permissions
def test_file_trust_checks_still_apply_in_a_safe_directory(tmp_path, monkeypatch, caplog, uid, mode):
write(tmp_path, "pump.set", SPEC)
original = commands.os.fstat
@@ -639,7 +663,7 @@ def test_file_trust_checks_still_apply_in_a_safe_directory(tmp_path, monkeypatch
assert "pump.set.json: must be owned by root" in caplog.text
-@pytest.mark.skipif(os.geteuid() != 0, reason="needs real root inside the Linux test container")
+@pytest.mark.skipif(os.name == "nt" or os.geteuid() != 0, reason="needs real root inside the Linux test container")
def test_disk_loaded_drop_in_really_runs_as_unprivileged_account(watchdog):
from pathlib import Path
diff --git a/linux/tests/test_config.py b/linux/tests/test_config.py
index 3ab8b08f9aaa8bbf7456785d0490f87818b0df59..e953a4d1fc4c1bc081e2f5a9a2c48d29be6cc303 100644
--- a/linux/tests/test_config.py
+++ b/linux/tests/test_config.py
@@ -52,6 +52,78 @@ def test_load_json_treats_undecodable_bytes_as_missing(tmp_path):
assert config.load_json("pairing.json", tmp_path) is None
+def test_unserializable_state_keeps_the_previous_record_and_cleans_up(tmp_path):
+ config.save_json("pairing.json", {"value": "first"}, tmp_path)
+ with pytest.raises(TypeError):
+ config.save_json("pairing.json", {"bad": object()}, tmp_path)
+ assert config.load_json("pairing.json", tmp_path) == {"value": "first"}
+ assert list(tmp_path.iterdir()) == [tmp_path / "pairing.json"]
+
+
+def test_concurrent_saves_publish_complete_independent_records(tmp_path, monkeypatch):
+ from concurrent.futures import ThreadPoolExecutor
+ from threading import Barrier
+
+ barrier = Barrier(2)
+ dump = config.json.dump
+
+ def simultaneous_dump(*args, **kwargs):
+ barrier.wait(timeout=5)
+ return dump(*args, **kwargs)
+
+ monkeypatch.setattr(config.json, "dump", simultaneous_dump)
+ records = [{"value": c * 8000} for c in "ab"]
+ with ThreadPoolExecutor(2) as pool:
+ list(pool.map(lambda record: config.save_json("pairing.json", record, tmp_path), records))
+ assert config.load_json("pairing.json", tmp_path) in records
+ assert list(tmp_path.iterdir()) == [tmp_path / "pairing.json"]
+
+
+@pytest.mark.skipif(os.name != "nt", reason="Windows filesystem ACLs")
+def test_state_is_owner_only_during_and_after_a_save_in_a_shared_directory(tmp_path, monkeypatch):
+ import msvcrt
+ import ntsecuritycon
+ import pywintypes
+ import win32api
+ import win32con
+ import win32file
+ import win32security as security
+
+ token = security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
+ try:
+ sid = security.GetTokenInformation(token, security.TokenUser)[0]
+ finally:
+ token.Close()
+ shared = tmp_path / "shared"
+ user = security.ConvertSidToStringSid(sid)
+ attributes = pywintypes.SECURITY_ATTRIBUTES()
+ attributes.SECURITY_DESCRIPTOR = security.ConvertStringSecurityDescriptorToSecurityDescriptor(
+ f"D:P(A;OICI;FA;;;{user})(A;OICI;FR;;;WD)", security.SDDL_REVISION_1)
+ win32file.CreateDirectory(str(shared), attributes)
+ path = shared / "pairing.json"
+ path.write_text("{}")
+ flags = security.OWNER_SECURITY_INFORMATION | security.DACL_SECURITY_INFORMATION
+ assert security.GetNamedSecurityInfo(str(path), security.SE_FILE_OBJECT, flags).GetSecurityDescriptorDacl().GetAceCount() == 2
+
+ def assert_private(descriptor):
+ assert descriptor.GetSecurityDescriptorOwner() == sid
+ assert descriptor.GetSecurityDescriptorControl()[0] & security.SE_DACL_PROTECTED
+ acl = descriptor.GetSecurityDescriptorDacl()
+ assert acl.GetAceCount() == 1
+ assert acl.GetAce(0) == ((security.ACCESS_ALLOWED_ACE_TYPE, 0), ntsecuritycon.FILE_ALL_ACCESS, sid)
+
+ dump = config.json.dump
+
+ def check_before_writing(data, file, **kwargs):
+ handle = msvcrt.get_osfhandle(file.fileno())
+ assert_private(security.GetSecurityInfo(handle, security.SE_FILE_OBJECT, flags))
+ return dump(data, file, **kwargs)
+
+ monkeypatch.setattr(config.json, "dump", check_before_writing)
+ config.save_json("pairing.json", {"value": "test"}, shared)
+ assert_private(security.GetNamedSecurityInfo(str(path), security.SE_FILE_OBJECT, flags))
+
+
@pytest.mark.skipif(
os.name == "nt" or getattr(os, "geteuid", lambda: 1)() == 0,
reason="needs POSIX file modes and a user the mode applies to",
diff --git a/linux/tests/test_doctor.py b/linux/tests/test_doctor.py
index 8010976f99341d9fe1197e9451afc9661d7078df..8a429cb18d07a6d16ab3e11eeccdaaf58c376001 100644
--- a/linux/tests/test_doctor.py
+++ b/linux/tests/test_doctor.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import errno
import json
+import os
import subprocess
from pathlib import Path
from typing import Literal
@@ -58,7 +59,7 @@ def test_pairing_accepts_saved_tokens_without_creating_identity(tmp_path: Path)
)
before: bytes = (tmp_path / config.PAIRING_FILE).read_bytes()
result: doctor.CheckResult = doctor.check_pairing(tmp_path)
- assert result["status"] == "OK"
+ assert result["status"] == ("FAIL" if os.name == "nt" else "OK")
assert "secret" not in doctor.format_check(result)
assert (tmp_path / config.PAIRING_FILE).read_bytes() == before
assert not (tmp_path / config.IDENTITY_FILE).exists()
@@ -254,7 +255,7 @@ def test_trust_store_fails_while_musegadget_would_refuse_to_connect(
result: doctor.CheckResult = doctor.check_trust_store()
assert result["status"] == "FAIL" # a failure wins over the retired-root warning
assert problem[1:] in result["detail"]
- assert "update your ca-certificates package" in result["hint"].lower()
+ assert doctor.tls.FIX.lower() in result["hint"].lower()
def test_trust_store_is_ok_without_distrusted_roots(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -291,7 +292,7 @@ def test_cli_renders_checks_and_sets_exit_status(
def test_unsupported_platform_does_not_probe_or_create_state(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
- monkeypatch.setattr(doctor.platform, "system", Mock(return_value="Windows"))
+ monkeypatch.setattr(doctor.platform, "system", Mock(return_value="Darwin"))
probe: Mock = Mock(side_effect=AssertionError("must not probe"))
monkeypatch.setattr(doctor.network, "is_online", probe)
monkeypatch.setenv(config.STATE_DIR_ENV, str(tmp_path / "absent"))
diff --git a/linux/tests/test_executor.py b/linux/tests/test_executor.py
index 50bb655768fd9403918bf7e2740057d1cab03e5d..466fc504e0c9e1f4e7c4d1e80642387ab2eabadd 100644
--- a/linux/tests/test_executor.py
+++ b/linux/tests/test_executor.py
@@ -19,6 +19,7 @@ import hashlib
import json
import os
import stat
+import sys
import time
from types import SimpleNamespace
@@ -27,6 +28,9 @@ import pytest
from musegadget import executor, fileops
from musegadget.executor import Account, Executor
+posix_mode = pytest.mark.skipif(os.name == "nt", reason="POSIX file modes")
+posix_session = pytest.mark.skipif(os.name == "nt", reason="detached POSIX sessions")
+
@pytest.fixture
def ex(monkeypatch, tmp_path):
@@ -37,24 +41,30 @@ def ex(monkeypatch, tmp_path):
def test_system_run_returns_output_and_exit_code(ex):
- result = ex.run("system.run", {"command": "echo out; echo err >&2; exit 3"})
+ command = ("(echo out)&(echo err)>&2&exit /b 3" if os.name == "nt"
+ else "echo out; echo err >&2; exit 3")
+ result = ex.run("system.run", {"command": command})
assert result["ok"]
payload = result["payload"]
- assert (payload["stdout"], payload["stderr"], payload["exit_code"]) == ("out\n", "err\n", 3)
+ assert (payload["stdout"], payload["stderr"], payload["exit_code"]) == (
+ "out" + os.linesep, "err" + os.linesep, 3)
assert not payload["timed_out"] and not payload["truncated"]
def test_system_run_defaults_to_the_account_home(ex, tmp_path):
- cwd = ex.run("system.run", {"command": "pwd -P"})["payload"]["stdout"].strip()
- assert cwd == os.path.realpath(tmp_path)
+ cwd = ex.run("system.run", {"command": "cd" if os.name == "nt" else "pwd -P"})["payload"]["stdout"].strip()
+ assert os.path.samefile(cwd, tmp_path)
def test_system_run_times_out_and_kills_the_process_group(ex):
- result = ex.run("system.run", {"command": "sleep 30 & sleep 30", "timeout_ms": 300})
+ command = (f'"{sys.executable}" -c "import time; time.sleep(30)"' if os.name == "nt"
+ else "sleep 30 & sleep 30")
+ result = ex.run("system.run", {"command": command, "timeout_ms": 300})
assert result["ok"] and result["payload"]["timed_out"]
assert result["payload"]["duration_ms"] < 5000
+@posix_session
def test_system_run_timeout_does_not_wait_for_a_detached_process(ex):
# A process that left the group with setsid survives the group kill and keeps the
# output pipes open. The timeout must still return promptly.
@@ -65,6 +75,7 @@ def test_system_run_timeout_does_not_wait_for_a_detached_process(ex):
assert elapsed < 4
+@posix_session
def test_system_run_returns_when_the_shell_exits_but_a_child_holds_the_pipes(ex):
# setsid leaves the group and keeps the inherited pipes open after bash exits 0.
# Waiting on pipe EOF reports a timeout for a command that already succeeded.
@@ -87,7 +98,9 @@ def test_system_run_returns_when_the_shell_exits_but_a_child_holds_the_pipes(ex)
def test_system_run_truncates_large_output(ex):
- result = ex.run("system.run", {"command": "head -c 200000 /dev/zero | tr '\\0' x"})
+ command = (f'''"{sys.executable}" -c "import sys;sys.stdout.write('x'*200000)"'''
+ if os.name == "nt" else "head -c 200000 /dev/zero | tr '\\0' x")
+ result = ex.run("system.run", {"command": command})
payload = result["payload"]
assert payload["truncated"]
assert len(payload["stdout"]) == executor.MAX_OUTPUT_BYTES
@@ -162,6 +175,7 @@ def test_file_write_rejects_out_of_order_chunks(ex, tmp_path, monkeypatch):
assert not result["ok"] and "expected offset 2" in result["error"]
+@posix_mode
def test_file_write_keeps_the_mode_of_the_file_it_replaces(ex, tmp_path, monkeypatch):
for name, mode in (("secret", 0o600), ("script.sh", 0o755)):
target = tmp_path / name
@@ -173,6 +187,7 @@ def test_file_write_keeps_the_mode_of_the_file_it_replaces(ex, tmp_path, monkeyp
assert stat.S_IMODE(target.stat().st_mode) == mode, name
+@posix_mode
def test_file_write_drops_setuid_setgid_and_sticky_bits(ex, tmp_path, monkeypatch):
target = tmp_path / "tool"
target.write_bytes(b"old")
@@ -182,6 +197,7 @@ def test_file_write_drops_setuid_setgid_and_sticky_bits(ex, tmp_path, monkeypatc
assert stat.S_IMODE(target.stat().st_mode) == 0o755
+@posix_mode
def test_file_write_keeps_the_partial_file_private_until_it_is_done(ex, tmp_path, monkeypatch):
target = tmp_path / "new"
assert ex.run("file.write", {"path": str(target), "data_b64": "aGk="})["ok"]
diff --git a/linux/tests/test_fileops.py b/linux/tests/test_fileops.py
index 0717f0e16851d04207733a2659d461fd4833a2e9..e7c3c84bc05456100fd32bcd92d45aaeba53a34b 100644
--- a/linux/tests/test_fileops.py
+++ b/linux/tests/test_fileops.py
@@ -16,22 +16,25 @@ import base64
import errno
import json
import os
-import select
+import queue
import stat
import subprocess
import sys
+import threading
from pathlib import Path
import pytest
from musegadget import fileops
+posix_publication = pytest.mark.skipif(os.name == "nt", reason="POSIX link-based file publication")
+
# Source-owned inert wrapper pauses the real publication primitive. No production
# algorithm is copied: all checks, chunking, checksum and mode logic are fileops.write.
CHILD = """import json, sys
from musegadget import fileops
request = json.loads(sys.stdin.readline())
-replace, link = fileops.os.replace, fileops.os.link
+replace, link, rename = fileops.os.replace, fileops.os.link, fileops.os.rename
def pause(publish):
def wrapped(source, destination, **kwargs):
@@ -42,6 +45,7 @@ def pause(publish):
fileops.os.replace = pause(replace)
fileops.os.link = pause(link)
+fileops.os.rename = pause(rename)
try:
result = {"ok": True, "payload": fileops.write(request)}
except (fileops.FileOpError, OSError, ValueError) as exc:
@@ -54,7 +58,9 @@ def test_overwrite_false_preserves_a_destination_created_before_publication(tmp_
target = tmp_path / "destination"
params = {"path": str(target), "data_b64": base64.b64encode(b"new contents").decode(),
"final": True, "overwrite": False}
- env = {"PATH": "/usr/bin:/bin", "PYTHONPATH": str(Path(fileops.__file__).parent.parent)}
+ env = {"PATH": os.defpath, "PYTHONPATH": str(Path(fileops.__file__).parent.parent)}
+ if os.name == "nt":
+ env["SYSTEMROOT"] = os.environ["SYSTEMROOT"]
child = subprocess.Popen(
[sys.executable, "-c", CHILD], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, env=env,
@@ -62,9 +68,9 @@ def test_overwrite_false_preserves_a_destination_created_before_publication(tmp_
try:
child.stdin.write(json.dumps(params) + "\n")
child.stdin.flush()
- ready, _, _ = select.select([child.stdout], [], [], 5)
- assert ready, "child never reached publication barrier"
- assert child.stdout.readline().strip() == "READY"
+ ready = queue.Queue()
+ threading.Thread(target=lambda: ready.put(child.stdout.readline()), daemon=True).start()
+ assert ready.get(timeout=5).strip() == "READY"
# Another process creates the destination just before the actual OS
# publication, with deterministic IPC rather than timing a race.
target.write_bytes(b"concurrent contents")
@@ -106,7 +112,12 @@ def test_no_overwrite_refuses_existing_directory_entries(tmp_path, entry):
referent = tmp_path / "referent"
if entry == "symlink":
referent.write_bytes(b"original")
- target.symlink_to(referent)
+ try:
+ target.symlink_to(referent)
+ except OSError as exc:
+ if getattr(exc, "winerror", None) == 1314:
+ pytest.skip("creating symlinks needs Windows Developer Mode or a privilege")
+ raise
with pytest.raises(fileops.FileOpError, match="overwrite is false"):
fileops.write(request_for(target))
assert os.path.lexists(target)
@@ -117,6 +128,7 @@ def test_no_overwrite_refuses_existing_directory_entries(tmp_path, entry):
assert target.is_symlink()
+@posix_publication
def test_no_overwrite_publication_failure_discards_partial(tmp_path, monkeypatch):
def unsupported(*args, **kwargs):
raise OSError("hard links unavailable")
@@ -128,6 +140,7 @@ def test_no_overwrite_publication_failure_discards_partial(tmp_path, monkeypatch
assert not (tmp_path / ".new.musegadget-partial").exists()
+@posix_publication
def test_no_overwrite_publishes_a_swapped_partial_symlink_not_its_target(tmp_path):
private = tmp_path / "private"
private.write_bytes(b"secret")
@@ -157,6 +170,7 @@ def fail_link(monkeypatch, code):
@pytest.mark.parametrize("code", NO_HARD_LINKS, ids=errno.errorcode.get)
+@posix_publication
def test_no_overwrite_without_hard_links_creates_new_file(tmp_path, monkeypatch, code):
fail_link(monkeypatch, code)
target = tmp_path / "new"
@@ -171,6 +185,7 @@ def test_no_overwrite_without_hard_links_creates_new_file(tmp_path, monkeypatch,
@pytest.mark.parametrize("entry", ["file", "dangling"])
@pytest.mark.parametrize("code", NO_HARD_LINKS, ids=errno.errorcode.get)
+@posix_publication
def test_no_overwrite_without_hard_links_refuses_existing_entries(
tmp_path, monkeypatch, code, entry
):
@@ -189,6 +204,7 @@ def test_no_overwrite_without_hard_links_refuses_existing_entries(
assert not (tmp_path / ".existing.musegadget-partial").exists()
+@posix_publication
def test_no_overwrite_without_hard_links_removes_placeholder_if_rename_fails(
tmp_path, monkeypatch
):
@@ -205,6 +221,7 @@ def test_no_overwrite_without_hard_links_removes_placeholder_if_rename_fails(
assert not (tmp_path / ".new.musegadget-partial").exists()
+@posix_publication
def test_no_overwrite_link_file_exists_error_is_not_retried(tmp_path, monkeypatch):
fail_link(monkeypatch, errno.EEXIST)
target = tmp_path / "new"
@@ -217,6 +234,7 @@ def test_no_overwrite_link_file_exists_error_is_not_retried(tmp_path, monkeypatc
@pytest.mark.parametrize(
"code", [errno.ENOSPC, errno.EACCES, errno.EROFS, errno.EIO], ids=errno.errorcode.get
)
+@posix_publication
def test_no_overwrite_other_link_errors_propagate(tmp_path, monkeypatch, code):
fail_link(monkeypatch, code)
target = tmp_path / "new"
diff --git a/linux/tests/test_identity.py b/linux/tests/test_identity.py
index 3d13fdd748e515c28be4ee7922efdd2dcd17233e..f5de7e56c730c3d34a91931ff50765f73f6e6eae 100644
--- a/linux/tests/test_identity.py
+++ b/linux/tests/test_identity.py
@@ -44,8 +44,8 @@ def test_generated_mac_is_locally_administered_unicast():
def test_identity_persists(tmp_path):
first = identity.load_or_create(tmp_path)
assert identity.load_or_create(tmp_path) == first
- mode = stat.S_IMODE(os.stat(tmp_path / config.IDENTITY_FILE).st_mode)
- assert mode == 0o600
+ if os.name != "nt":
+ assert stat.S_IMODE(os.stat(tmp_path / config.IDENTITY_FILE).st_mode) == 0o600
def test_corrupt_identity_is_replaced(tmp_path):
diff --git a/linux/tests/test_install_sh.py b/linux/tests/test_install_sh.py
index cba63e6eecac6a72ca45ff287112b23e72d53eda..b6c6ed45c64859be7f8fd05f4bf5ae9aaba85b35 100644
--- a/linux/tests/test_install_sh.py
+++ b/linux/tests/test_install_sh.py
@@ -37,6 +37,8 @@ from pathlib import Path
import pytest
+pytestmark = pytest.mark.skipif(os.name == "nt", reason="Linux shell installer")
+
INSTALL_SH = Path(__file__).resolve().parents[1] / "install.sh"
TARGET = "x86_64-unknown-linux-gnu"
OTHER_UID = 1001
diff --git a/linux/tests/test_link_client.py b/linux/tests/test_link_client.py
index d1e8c0d8cc6d78cb2de801116fcba15f1c5d6c90..6d8a7fb66403a15cf6e0fc65342eb034edf7848e 100644
--- a/linux/tests/test_link_client.py
+++ b/linux/tests/test_link_client.py
@@ -19,6 +19,7 @@ import base64
import dataclasses
import io
import json
+import os
import struct
import wave
@@ -36,6 +37,8 @@ from musegadget.noise import (
)
from musegadget.noise.transport import decode_request_envelope, encode_response_envelope
+HOST_OS = "Windows" if os.name == "nt" else "Linux"
+
DEVICE = DeviceDescription(
node_id="homelink-abcdef", display_name="pi", version="0.1.0",
commands={"system.run": {"description": "run", "required": {}, "optional": {}}},
@@ -146,7 +149,7 @@ def test_register_invoke_result_and_unpair():
assert register["method"] == "link.register"
params = register["params"]
assert params["node_id"] == "homelink-abcdef"
- assert (params["platform"], params["device_family"]) == ("linux", "gadget")
+ assert (params["platform"], params["device_family"]) == (HOST_OS.lower(), "gadget")
assert "system.run" in params["commands_v2"]
await vm.send_message({"type": "res", "id": register["id"], "ok": True})
@@ -172,8 +175,8 @@ def test_register_invoke_result_and_unpair():
def test_register_describes_the_model():
params = DEVICE.register_params()
- assert (params["device_family"], params["model_id"]) == ("gadget", "muse-gadget-linux")
- assert params["metadata"] == {"model_name": "Linux gadget"}
+ assert (params["device_family"], params["model_id"]) == ("gadget", f"muse-gadget-{HOST_OS.lower()}")
+ assert params["metadata"] == {"model_name": f"{HOST_OS} gadget"}
assert device_guide.COMMAND not in params["commands_v2"]
robot = dataclasses.replace(DEVICE, model_id="acme-robot-2", model_name="Acme Robot 2",
@@ -424,11 +427,11 @@ def test_drop_in_command_is_registered_and_runs_over_the_session(tmp_path, fill_
if fill_budget:
for i in range(4):
(tmp_path / f"custom.a{i}.json").write_text(json.dumps({
- "description": "x" * 60000, "exec": ["/bin/true"]}))
+ "description": "x" * 60000, "exec": [sys.executable]}))
(tmp_path / "zzz.large.json").write_text(json.dumps({
- "description": "界" * 21000, "exec": ["/bin/true"]}, ensure_ascii=False))
+ "description": "界" * 21000, "exec": [sys.executable]}, ensure_ascii=False), encoding="utf-8")
(tmp_path / "aaa.bad.json").write_text(json.dumps({
- "description": "bad", "exec": ["/bin/true"],
+ "description": "bad", "exec": [sys.executable],
"required": {"x": {"type": ["string"], "description": "d"}}}))
current = Account.current()
executor = Executor(Account(current.name, current.uid, current.gid, str(tmp_path)),
diff --git a/linux/tests/test_pair.py b/linux/tests/test_pair.py
index 5c866e1e2898ed2bdcf1fcd752a5a1cbc815a765..8d98a37780ddbaa24a1bc2c31808384ecbda532e 100644
--- a/linux/tests/test_pair.py
+++ b/linux/tests/test_pair.py
@@ -25,6 +25,8 @@ from musegadget import cli, config
from musegadget import pair as pair_module
from musegadget.pair import PairOutcome, PairResult, SetupWindow, pair
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="Bluetooth pairing runs on Linux")
+
class FakeBleServer:
def __init__(self, name, *, on_write, on_disconnect):
diff --git a/linux/tests/test_reaper.py b/linux/tests/test_reaper.py
index 940502a072d9ef617ff182c8ae51c690e7ba4683..d123d92be8ae48326ba515856b8368d29ebf06ea 100644
--- a/linux/tests/test_reaper.py
+++ b/linux/tests/test_reaper.py
@@ -27,7 +27,7 @@ import pytest
from musegadget import reaper
pytestmark = pytest.mark.skipif(
- not hasattr(os, "waitpid"), reason="waitpid is POSIX-only")
+ os.name == "nt", reason="POSIX child reaping")
@pytest.fixture()
diff --git a/linux/tests/test_send_and_wait.py b/linux/tests/test_send_and_wait.py
index 13c992417b94bdf780595fb39ce243140b31556b..ec115674aaee33ccc83ebbb2c1c983b1e2ed34f4 100644
--- a/linux/tests/test_send_and_wait.py
+++ b/linux/tests/test_send_and_wait.py
@@ -18,14 +18,10 @@ from __future__ import annotations
import asyncio
import json
-import socket
-import tempfile
-import threading
-from pathlib import Path
import pytest
-from musegadget import cli, config, service as service_module
+from musegadget import cli, service as service_module
from musegadget.link_client import HttpStreamError
from musegadget.noise import ApplicationResponse, BodyChunk, Header, ServiceFrame
from musegadget.service import send_and_wait
@@ -586,39 +582,6 @@ def test_local_socket_refuses_a_bad_wait(wait):
run_with_socket(check)
-@pytest.fixture
-def local_reply(monkeypatch):
- """A one-shot local socket that records the request and answers with ``reply[0]``."""
- received, reply = [], [{"ok": True}]
- with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
- path = Path(tmp) / "mg.sock"
- server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- server.bind(str(path))
- server.listen(1)
- server.settimeout(10)
-
- def serve():
- try:
- conn, _ = server.accept()
- except OSError:
- return
- with conn:
- line = conn.makefile("rb").readline()
- if line:
- received.append(json.loads(line))
- conn.sendall(json.dumps(reply[0]).encode() + b"\n")
-
- thread = threading.Thread(target=serve, daemon=True)
- thread.start()
- monkeypatch.setenv(config.SOCKET_ENV, str(path))
- yield received, reply
- if thread.is_alive():
- with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as wake:
- wake.connect(str(path))
- thread.join(5)
- server.close()
-
-
@pytest.mark.parametrize("answer, code, out, err", [
({**ACK, "reply": "Four."}, 0, "Four.\n", ""),
({**ACK, "reply": ""}, 0, "", "Muse finished without a text answer.\n"),
diff --git a/linux/tests/test_send_user_msg.py b/linux/tests/test_send_user_msg.py
index 7055f2bbb8c6caa39c458a838ae0b1ed90bb2fe1..91bb6702d4b594b80db9d1ed04a636247391683b 100644
--- a/linux/tests/test_send_user_msg.py
+++ b/linux/tests/test_send_user_msg.py
@@ -18,51 +18,17 @@ from __future__ import annotations
import base64
import builtins
-import json
import os
-import socket
-import tempfile
-import threading
-from pathlib import Path
import pytest
-from musegadget import cli, config
+from musegadget import cli
from musegadget.link_client import MAX_IMAGE_BYTES
@pytest.fixture
-def service(monkeypatch):
- """A one-shot local socket that records the request and says ok."""
- received = []
- # AF_UNIX paths are short on macOS, so avoid pytest's long tmp_path.
- with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
- path = Path(tmp) / "mg.sock"
- server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- server.bind(str(path))
- server.listen(1)
- server.settimeout(10)
-
- def serve():
- try:
- conn, _ = server.accept()
- except OSError:
- return
- with conn:
- line = conn.makefile("rb").readline()
- if line:
- received.append(json.loads(line))
- conn.sendall(b'{"ok": true}\n')
-
- thread = threading.Thread(target=serve, daemon=True)
- thread.start()
- monkeypatch.setenv(config.SOCKET_ENV, str(path))
- yield received
- if thread.is_alive(): # nothing connected; wake the accept
- with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as wake:
- wake.connect(str(path))
- thread.join(5)
- server.close()
+def service(local_reply):
+ return local_reply[0]
def refuse_to_open(monkeypatch, path):
@@ -107,6 +73,7 @@ def test_non_image_is_refused_before_it_is_read(tmp_path, monkeypatch, capsys, s
assert service == []
+@pytest.mark.skipif(os.name == "nt", reason="POSIX FIFO")
def test_fifo_is_refused_instead_of_waiting_for_a_writer(tmp_path, monkeypatch, capsys, service):
fifo = tmp_path / "camera.jpg"
os.mkfifo(fifo)
diff --git a/linux/tests/test_service.py b/linux/tests/test_service.py
index b32e108a04351c4dce1f6365d87856ba530c5307..338e89e8d9716a262ff943d6b3db9ee2f6f9e3c9 100644
--- a/linux/tests/test_service.py
+++ b/linux/tests/test_service.py
@@ -35,9 +35,10 @@ from musegadget.link_client import (
MAX_CONTROL_MESSAGE_BYTES, MAX_IMAGE_BYTES, REGISTER_ID_BYTES, DeviceDescription, Outcome, encode_message,
)
from musegadget.noise import ApplicationResponse, ServiceFrame
+from musegadget.local_ipc import open_connection
from musegadget.service import MAX_LOCAL_REQUEST, Backoff, Service
-from test_link_client import FakeVm, Pipe, bounded_scenario
+from test_link_client import HOST_OS, FakeVm, Pipe, bounded_scenario
class FakeSession:
@@ -57,7 +58,7 @@ class FakeSession:
async def ask(path: Path, payload: bytes) -> dict:
- reader, writer = await asyncio.open_unix_connection(str(path))
+ reader, writer = await open_connection(path, limit=MAX_LOCAL_REQUEST)
writer.write(payload)
await writer.drain()
reply = json.loads(await reader.readline())
@@ -68,7 +69,7 @@ async def ask(path: Path, payload: bytes) -> dict:
def run_with_socket(check) -> None:
async def scenario():
# AF_UNIX paths are short on macOS, so avoid pytest's long tmp_path.
- with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
+ with tempfile.TemporaryDirectory(dir=None if os.name == "nt" else "/tmp") as tmp:
path = Path(tmp) / "mg.sock"
service = Service(identity=Identity("02:00:00:00:00:01"),
executor=Executor(Account.current()))
@@ -83,7 +84,8 @@ def run_with_socket(check) -> None:
def test_local_message_is_forwarded_to_the_live_session():
async def check(service, path):
- assert stat.S_IMODE(os.stat(path).st_mode) == 0o660
+ if os.name != "nt":
+ assert stat.S_IMODE(os.stat(path).st_mode) == 0o660
session = FakeSession()
service._current = session
reply = await ask(path, json.dumps({"message": "hello from the ring"}).encode() + b"\n")
@@ -135,7 +137,7 @@ def test_local_message_can_carry_a_picture():
def test_local_request_over_the_line_limit_gets_a_json_error():
async def check(service, path):
service._current = session = FakeSession()
- reader, writer = await asyncio.open_unix_connection(str(path))
+ reader, writer = await open_connection(path, limit=MAX_LOCAL_REQUEST)
# Send the whole oversized line before reading, as the CLI does.
writer.write(b'{"message": "' + b"x" * MAX_LOCAL_REQUEST + b'"}\n')
await writer.drain()
@@ -208,7 +210,7 @@ def test_a_subclass_runs_its_own_device_and_work_on_the_service_session(paired_d
return device_ws
monkeypatch.setattr("websockets.asyncio.client.connect", connect)
- with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
+ with tempfile.TemporaryDirectory(dir=None if os.name == "nt" else "/tmp") as tmp:
lamp = Lamp(identity=Identity("02:00:00:00:00:01"), executor=Executor(Account.current()))
path = Path(tmp) / "mg.sock"
server = await lamp.serve_local(path)
@@ -220,8 +222,8 @@ def test_a_subclass_runs_its_own_device_and_work_on_the_service_session(paired_d
assert register["method"] == "link.register"
assert register["params"] == {
"node_id": "homelink-000001", "display_name": "Lamp", "version": "2.0",
- "platform": "linux", "device_family": "gadget", "model_id": "muse-gadget-linux",
- "metadata": {"model_name": "Linux gadget"}, "is_wakeup_supported": False,
+ "platform": HOST_OS.lower(), "device_family": "gadget", "model_id": f"muse-gadget-{HOST_OS.lower()}",
+ "metadata": {"model_name": f"{HOST_OS} gadget"}, "is_wakeup_supported": False,
"commands_v2": {"lamp.on": {"description": "Turn on the lamp", "required": {}, "optional": {}}},
}
await vm.send_message({"type": "res", "id": register["id"], "ok": True})
@@ -266,14 +268,14 @@ def test_a_subclass_runs_its_own_device_and_work_on_the_service_session(paired_d
-def test_the_service_describes_the_linux_client_with_its_guide():
+def test_the_service_describes_the_host_with_its_guide():
async def describe():
return Service(identity=Identity("02:00:00:00:00:01"), executor=Executor(Account.current())).describe()
params = asyncio.run(describe()).register_params()
assert params["commands_v2"]["device.guide"] == device_guide.SPEC
guide = device_guide.default_guide()
- assert guide.startswith("# Linux gadget\n")
+ assert guide.startswith(f"# {HOST_OS} gadget\n")
assert "Hatch" not in guide and len(guide.encode()) <= 2048
# The rules for this repository's guides (protocols/DEVICE.md, Guides in this repository).
assert not re.search(r"https?://|www\.|<[A-Za-z!/]|^\s*(```|~~~)|[\x00-\x09\x0b-\x1f\x7f-\x9f]", guide, re.M)
@@ -495,7 +497,8 @@ def test_service_waits_for_repaired_pairing(tmp_path, monkeypatch, caplog, inval
asyncio.run(scenario())
assert fetched == [valid["access_token"]]
- assert "musegadget pair --force" in caplog.text
+ hint = config.PAIRING_HINT if os.name == "nt" else "musegadget pair --force"
+ assert hint in caplog.text
def test_a_start_with_an_sdk_token_keeps_a_fresh_token(monkeypatch):
@@ -528,8 +531,9 @@ def warnings_for(sdk_token, pairing, caplog) -> list[str]:
def test_a_token_changed_since_pairing_says_to_pair_again_once(caplog):
pairing = {**fresh_pairing(), "sdk_token_hint": "mgst_AAAAAAA"}
+ hint = config.PAIRING_HINT if os.name == "nt" else "run `musegadget pair --force` to use it"
assert warnings_for("mgst_BBBBBBBtoken", pairing, caplog) == [
- "paired with SDK token mgst_AAAAAAA, not this one; run `musegadget pair --force` to use it"]
+ f"paired with SDK token mgst_AAAAAAA, not this one; {hint}"]
def test_the_token_pairing_used_or_an_older_pairing_says_nothing(caplog):
diff --git a/linux/tests/test_terminal_chat.py b/linux/tests/test_terminal_chat.py
index be1d86953d5113668934edcc0079b55cef50f462..200ab5e21f39b4590d0908115053467d21fa5000 100644
--- a/linux/tests/test_terminal_chat.py
+++ b/linux/tests/test_terminal_chat.py
@@ -17,12 +17,13 @@ from __future__ import annotations
import asyncio
import io
import json
+import os
import tempfile
from pathlib import Path
import pytest
-from musegadget import config, terminal_chat
+from musegadget import config, local_ipc, terminal_chat
from musegadget.executor import Account, Executor
from musegadget.identity import Identity
from musegadget.noise import ApplicationResponse, BodyChunk, ServiceFrame
@@ -146,7 +147,7 @@ def test_live_users_bound_text_storage_and_sequences():
def test_repl_uses_service_transport_and_receives_before_ack(monkeypatch, exit_line, session_id):
async def scenario():
session, vm, stop, session_task = await registered_session()
- with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
+ with tempfile.TemporaryDirectory(dir=None if os.name == "nt" else "/tmp") as tmp:
path = Path(tmp) / "chat.sock"
monkeypatch.setenv(config.SOCKET_ENV, str(path))
service = Service(Identity("02:00:00:00:00:01"), Executor(Account.current()))
@@ -218,7 +219,7 @@ def test_repl_uses_service_transport_and_receives_before_ack(monkeypatch, exit_l
{"op": "subscribe_chat", "session_id": "../invalid"}])
def test_subscription_errors_are_typed(payload):
async def check(service, path):
- reader, writer = await asyncio.open_unix_connection(str(path))
+ reader, writer = await local_ipc.open_connection(path)
writer.write(json.dumps(payload).encode() + b"\n")
await writer.drain()
result = json.loads(await reader.readline())
@@ -246,7 +247,7 @@ def test_subscription_disconnect_releases_upstream():
closed.set()
service._current = Session()
- reader, writer = await asyncio.open_unix_connection(str(path))
+ reader, writer = await local_ipc.open_connection(path)
writer.write(b'{"op":"subscribe_chat"}\n')
await writer.drain()
assert json.loads(await reader.readline()) == {"type": "ready"}
@@ -334,7 +335,7 @@ def test_subscription_failure_ends_client_without_resending(failure):
closed.set()
service._current = Session()
- reader, writer = await asyncio.open_unix_connection(str(path))
+ reader, writer = await local_ipc.open_connection(path)
writer.write(b'{"op":"subscribe_chat"}\n')
await writer.drain()
if failure == "transport":
@@ -411,10 +412,10 @@ def test_rejected_terminal_send_is_reported_and_connections_close(monkeypatch):
writer.close()
await writer.wait_closed()
- with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
+ with tempfile.TemporaryDirectory(dir=None if os.name == "nt" else "/tmp") as tmp:
path = Path(tmp) / "chat.sock"
monkeypatch.setenv(config.SOCKET_ENV, str(path))
- server = await asyncio.start_unix_server(handle, str(path))
+ server = await local_ipc.start_server(handle, path, limit=65536, gid=None)
stdin = asyncio.StreamReader()
stdin.feed_data(b"hello\n")
try:
@@ -433,7 +434,7 @@ def test_rejected_terminal_send_is_reported_and_connections_close(monkeypatch):
def test_follow_ups_are_ordered_and_progress_is_shown(monkeypatch, session_id, combined):
async def scenario():
session, vm, stop, session_task = await registered_session()
- with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
+ with tempfile.TemporaryDirectory(dir=None if os.name == "nt" else "/tmp") as tmp:
path = Path(tmp) / "chat.sock"
monkeypatch.setenv(config.SOCKET_ENV, str(path))
service = Service(Identity("02:00:00:00:00:01"), Executor(Account.current()))
@@ -751,13 +752,12 @@ def test_streaming_during_an_unacknowledged_follow_up_keeps_the_chat_open(monkey
def test_ctrl_c_cancels_the_chat_so_cleanup_runs(monkeypatch):
- import os
import signal
cleaned = []
async def chat(session_id):
try:
- os.kill(os.getpid(), signal.SIGINT)
+ signal.raise_signal(signal.SIGINT)
await asyncio.sleep(5)
finally:
cleaned.append(session_id)
@@ -889,6 +889,7 @@ def test_chat_errors_from_muse_cannot_reach_the_terminal_raw(monkeypatch, capsys
@pytest.mark.parametrize("ending", ["quit", "eof"])
+@pytest.mark.skipif(os.name == "nt", reason="POSIX stdin non-blocking flags")
def test_plain_mode_restores_blocking_stdin(monkeypatch, ending):
import os
import sys
diff --git a/linux/tests/test_terminal_chat_ui.py b/linux/tests/test_terminal_chat_ui.py
index 5e487b351409d0a691717fdad1aa801c5b8df991..42fa647e97e14c7e280b113a5afd774d45039368 100644
--- a/linux/tests/test_terminal_chat_ui.py
+++ b/linux/tests/test_terminal_chat_ui.py
@@ -15,6 +15,7 @@
import asyncio
import curses
import io
+import os
from collections import deque
import pytest
@@ -413,6 +414,7 @@ def test_speaker_colors_use_terminal_background(display, monkeypatch):
@pytest.mark.parametrize('ending', ['quit', 'exit', 'eof', 'interrupt'])
+@pytest.mark.skipif(os.name == "nt", reason="POSIX pseudo-terminal line discipline")
def test_real_terminal_chat_restores_echo_and_line_input(ending):
"""Exercise curses and run_chat together, with real terminal line discipline."""
import os
diff --git a/linux/tests/test_tls.py b/linux/tests/test_tls.py
index 71282b6bf271a110b87134e2aa28d54aca10380c..a8cc21edb7ba9ac9779347f8e5553792e00cb32b 100644
--- a/linux/tests/test_tls.py
+++ b/linux/tests/test_tls.py
@@ -39,6 +39,26 @@ from musegadget import tls
VECTORS = Path(__file__).parent / "vectors" / "distrusted_roots.pem"
+@pytest.fixture(autouse=True)
+def isolate_windows_trust_store(monkeypatch):
+ if os.name == "nt":
+ monkeypatch.setattr(ssl, "enum_certificates", lambda name: [])
+
+
+@pytest.mark.skipif(os.name != "nt", reason="Windows certificate stores")
+def test_windows_checks_both_server_auth_stores(monkeypatch):
+ (g3, compromised), _, (c1, retired), (_, unrelated) = published_roots()
+ stores = {
+ "CA": [(retired, "x509_asn", {ssl.Purpose.SERVER_AUTH.oid})],
+ "ROOT": [(compromised, "x509_asn", True), (unrelated, "x509_asn", set())],
+ }
+ monkeypatch.setattr(ssl, "enum_certificates", stores.__getitem__)
+ use_store(monkeypatch, None, None)
+ assert tls.check_trust_store() == sorted([g3, c1])
+ assert g3 in tls.trust_store_problem()
+ assert c1 in tls.trust_store_warning()
+
+
def published_roots() -> list[tuple[str, bytes]]:
text = VECTORS.read_text()
blocks = re.findall(r"# ([^\n]+)\n(-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----)",
@@ -382,7 +402,10 @@ UNSAFE = ("can't read the system trust store",
@pytest.mark.parametrize("problem", UNSAFE)
-@pytest.mark.parametrize("argv", [["run"], ["pair"], ["voice-call", "--vm-id", "vm-1"]])
+@pytest.mark.parametrize("argv", [
+ ["run"], pytest.param(["pair"], marks=pytest.mark.skipif(os.name == "nt", reason="Linux BLE")),
+ ["voice-call", "--vm-id", "vm-1"],
+])
def test_commands_that_connect_refuse_to_start_on_an_unsafe_trust_store(monkeypatch, capsys, argv, problem):
from unittest.mock import Mock
@@ -423,6 +446,7 @@ def test_the_service_checks_the_trust_store_before_connecting(monkeypatch):
connect.assert_not_called()
+@pytest.mark.skipif(os.name == "nt", reason="Linux BLE")
def test_pairing_checks_the_trust_store_before_opening_setup(monkeypatch):
from unittest.mock import Mock
diff --git a/linux/tests/test_voice_cli.py b/linux/tests/test_voice_cli.py
index ad637985f13e37def8e21cec38b5b63df8710523..90a13ac6076ab5fd9d4b312ced1567e5c6606a49 100644
--- a/linux/tests/test_voice_cli.py
+++ b/linux/tests/test_voice_cli.py
@@ -83,6 +83,7 @@ def test_cli_uses_host_pairing_exact_vm_and_noise_upgrade_app_id(tmp_path, monke
def test_cli_does_not_fall_back_to_default_vm(tmp_path, monkeypatch):
monkeypatch.setenv(config.STATE_DIR_ENV, str(tmp_path / "state"))
+ identity.load_or_create()
config.save_json(config.PAIRING_FILE, {"access_token": "synthetic"})
monkeypatch.setattr(muse_api, "fetch_vms_with_status", lambda *a: (
[{"vm_id": "default", "is_default": True}], 200))
@@ -117,6 +118,7 @@ def test_cli_video_call_signals_over_noise_and_writes_h264(tmp_path, monkeypatch
opus_or_skip()
monkeypatch.setenv(config.STATE_DIR_ENV, str(tmp_path / "state"))
+ identity.load_or_create()
config.save_json(config.PAIRING_FILE, {"access_token": "synthetic", "noise_host": "noise.example"})
monkeypatch.setattr(muse_api, "fetch_vms_with_status", lambda *a: (
[{"vm_id": "target", "vm_auth_token": "synthetic-vm-token"}], 200))
@@ -174,6 +176,7 @@ def test_cli_reports_a_missing_video_player_before_calling(tmp_path, monkeypatch
monkeypatch.setattr(opus, "_opus", lambda: None)
monkeypatch.setenv(config.STATE_DIR_ENV, str(tmp_path / "state"))
+ identity.load_or_create()
config.save_json(config.PAIRING_FILE, {"access_token": "synthetic"})
monkeypatch.setattr("shutil.which", lambda name: None)
monkeypatch.setattr(muse_api, "fetch_vms_with_status", lambda *a: pytest.fail("called Muse"))
@@ -190,6 +193,7 @@ def test_cli_reports_missing_libopus_before_calling(tmp_path, monkeypatch, capsy
raise opus.OpusUnavailable("libopus not found; install it (e.g. apt install libopus0)")
monkeypatch.setenv(config.STATE_DIR_ENV, str(tmp_path / "state"))
+ identity.load_or_create()
config.save_json(config.PAIRING_FILE, {"access_token": "synthetic"})
monkeypatch.setattr(opus, "_opus", missing)
monkeypatch.setattr(muse_api, "fetch_vms_with_status", lambda *a: pytest.fail("called Muse"))
@@ -207,6 +211,7 @@ def test_cli_refuses_video_outputs_that_would_destroy_audio_or_cannot_run(tmp_pa
monkeypatch.setattr(opus, "_opus", lambda: None)
monkeypatch.setenv(config.STATE_DIR_ENV, str(tmp_path / "state"))
+ identity.load_or_create()
config.save_json(config.PAIRING_FILE, {"access_token": "synthetic"})
monkeypatch.setattr(muse_api, "fetch_vms_with_status", lambda *a: pytest.fail("called Muse"))
in_wav = tmp_path / "in.wav"
diff --git a/linux/tests/test_voice_quiet_input.py b/linux/tests/test_voice_quiet_input.py
index af3e130fa9e3e39728bfc95f54415043cbae7fd1..45715150b49fbaec1cf74390cddb11aabb2b4735 100644
--- a/linux/tests/test_voice_quiet_input.py
+++ b/linux/tests/test_voice_quiet_input.py
@@ -25,6 +25,43 @@ from test_voice_call import (Output, TONE, admit, assert_quiet_append, cavd, han
from test_voice_lifecycle import wait_until
+def test_live_input_keeps_the_capture_rate_on_a_coarse_timer(monkeypatch):
+ from types import SimpleNamespace
+ from musegadget import voice_call
+
+ async def scenario():
+ clock = 0.0
+ sent = []
+ monkeypatch.setattr(voice_call, "time", SimpleNamespace(monotonic=lambda: clock, time=lambda: clock))
+
+ async def capture():
+ nonlocal clock
+ for index in range(51):
+ clock = max(clock, index * 0.04)
+ yield TONE
+ raise asyncio.CancelledError
+
+ async def send(event):
+ nonlocal clock
+ sent.append(clock)
+ clock += 0.002
+
+ async def sleep(delay):
+ nonlocal clock
+ if delay > 0:
+ clock += delay + 0.01
+
+ monkeypatch.setattr(voice_call.asyncio, "sleep", sleep)
+ call = VoiceCall(None, device_id="synthetic")
+ call.ready.set()
+ monkeypatch.setattr(call, "_event", send)
+ with pytest.raises(asyncio.CancelledError):
+ await call._input(capture(), realtime=True)
+ assert len(sent) == 51 and 2.0 <= sent[-1] - sent[0] <= 2.011
+
+ asyncio.run(scenario())
+
+
async def three_quiet_frames(vm):
arrived = []
for _ in range(3):
diff --git a/linux/tests/test_wakeword_check.py b/linux/tests/test_wakeword_check.py
index 5b4215b5a28ff7c39713e017b4abb873b4fefa03..74a1ca76234fc70dd7164e144fa0e4ddf7e93666 100644
--- a/linux/tests/test_wakeword_check.py
+++ b/linux/tests/test_wakeword_check.py
@@ -47,6 +47,7 @@ def test_success_report_never_opens_the_microphone(monkeypatch):
def test_audio_dependencies_checked_without_importing_or_opening_audio(monkeypatch):
+ monkeypatch.setattr(checker.sys, "platform", "linux")
monkeypatch.setitem(sys.modules, "sounddevice", None)
monkeypatch.setattr(checker.metadata, "version", lambda name: "synthetic")
monkeypatch.setattr(
@@ -64,6 +65,16 @@ def test_audio_dependencies_checked_without_importing_or_opening_audio(monkeypat
with pytest.raises(checker.CompatibilityError, match="PortAudio is unavailable"):
checker.audio_prerequisites()
+
+def test_windows_audio_uses_the_dll_selected_by_sounddevice(monkeypatch):
+ monkeypatch.setattr(checker.sys, "platform", "win32")
+ monkeypatch.setattr(checker.metadata, "version", lambda name: "synthetic")
+ monkeypatch.setitem(sys.modules, "sounddevice", SimpleNamespace(get_portaudio_version=lambda: (1, "test")))
+ assert checker.audio_prerequisites()["portaudio_available"]
+ monkeypatch.setitem(sys.modules, "sounddevice", None)
+ with pytest.raises(checker.CompatibilityError, match="PortAudio is unavailable"):
+ checker.audio_prerequisites()
+
def no_package(name):
raise checker.metadata.PackageNotFoundError(name)
diff --git a/linux/tests/test_wakeword_cli.py b/linux/tests/test_wakeword_cli.py
index 41b1bb66b4c76c75d7f531eba55b4cb43728480d..c9ff58911a2aac74a7f7820d22aa3f876a1fbb24 100644
--- a/linux/tests/test_wakeword_cli.py
+++ b/linux/tests/test_wakeword_cli.py
@@ -15,7 +15,6 @@
import asyncio
import base64
import json
-import os
import signal
import sys
import wave
@@ -56,6 +55,7 @@ class Detector:
def prepare_audio(tmp_path, monkeypatch, pcm):
monkeypatch.setenv(config.STATE_DIR_ENV, str(tmp_path / "state"))
+ config.save_json(config.IDENTITY_FILE, {"mac": "02:00:00:00:00:01"})
config.save_json(config.PAIRING_FILE, {"access_token": "synthetic"})
monkeypatch.setitem(
sys.modules,
@@ -199,6 +199,7 @@ def test_a_wake_started_video_call_keeps_its_idle_timer(tmp_path, monkeypatch):
await stop.wait()
monkeypatch.setattr(video_call, "VideoCall", Recorder)
+ monkeypatch.setattr("musegadget.rtc.opus.ensure_available", lambda: None)
monkeypatch.setattr(muse_api, "fetch_vms_with_status",
lambda *unused: ([{"vm_id": "target", "vm_auth_token": "synthetic"}], 200))
monkeypatch.setattr(LinkSession, "wait_transport_ready", ready)
@@ -340,7 +341,7 @@ def test_interrupt_during_call_teardown_stops_live_listening(
async def run(self, stop):
await stop.wait()
# Ctrl-C arrives while the transport is still closing.
- os.kill(os.getpid(), signal.SIGINT)
+ signal.raise_signal(signal.SIGINT)
await asyncio.sleep(0.5)
async def wait_transport_ready(self, timeout):
diff --git a/linux/tests/test_windows_client.py b/linux/tests/test_windows_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b473d9eb188c1ea5978ba923968d887807109e4
--- /dev/null
+++ b/linux/tests/test_windows_client.py
@@ -0,0 +1,89 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Native CLI startup with state provisioned by the Linux SDK."""
+
+import errno
+import os
+from pathlib import Path
+from unittest.mock import Mock
+
+import pytest
+
+from musegadget import cli, config, doctor, service
+from musegadget.executor import Account
+
+pytestmark = pytest.mark.skipif(os.name != "nt", reason="Windows client")
+
+
+def test_per_user_paths(monkeypatch, tmp_path):
+ for variable in (config.STATE_DIR_ENV, config.SOCKET_ENV, config.COMMANDS_DIR_ENV):
+ monkeypatch.delenv(variable, raising=False)
+ assert config.state_dir() == Path(os.environ["LOCALAPPDATA"]) / "MuseGadget"
+ monkeypatch.setenv(config.STATE_DIR_ENV, str(tmp_path))
+ assert config.socket_path().parent == tmp_path
+ assert config.commands_dir() == tmp_path / "commands.d"
+
+
+def test_pair_does_not_open_bluetooth_or_overwrite_state(tmp_path, monkeypatch, capsys):
+ monkeypatch.setenv(config.STATE_DIR_ENV, str(tmp_path))
+ saved = tmp_path / config.PAIRING_FILE
+ saved.write_bytes(b"existing-pairing")
+ monkeypatch.setattr(cli, "pair", lambda **kw: pytest.fail("opened Bluetooth pairing"))
+ assert cli.main(["pair", "--force"]) == 1
+ assert "Bluetooth pairing requires Linux" in capsys.readouterr().err
+ assert saved.read_bytes() == b"existing-pairing"
+ assert not (tmp_path / config.IDENTITY_FILE).exists()
+
+
+def test_run_uses_only_the_transferred_identity(tmp_path, monkeypatch, capsys):
+ monkeypatch.setenv(config.STATE_DIR_ENV, str(tmp_path))
+ monkeypatch.delenv(config.SDK_TOKEN_ENV, raising=False)
+ pairing = {"node_id": "gadget-abcdef", "access_token": "test-access",
+ "refresh_token": "test-refresh"}
+ config.save_json(config.PAIRING_FILE, pairing)
+ assert cli.main(["run"]) == 1
+ assert not (tmp_path / config.IDENTITY_FILE).exists()
+ config.save_json(config.IDENTITY_FILE, {"mac": "02:00:00:12:34:56"})
+ assert cli.main(["run"]) == 1
+ assert "same gadget" in capsys.readouterr().err
+ config.save_json(config.IDENTITY_FILE, {"mac": "02:00:00:ab:cd:ef"})
+ token = "mgst_" + "A" * 43
+ (tmp_path / config.SDK_TOKEN_FILE).write_text(token, encoding="utf-8")
+ calls = []
+ monkeypatch.setattr(service, "run_service", lambda *args: calls.append(args))
+ assert cli.main(["run"]) == 0
+ (device, executor, sdk_token), = calls
+ assert device.node_id == pairing["node_id"]
+ assert sdk_token == token
+ assert executor.account == Account.current()
+ assert cli.main(["info"]) == 0
+ assert "gadget-abcdef" in capsys.readouterr().out
+ assert config.load_json(config.PAIRING_FILE) == pairing
+
+ occupied = FileExistsError(errno.EEXIST, "in use", str(config.socket_path()))
+ monkeypatch.setattr(service, "run_service", Mock(side_effect=occupied))
+ assert cli.main(["run"]) == 1
+ assert "Local endpoint already in use" in capsys.readouterr().err
+
+
+def test_windows_doctor_checks_the_transferred_state(tmp_path, monkeypatch):
+ monkeypatch.setenv(config.STATE_DIR_ENV, str(tmp_path))
+ monkeypatch.delenv(config.SDK_TOKEN_ENV, raising=False)
+ config.save_json(config.IDENTITY_FILE, {"mac": "02:00:00:12:34:56"})
+ config.save_json(config.PAIRING_FILE, {"access_token": "test-access", "refresh_token": "test-refresh"})
+ (tmp_path / config.SDK_TOKEN_FILE).write_text("mgst_" + "A" * 43)
+ monkeypatch.setattr(doctor.network, "is_online", lambda **kw: True)
+ assert [(r["name"], r["status"]) for r in doctor.run_checks()] == [
+ ("Pairing", "OK"), ("SDK token", "OK"), ("Muse API TCP", "OK"), ("Root CAs", "OK")]
diff --git a/linux/tests/test_windows_executor.py b/linux/tests/test_windows_executor.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbcaa47d1904e73212e37e942fe609fbf2da220b
--- /dev/null
+++ b/linux/tests/test_windows_executor.py
@@ -0,0 +1,108 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# SPDX-License-Identifier: Apache-2.0
+
+import base64
+import hashlib
+import json
+import os
+import sys
+
+import pytest
+
+from musegadget import commands
+from musegadget.executor import Account, Executor, MAX_OUTPUT_BYTES
+
+pytestmark = pytest.mark.skipif(os.name != "nt", reason="Windows command processes and filesystem")
+
+
+def test_shell_uses_cmd_and_the_requested_directory(tmp_path):
+ payload = Executor(Account.current()).run("system.run", {
+ "command": 'cd & echo "two words" & (echo error)>&2 & exit /b 7', "cwd": str(tmp_path),
+ })["payload"]
+ assert os.path.samefile(payload["stdout"].splitlines()[0], tmp_path)
+ assert '"two words"' in payload["stdout"]
+ assert payload["stderr"].strip() == "error"
+ assert payload["exit_code"] == 7 and not payload["timed_out"]
+
+
+def test_timeout_terminates_descendants(tmp_path):
+ import psutil
+
+ child_pid = tmp_path / "pid"
+ body = ("import pathlib,subprocess,sys,time;"
+ "p=subprocess.Popen([sys.executable,'-c','import time;time.sleep(30)']);"
+ "pathlib.Path('pid').write_text(str(p.pid));time.sleep(30)")
+ ex = Executor(Account.current())
+ try:
+ _, _, _, timed_out = ex._run_child([sys.executable, "-c", body], str(tmp_path), 2)
+ assert timed_out
+ pid = int(child_pid.read_text())
+ assert not psutil.pid_exists(pid)
+ finally:
+ if child_pid.exists():
+ pid = int(child_pid.read_text())
+ if psutil.pid_exists(pid):
+ psutil.Process(pid).kill()
+
+
+def test_command_definitions_use_argv_and_bounded_duplex_io(tmp_path, monkeypatch):
+ monkeypatch.setenv("MUSEGADGET_SDK_TOKEN", "private")
+ (tmp_path / "pump.read.json").write_text(json.dumps({
+ "description": "Read pump", "required": {"x": {"type": "string", "description": "input"}},
+ "exec": [sys.executable, "-c",
+ "import json,os,sys;sys.stderr.write('e'*200000);"
+ "assert len(json.load(sys.stdin)['x'])==300000;"
+ "assert 'MUSEGADGET_SDK_TOKEN' not in os.environ;"
+ "assert sys.argv[1]=='two & words';sys.stdout.write('o'*200000)", "two & words"],
+ }))
+ ex = Executor(Account.current(), commands.load(tmp_path))
+ assert "pump.read" in ex.specs()
+ result = ex.run("pump.read", {"x": "x" * 300000})
+ assert result == {"ok": True, "payload": {"output": "o" * MAX_OUTPUT_BYTES, "truncated": True}}
+
+
+def test_file_transfer_preserves_target_and_its_acl_until_verified(tmp_path):
+ import win32security
+
+ def dacl(path):
+ flags = win32security.DACL_SECURITY_INFORMATION
+ desc = win32security.GetNamedSecurityInfo(str(path), win32security.SE_FILE_OBJECT, flags)
+ acl = desc.GetSecurityDescriptorDacl()
+ return [acl.GetAce(i) for i in range(acl.GetAceCount())]
+
+ ex = Executor(Account.current())
+ target = tmp_path / "output.bin"
+ target.write_bytes(b"previous")
+ expected_acl = dacl(target)
+ content = bytes(range(256)) * 256
+ chunk = {"path": str(target), "data_b64": base64.b64encode(content).decode()}
+ assert ex.run("file.write", chunk)["payload"]["received"] == len(content)
+ assert target.read_bytes() == b"previous"
+ assert not ex.run("file.write", {**chunk, "offset": 1})["ok"]
+ final = {"path": str(target), "data_b64": "", "offset": len(content), "final": True}
+ assert not ex.run("file.write", {**final, "sha256": "00"})["ok"]
+ assert target.read_bytes() == b"previous"
+ assert not ex.run("file.write", {**chunk, "final": True, "overwrite": False})["ok"]
+ assert target.read_bytes() == b"previous"
+ assert ex.run("file.write", {**chunk, "final": True, "sha256": hashlib.sha256(content).hexdigest()})["ok"]
+ assert dacl(target) == expected_acl
+ result = ex.run("file.read", {"path": str(target)})["payload"]
+ assert result["eof"] and base64.b64decode(result["data_b64"]) == content
+ assert list(tmp_path.iterdir()) == [target]
+
+
+def test_file_transfer_rejects_a_preexisting_non_private_stage(tmp_path):
+ target = tmp_path / "notes"
+ stage = tmp_path / ".notes.musegadget-partial"
+ stage.mkdir()
+ (stage / "contents").write_bytes(b"original")
+ result = Executor(Account.current()).run("file.write", {"path": str(target), "data_b64": "dA=="})
+ assert not result["ok"] and (stage / "contents").read_bytes() == b"original"
+ assert not target.exists()
+
+
+def test_health_reports_windows_uptime_memory_and_disk():
+ health = Executor(Account.current()).run("device.health", {})["payload"]
+ assert health["hostname"] and health["version"] and health["uptime_s"] >= 0
+ assert 0 <= health["memory_mb"]["available"] <= health["memory_mb"]["total"]
+ assert 0 <= health["disk_gb"]["free"] <= health["disk_gb"]["total"]
diff --git a/linux/tests/test_windows_ipc.py b/linux/tests/test_windows_ipc.py
new file mode 100644
index 0000000000000000000000000000000000000000..5372e554f65b9702da09444b5b9546c4f5468b35
--- /dev/null
+++ b/linux/tests/test_windows_ipc.py
@@ -0,0 +1,110 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import asyncio
+import os
+
+import pytest
+
+from musegadget import local_ipc
+
+pytestmark = pytest.mark.skipif(os.name != "nt", reason="Windows local transport and console")
+
+
+def test_only_authenticated_clients_reach_the_service(tmp_path):
+ async def scenario():
+ lines = []
+
+ async def echo(reader, writer):
+ lines.append(await reader.readline())
+ writer.write(lines[-1])
+ await writer.drain()
+
+ path = tmp_path / "endpoint"
+ server = await local_ipc.start_server(echo, path, limit=1024, gid=None)
+ try:
+ with pytest.raises(FileExistsError):
+ await local_ipc.start_server(echo, path, limit=1024, gid=None)
+ address, port = server.sockets[0].getsockname()
+ assert address == "127.0.0.1"
+ reader, writer = await asyncio.open_connection(address, port)
+ writer.write(bytes(32))
+ await reader.readexactly(64)
+ writer.write(bytes(32) + b'{"message":"untrusted"}\n')
+ assert await reader.read() == b""
+ writer.close()
+ assert lines == []
+
+ reader, writer = await local_ipc.open_connection(path)
+ writer.write(b'{"message":"trusted"}\n')
+ assert await reader.readline() == b'{"message":"trusted"}\n'
+ assert lines == [b'{"message":"trusted"}\n']
+ writer.close()
+ finally:
+ server.close()
+ await server.wait_closed()
+ assert not path.exists()
+
+ asyncio.run(asyncio.wait_for(scenario(), 5))
+
+
+def test_client_authenticates_the_service_and_rejects_invalid_endpoints(tmp_path):
+ import win32crypt
+
+ async def scenario():
+ async def impersonator(reader, writer):
+ await reader.readexactly(32)
+ writer.write(bytes(64))
+ await writer.drain()
+ writer.close()
+
+ server = await asyncio.start_server(impersonator, "127.0.0.1", 0)
+ path = tmp_path / "endpoint"
+ try:
+ data = local_ipc._ENDPOINT.pack(server.sockets[0].getsockname()[1], os.urandom(32))
+ path.write_bytes(win32crypt.CryptProtectData(data, "", None, None, None, 1))
+ with pytest.raises(ConnectionError, match="authentication failed"):
+ await local_ipc.open_connection(path)
+ path.write_bytes(b"ordinary file")
+ with pytest.raises(ConnectionError, match="Windows user"):
+ await local_ipc.open_connection(path)
+ assert path.read_bytes() == b"ordinary file"
+ finally:
+ server.close()
+ await server.wait_closed()
+
+ asyncio.run(asyncio.wait_for(scenario(), 5))
+
+
+def test_redirected_input_can_cancel_a_blocked_read():
+ from musegadget.windows_input import WindowsInput
+
+ async def scenario():
+ rd, wr = os.pipe()
+ with os.fdopen(rd, "r", encoding="utf-8") as stream:
+ try:
+ source = WindowsInput(stream, 100)
+ os.write(wr, b"first\n")
+ assert await source.readline() == b"first\n"
+ pending = asyncio.create_task(source.readline())
+ await asyncio.sleep(0.05)
+ pending.cancel()
+ await asyncio.wait({pending}, timeout=2)
+ assert pending.cancelled()
+ os.write(wr, b"next\n")
+ assert await source.readline() == b"next\n"
+ finally:
+ os.close(wr)
+
+ asyncio.run(scenario())
diff --git a/linux/wakeword/build.sh b/linux/wakeword/build.sh
index 64acc791dbda1f26238aae1561da420feb3acfee..1ce67a4119c78249b8e55f4e5723a6c821aa6c44 100755
--- a/linux/wakeword/build.sh
+++ b/linux/wakeword/build.sh
@@ -13,7 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-# Builds the native Hey Muse runner for Linux: libmuse_wakeword.so (what
+# Builds the native Hey Muse runner: libmuse_wakeword.so or muse_wakeword.dll (what
# musegadget.wakeword loads) and ww-run (the same runner on a WAV or raw
# PCM file, for checks).
#
@@ -164,7 +164,12 @@ add c++ "$WW/ww_runner_espnn.cpp" -I"$WW" -I"$WW/include" "${INC_ET[@]}" "${ETDE
add cc "$HERE/ww_resample.c" -ffp-contract=off
# The model, embedded 16-aligned as in the firmware.
pte="$WW/models/hey_muse.pte"
-sed -e "s|@HEY_MUSE_PTE_PATH@|$pte|" -e "s|@HEY_MUSE_PTE_LEN@|$(stat -c %s "$pte")|" \
+model_path=$pte
+case "$("$CC" -dumpmachine)" in
+ *mingw*|*windows-gnu*) windows=1; model_path=$(cygpath -m "$pte") ;;
+ *) windows=0 ;;
+esac
+sed -e "s|@HEY_MUSE_PTE_PATH@|$model_path|" -e "s|@HEY_MUSE_PTE_LEN@|$(stat -c %s "$pte")|" \
"$WW/hey_muse_pte.S.in" > "$OBJ/hey_muse_pte.S"
add cc "$OBJ/hey_muse_pte.S"
for pid in "${pids[@]}"; do
@@ -174,12 +179,26 @@ done
printf 'Compiled %d files\n' "$n"
objs=("$OBJ"/*.o)
-cat > "$OBJ/exports.map" <<'EOF'
-{ global: ww_runner_create; ww_runner_destroy; ww_runner_reset; ww_runner_feed;
- ww_runner_set_listening; ww_runner_set_suppressed; ww_runner_ok;
- ww_runner_set_score_hook; muse_ww_resampler_create; muse_ww_resampler_destroy;
- muse_ww_resampler_reset; muse_ww_resampler_feed; local: *; };
-EOF
+exports=(ww_runner_create ww_runner_destroy ww_runner_reset ww_runner_feed
+ ww_runner_set_listening ww_runner_set_suppressed ww_runner_ok ww_runner_set_score_hook
+ muse_ww_resampler_create muse_ww_resampler_destroy muse_ww_resampler_reset muse_ww_resampler_feed)
+if (( windows )); then
+ # Link the C++ runtime statically, so a native Python installation
+ # can load the DLL without the compiler's bin directory in its path.
+ printf '%s\n' EXPORTS "${exports[@]}" > "$OBJ/exports.def"
+ "$CXX" -shared -static -o "$OBJ/muse_wakeword.dll" "${objs[@]}" "$OBJ/exports.def" \
+ -Wl,--gc-sections -Wl,--out-implib,"$OBJ/muse_wakeword.a" -lwinpthread
+ "$CC" -O2 -std=c11 -I"$WW/include" "$HERE/tools/ww_run.c" "$OBJ/muse_wakeword.a" -o "$OBJ/ww-run.exe"
+ mv -- "$OBJ/muse_wakeword.dll" "$OUT/muse_wakeword.dll"
+ mv -- "$OBJ/ww-run.exe" "$OUT/ww-run.exe"
+ printf 'Built %s and %s\n' "$OUT/muse_wakeword.dll" "$OUT/ww-run.exe"
+ exit 0
+fi
+{
+ printf '{ global:\n'
+ printf ' %s;\n' "${exports[@]}"
+ printf ' local: *; };\n'
+} > "$OBJ/exports.map"
"$CXX" -shared -o "$OUT/libmuse_wakeword.so.part" "${objs[@]}" -Wl,--gc-sections -Wl,-O1 \
-Wl,--version-script="$OBJ/exports.map" -Wl,-z,defs -Wl,-z,noexecstack -Wl,-z,relro,-z,now -lm
"${STRIP:-strip}" --strip-unneeded "$OUT/libmuse_wakeword.so.part" 2>/dev/null || true
diff --git a/linux/wakeword/tests/test_wrapper.py b/linux/wakeword/tests/test_wrapper.py
index f7c538492edb8d2711af36d961a5c6d8d556cffc..346d2f555dcc6c82ad29907e9454ad3f416163fd 100644
--- a/linux/wakeword/tests/test_wrapper.py
+++ b/linux/wakeword/tests/test_wrapper.py
@@ -27,6 +27,7 @@ import ast
import math
import os
import struct
+import subprocess
import sys
import unittest
import warnings
@@ -44,6 +45,7 @@ from musegadget.wakeword import ( # noqa: E402
)
MODEL = ROOT.parent / "esp32" / "components" / "muse_wakeword" / "models" / "hey_muse.pte"
+LIBRARY_NAME = "muse_wakeword.dll" if sys.platform == "win32" else "libmuse_wakeword.so"
def library_available() -> bool:
@@ -76,13 +78,15 @@ class ContractTests(unittest.TestCase):
def test_an_empty_model_file_is_refused_not_replaced(self):
import tempfile
- with tempfile.NamedTemporaryFile(suffix=".pte") as f:
+ with tempfile.TemporaryDirectory() as directory:
+ model = Path(directory) / "empty.pte"
+ model.touch()
with self.assertRaises(WakeWordUnavailableError):
- WakeWordDetector(model_path=f.name)
+ WakeWordDetector(model_path=model)
def test_missing_library_is_actionable(self):
with patch.dict(os.environ, {"MUSE_WAKEWORD_LIBRARY": "/nonexistent/library.so"}):
- with self.assertRaisesRegex(WakeWordUnavailableError, "setup.sh"):
+ with self.assertRaisesRegex(WakeWordUnavailableError, "MUSE_WAKEWORD_LIBRARY"):
WakeWordDetector()
def test_library_lookup_order(self):
@@ -90,10 +94,10 @@ class ContractTests(unittest.TestCase):
os.environ.pop("MUSE_WAKEWORD_LIBRARY", None)
with patch.object(sys, "prefix", "/opt/env"):
found = _candidates()
- self.assertEqual(found[0], Path("/opt/env/lib/musegadget/libmuse_wakeword.so"))
- self.assertEqual(found[1].parts[-3:], ("wakeword", "build", "libmuse_wakeword.so"))
+ self.assertEqual(found[0], Path("/opt/env/lib/musegadget") / LIBRARY_NAME)
+ self.assertEqual(found[1].parts[-3:], ("wakeword", "build", LIBRARY_NAME))
with patch.dict(os.environ, {"MUSE_WAKEWORD_LIBRARY": "/x/lib.so"}):
- self.assertEqual(_candidates(), [Path("/x/lib.so")])
+ self.assertEqual(_candidates(), [Path("/x/lib.so").absolute()])
# A file in the current directory stays that file, not a bare name
# ctypes would look up on the loader's search path.
with patch.dict(os.environ, {"MUSE_WAKEWORD_LIBRARY": "./lib.so"}):
@@ -109,14 +113,15 @@ class ContractTests(unittest.TestCase):
f.truncate(_MAX_MODEL_BYTES + 1)
with self.assertRaises(OSError):
_read_model(big)
- # A FIFO with no writer: opening it must neither block nor read.
- fifo = Path(tmp) / "fifo.pte"
- os.mkfifo(fifo)
- with self.assertRaisesRegex(OSError, "not a regular file"):
- _read_model(fifo)
+ if hasattr(os, "mkfifo"):
+ # A FIFO with no writer: opening it must neither block nor read.
+ fifo = Path(tmp) / "fifo.pte"
+ os.mkfifo(fifo)
+ with self.assertRaisesRegex(OSError, "not a regular file"):
+ _read_model(fifo)
small = Path(tmp) / "small.pte"
- small.write_bytes(b"x" * 10)
- self.assertEqual(_read_model(small), b"x" * 10)
+ small.write_bytes(b"\r\n\x1a\x00")
+ self.assertEqual(_read_model(small), b"\r\n\x1a\x00")
def test_import_loads_nothing(self):
tree = ast.parse((ROOT / "src/musegadget/wakeword.py").read_text())
@@ -176,11 +181,11 @@ class NativeLibraryTests(unittest.TestCase):
def test_a_file_that_is_not_the_model_is_refused(self):
import tempfile
- with tempfile.NamedTemporaryFile(suffix=".pte") as f:
- f.write(MODEL.read_bytes()[:4096])
- f.flush()
+ with tempfile.TemporaryDirectory() as directory:
+ model = Path(directory) / "truncated.pte"
+ model.write_bytes(MODEL.read_bytes()[:4096])
with self.assertRaises(WakeWordUnavailableError):
- detector(model_path=f.name)
+ detector(model_path=model)
def test_the_environment_copy_is_found_without_an_override(self):
import shutil
@@ -188,14 +193,17 @@ class NativeLibraryTests(unittest.TestCase):
built = next(path for path in _candidates() if path.is_file())
with tempfile.TemporaryDirectory() as prefix:
- copy = Path(prefix) / "lib" / "musegadget" / "libmuse_wakeword.so"
+ copy = Path(prefix) / "lib" / "musegadget" / LIBRARY_NAME
copy.parent.mkdir(parents=True)
shutil.copyfile(built, copy)
environment = {k: v for k, v in os.environ.items() if k != "MUSE_WAKEWORD_LIBRARY"}
- with patch.dict(os.environ, environment, clear=True), patch.object(sys, "prefix", prefix):
- self.assertEqual(_candidates()[0], copy)
- with detector() as d:
- self.assertFalse(d.feed(tones(1.0)))
+ # The subprocess releases the DLL before the temporary directory is removed.
+ environment["PYTHONPATH"] = str(ROOT / "src")
+ subprocess.run([sys.executable, "-c",
+ "import sys; from musegadget.wakeword import _candidates, WakeWordDetector; "
+ "sys.prefix = sys.argv[1]; assert str(_candidates()[0]) == sys.argv[2]; "
+ "assert not WakeWordDetector().feed(bytes(32000))",
+ prefix, str(copy)], check=True, env=environment)
def test_a_model_planning_huge_buffers_is_refused(self):
# forward's two planned buffers declared at 2 GiB and 2 GiB + 32,
@@ -206,11 +214,11 @@ class NativeLibraryTests(unittest.TestCase):
for offset, fmt, value in ((0x10, "