diff --git a/NOTICE.md b/NOTICE.md index f52d1dd..afd55a3 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -75,3 +75,15 @@ All seven resolved runtime packages, including transitive packages, appear in `about credits` / `about licenses`. Self-contained runtime notices are additionally included by CI under `third-party/dotnet`. No affiliate relationship is implied; manufacturer links are ordinary URLs. + +## Storage and firmware protocols (2026-11-30) + +`Firmware.cs`, `UsbStorage.cs` and `Read2Me.cs` adapt the package validation, +SPS1/SPI1 USB messages and READ2ME v1 protocol described by upstream +`src/sidepulse/firmware.py`, `usb_control.py`, `storage.py`, and +`_vendor/read2me.py` at `4ebe1a3849c8098b87e7ef9436d9d2f875df8e46`. +Copyright (c) 2026 Peter Kuhar, MIT; the license is retained in +`third-party/inteliwear-sidepulse/LICENSE`. Windows aligned uncached I/O and +SPN command integration are implemented here. Firmware images are downloaded +from the official upstream repository or supplied by the user; none are embedded. +libusb is an optional externally installed Linux/macOS component, not bundled. diff --git a/README.md b/README.md index f328678..e230e45 100644 --- a/README.md +++ b/README.md @@ -156,3 +156,19 @@ host first and confirm `installed` before restarting it. See publish a release. A matching version tag or manual Prepare release run on `main` builds and verifies six archives, then creates an unpublished release draft. Publishing the reviewed draft is a separate explicit release action. + +### Device storage and firmware + +```text +spn storage status --json +spn storage off --device SPD-000006 +spn firmware version --json +spn firmware upgrade --device E:\ --dry-run +spn firmware upgrade --device E:\ +``` + +Firmware packages are verified against checksums and the device model/version. +Windows read-only Pro updates use `--read-only`; raw Dot USB control currently +supports Linux/macOS with system libusb. A safe Windows USB backend remains open. Storage on/off saves the preference; safely eject and +reconnect to apply it. See [device protocols](docs/wiki/Devices-and-Protocols.md) +for prerequisites, transfer semantics and hardware acceptance limits. diff --git a/docs/reviews/upstream-2026-11-30.md b/docs/reviews/upstream-2026-11-30.md new file mode 100644 index 0000000..91601e0 --- /dev/null +++ b/docs/reviews/upstream-2026-11-30.md @@ -0,0 +1,25 @@ +# Upstream review — 2026-11-30 + +Reviewed target: `inteliwear/sidepulse@4ebe1a3849c8098b87e7ef9436d9d2f875df8e46`. +The watch issue #72 reports 103 commits since the previous baseline. This is a +partial port, so `upstream.json` retains its previous baseline until the remaining +items have been assessed and dispositioned. + +| Change | SPN disposition | +|---|---| +| SPS1 persisted storage status/on/off; SPI1 Dot USB discovery | #77 adds explicit serial/USB selection and acknowledged preference saves. Linux/macOS use libusb. Safe Windows raw control is blocked pending #82; mounted-volume ejection remains #79. | +| Verified customer OTA ZIPs, batch upgrade, model/version guards | #77 adds online/local packages, bounded downloads, complete checksums, multi-device preflight and no downgrade. | +| Read-only Pro transfer | #77 implements Windows aligned uncached READ2ME v1; native symbol probe fails closed. Other read-only platforms and physical acceptance remain #78. | +| Storage-disabled Dot firmware | #77 temporarily enables a uniquely identified Dot drive, restores its saved preference before image bytes and matches serial/version after reconnect. | +| Direct SPC2 live LEDs and unmounted devices in normal delivery | Deferred: #11 / #3. Firmware/storage USB access does not imply that `state`/`write` can use raw USB. | +| OSC 7501 program status, PTY forwarding and terminal/session presentation | #80; requires schema fixtures and a compatibility design with SPN host lifecycle. | +| New Antigravity/Herdr/T3 Code hooks; Cursor/Grok/Junie improvements; terminal opening | #80 plus existing #41–44. No copied adapter is presented as tested. | +| OpenCode event ordering/hot reload, Codex trust entries/memory jobs/plan waits, Claude compaction/browser waits | #80 / #40 / #30; audit against SPN adapters before changing session state rules. | +| Android pairing and remote transports | Existing #46 / #45; retain current iPhone boundaries. | +| Dark hours, battery, platform helpers and Neon animations | #80, #50, #47; review UX, grammar vectors and attribution before porting. | +| Platform installers, VM tests and daemon refactoring | Reference material for #18, #25 and #40; SPN keeps its own install/host contracts. | + +Firmware protocol code is adapted with the retained upstream MIT notice. Images +are neither embedded nor redistributed by this change. Package hashes establish +integrity against the selected upstream source, not an independent signature. +No firmware was sent to physical hardware during development. diff --git a/docs/wiki/Devices-and-Protocols.md b/docs/wiki/Devices-and-Protocols.md index 53b96ae..8ac536d 100644 --- a/docs/wiki/Devices-and-Protocols.md +++ b/docs/wiki/Devices-and-Protocols.md @@ -39,3 +39,76 @@ A later migration or relay feature must preserve source machine identity. Protocol fixtures should be derived from the pinned upstream source revision and redacted captures, with attribution recorded alongside them. + +## Firmware updates + +```text +spn firmware version --json +spn firmware upgrade --device E:\ --dry-run +spn firmware upgrade --device E:\ +spn firmware upgrade --device E:\ --release-version 1.1.17 +spn firmware upgrade --device E:\ --file sidepulse-dot-1.1.17-ota.zip +spn firmware upgrade --device E:\ --read-only +spn firmware upgrade --all --dry-run +``` + +`--release-version` selects firmware; SPN reserves `--version` for its own version. +The default source is the official `inteliwear/sidepulse` firmware directory. +Downloads and expanded packages are limited to 4 MiB. SPN checks the published +ZIP SHA-256, every embedded file checksum, archive layout, package/model/version, +connected device identity and downgrade protection before writing. SHA-256 detects +corruption; these packages do not provide an independent publisher signature. +Local ZIPs are checked against their internal checksums and model/version header. + +Dry-run validates without creating device files or changing storage preferences. +Unknown or repeated maintenance options fail before hardware access. Multiple +devices require explicit selection or `--all`; all packages are verified first. +Stop the SPN host and other LED writers before upgrading. SPN serializes its own +file writes and holds the device lock for ten seconds after sending firmware. +A transferred image is **not** confirmed installation: keep connected, then +reconnect and run `firmware version` to verify the installed version. Failed or +ambiguous transfers are never automatically replayed. + +Writable mounted Dot and Pro updates use a flushed `FIRMWARE.BIN` file on all +platforms, including Windows. A read-only **Pro** can use `--read-only` on Windows: +SPN reads aligned 512-byte sectors of `setup.html` with `FILE_FLAG_NO_BUFFERING`, +probes exact symbol delivery, and validates chunk/completion acknowledgements and +CRC. It refuses other sector sizes and cached/aggregated reads before uploading. +This Windows hardware path still needs physical-device acceptance; unit and CI +checks do not prove that a particular Windows storage stack supports it. The +read-only channel is currently Windows-only. Dot firmware requires writable storage. + +## Dot USB storage + +```text +spn storage status --json +spn storage off --device SPD-000006 +spn storage on --device SPD-000006 +spn storage on --device SPD-000006 --reconnect +``` + +Requires Dot firmware supporting SPI1/SPS1. Select by production serial or +`usb:BUS:ADDRESS`. Pro does not support this setting. `Saved` is the persisted +preference; `Active` is the current USB configuration. `on/off` saves the setting +and verifies acknowledgement. Safely eject any mounted Dot drive, then unplug and +reconnect to apply it. `--reconnect` can enable storage when it is already inactive; +it refuses to detach active storage. Unlike upstream macOS/Linux, SPN does not yet +automatically eject a mounted drive. No filesystem is forcibly unmounted. + +USB control currently supports Linux/macOS with externally installed libusb 1.0. +Linux needs permission for VID `1a86`, PID `fe10`; macOS can use Homebrew libusb. +Windows Dot storage control is rejected **before** loading a native backend: +libusb's UsbDk backend captures the entire device on open and detaches it from +Windows PnP/storage drivers, even for a status query. SPN must not do that to a +mounted drive. Keep the normal mass-storage driver; do not replace it with +WinUSB/Zadig. A safe Windows control backend remains open in #82. Mounted Windows firmware +updates and the Windows read-only Pro channel do not require libusb/UsbDk. +SPN never installs drivers, claims interfaces, detaches kernel drivers, or resets +arbitrary USB devices. + +`firmware version` also discovers storage-disabled Dots when USB access is available. +A USB-selected Dot upgrade requires a unique production serial. SPN temporarily +enables storage, verifies the reconnected serial/version, restores the saved +storage-off preference **before** sending image bytes, and matches the mounted drive. +If storage preparation fails, no firmware bytes are sent. Read the error and check +`storage status` before retrying. Hardware acceptance for these paths remains open. diff --git a/scripts/cli_smoke.py b/scripts/cli_smoke.py index cada94b..d051b75 100644 --- a/scripts/cli_smoke.py +++ b/scripts/cli_smoke.py @@ -1,5 +1,7 @@ """Exercise published CLI, local hooks and a simulated device without hardware.""" import json +import hashlib +import zipfile import os from pathlib import Path import subprocess @@ -8,6 +10,43 @@ import time +def firmware_checks(exe, environment): + with tempfile.TemporaryDirectory(prefix='SidePulse firmware ü ') as directory: + root = Path(directory) + device = root / 'device' + device.mkdir() + (device / 'STATUS.TXT').write_text('app_version 1.1.16\nserial SPD-000123\n', encoding='utf-8') + payload = bytes(range(256)) * 3 + files = {'FIRMWARE.BIN': payload, + 'README.txt': b'SidePulse Dot firmware update - version 1.1.17\n', + 'RELEASE_NOTES.txt': b'Smoke fixture\n'} + files['SHA256SUMS.txt'] = '\n'.join(hashlib.sha256(data).hexdigest() + ' ' + name for name, data in files.items()).encode() + package = root / 'sidepulse-dot-1.1.17-ota.zip' + with zipfile.ZipFile(package, 'w') as archive: + for name, data in files.items(): + archive.writestr(name, data) + env = dict(environment, SIDEPULSE_NET_HOME=str(root / 'config')) + def invoke(*args, success=True): + response = subprocess.run([exe, *args, '--json'], env=env, capture_output=True, text=True, timeout=25) + assert (response.returncode == 0) == success, (args, response.stdout, response.stderr) + return json.loads(response.stdout if success else response.stderr) + version = invoke('firmware', 'version', '--device', str(device)) + assert version[0]['Serial'] == 'SPD-000123' + result = invoke('firmware', 'upgrade', '--device', str(device), '--file', str(package), '--dry-run') + assert result[0]['State'] == 'verified' and result[0]['DryRun'] + assert not (device / 'FIRMWARE.BIN').exists() and not (root / 'config').exists() + for option in ('--dryrun', '--dry-run=false', '--file='): + invoke('firmware', 'upgrade', '--device', str(device), option, success=False) + assert not (device / 'FIRMWARE.BIN').exists() + invoke('storage', 'status', '--unknown', success=False) + result = invoke('firmware', 'upgrade', '--device', str(device), '--file', str(package)) + assert result[0]['State'] == 'transferred-reconnect-to-confirm' + assert (device / 'FIRMWARE.BIN').read_bytes() == payload + (device / 'STATUS.TXT').write_text('app_version 1.1.18\nserial SPD-000123\n', encoding='utf-8') + invoke('firmware', 'upgrade', '--device', str(device), '--file', str(package), success=False) + assert (device / 'FIRMWARE.BIN').read_bytes() == payload + + def main(): exe = str(Path(sys.argv[1]).resolve()) @@ -18,6 +57,7 @@ def run(*args, input=None): assert result.returncode == 0, (args, result.stdout, result.stderr) return result + firmware_checks(exe, child_env) version = run('--version').stdout assert version and version == run('-v').stdout assert run('--version', '--quiet').stdout == '' diff --git a/scripts/install_smoke.py b/scripts/install_smoke.py index 8c9facb..b2dec69 100644 --- a/scripts/install_smoke.py +++ b/scripts/install_smoke.py @@ -10,6 +10,20 @@ import time +def remove_tree(path, timeout=10): + # Windows can retain an executable image lock briefly after its process exits. + # Retry only sharing/lock violations, and preserve permanent failures. + deadline = time.monotonic() + timeout + while True: + try: + shutil.rmtree(path) + return + except OSError as error: + if getattr(error, 'winerror', None) not in (32, 33) or time.monotonic() >= deadline: + raise + time.sleep(0.1) + + def main(executable): source = Path(executable).resolve() if os.name == 'nt' and os.environ.get('SIDEPULSE_INSTALL_SYSTEM_TESTS') != '1': @@ -76,7 +90,7 @@ def run(exe, *args, success=True, extra_env=None): assert Path(registration['Backup']).read_bytes() == original_profile assert profile.read_text().count('# >>> SidePulse.NET PATH >>>') == 1 profile.write_bytes(profile.read_bytes() + b'# Added after installation\n') - shutil.rmtree(download) + remove_tree(download) unrelated = root / 'unrelated working directory' unrelated.mkdir() fresh_env = dict(env) @@ -117,13 +131,8 @@ def run(exe, *args, success=True, extra_env=None): assert Path(registration['Backup']).exists() else: assert user_path() == original_path, 'User PATH or its registry type was not restored exactly' - # Give the detached Windows helper time to close its executable before cleanup. - for attempt in range(100): - try: - shutil.rmtree(job) - break - except PermissionError: - time.sleep(0.1) + # Result publication can precede the detached helper releasing its image. + remove_tree(job) print('Single-file offline resources, install/PATH preview, conflicts, idempotence, stable hooks and owned uninstall passed.') diff --git a/scripts/json_compatibility.py b/scripts/json_compatibility.py index 550ba28..645269c 100644 --- a/scripts/json_compatibility.py +++ b/scripts/json_compatibility.py @@ -27,6 +27,15 @@ def normalize(value, executable): if isinstance(value, dict): + # This reviewed notice is appended with the new protocol implementation. + # Preserve exact comparison of all pre-existing notice text and fields. + if set(value) == {'name', 'text'} and value['name'].endswith('NOTICE.md') and value['text']: + marker = '\n## Storage and firmware protocols (2026-11-30)\n' + notice = (Path(__file__).resolve().parents[1] / 'NOTICE.md').read_text(encoding='utf-8') + if marker in notice: + appendix = marker + notice.split(marker, 1)[1] + if value['text'].endswith(appendix): + value = dict(value, text=value['text'][:-len(appendix)]) # Explicit reviewed dependency upgrades change inventory values, not its schema. # Keep all other fields and all unlisted version changes under exact comparison. transitions = {('QRCoder', '1.8.1'): '1.9.0', diff --git a/scripts/tests/test_install_smoke.py b/scripts/tests/test_install_smoke.py new file mode 100644 index 0000000..98fb083 --- /dev/null +++ b/scripts/tests/test_install_smoke.py @@ -0,0 +1,30 @@ +from pathlib import Path +import sys +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from install_smoke import remove_tree + + +class InstallSmokeTests(unittest.TestCase): + def error(self, code): + error = PermissionError('fixture Windows error') + error.winerror = code + return error + + def test_exited_process_image_lock_can_clear_before_cleanup(self): + with patch('install_smoke.shutil.rmtree', side_effect=[self.error(32), None]) as remove, patch('install_smoke.time.sleep'): + remove_tree('fixture') + self.assertEqual(2, remove.call_count) + + def test_access_denied_is_not_hidden_as_a_transient_lock(self): + with patch('install_smoke.shutil.rmtree', side_effect=self.error(5)) as remove: + with self.assertRaises(PermissionError): + remove_tree('fixture') + self.assertEqual(1, remove.call_count) + + def test_persistent_sharing_violation_still_fails_acceptance(self): + with patch('install_smoke.shutil.rmtree', side_effect=self.error(32)): + with self.assertRaises(PermissionError): + remove_tree('fixture', timeout=0) diff --git a/src/SidePulse.Cli/CliApplication.cs b/src/SidePulse.Cli/CliApplication.cs index a76816e..2399bc1 100644 --- a/src/SidePulse.Cli/CliApplication.cs +++ b/src/SidePulse.Cli/CliApplication.cs @@ -24,6 +24,8 @@ static string[] Normalize(string[] command) return command; } args = Normalize(args); + try { MaintenanceArguments.Validate(args); } + catch (Exception ex) { return TerminalMode.Error(ex); } using var logOutput = HostLogs.Redirect(args); var app = new CommandApp(); app.Configure(config => @@ -80,6 +82,13 @@ static string[] Normalize(string[] command) links.AddCommand("remove").WithDescription("Remove a local phone link."); }); config.AddCommand("doctor").WithDescription("Check local setup without sending to devices or the network."); + config.AddCommand("storage").WithDescription("Show or save Dot USB storage on/off settings."); + config.AddBranch("firmware", firmware => + { + firmware.SetDescription("Inspect and update device firmware using verified official OTA packages."); + firmware.AddCommand("version"); + firmware.AddCommand("upgrade"); + }); config.AddCommand("devices").WithDescription("List mounted SidePulse devices."); config.AddCommand("state").WithDescription("Display an agent state on USB or iPhone."); config.AddCommand("write").WithDescription("Send a raw LED program with firmware envelope checks."); @@ -110,7 +119,7 @@ static string[] Normalize(string[] command) return TerminalMode.Error(exception); }); }); - try { return session ? new ShellSession((command, token) => app.Run(Normalize(command), token)).Run(args) : app.Run(args); } + try { return session ? new ShellSession((command, token) => { var normalized = Normalize(command); MaintenanceArguments.Validate(normalized); return app.Run(normalized, token); }).Run(args) : app.Run(args); } catch (Exception ex) { return TerminalMode.Error(ex); } } } diff --git a/src/SidePulse.Cli/FirmwareCommands.cs b/src/SidePulse.Cli/FirmwareCommands.cs new file mode 100644 index 0000000..b095016 --- /dev/null +++ b/src/SidePulse.Cli/FirmwareCommands.cs @@ -0,0 +1,88 @@ +using System.ComponentModel; +using SidePulse.Core; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace SidePulse.Cli; + +public class FirmwareVersionSettings : CommandSettings +{ + [CommandOption("--device ")] [Description("Mounted SidePulse drive or LEDS.LED path.")] + public string? Device { get; init; } + [CommandOption("--json")] public bool Json { get; init; } +} +public sealed class FirmwareVersionCommand : Command +{ + public override int Execute(CommandContext context, FirmwareVersionSettings settings, CancellationToken cancellationToken) + { + var devices = Firmware.Discover(settings.Device); + if (settings.Json) Output.Print(devices); + else foreach (var device in devices) Console.WriteLine($"SidePulse {device.Product}: {device.Version} ({device.Serial}, {device.Root})"); + return 0; + } +} +public sealed class FirmwareUpgradeSettings : FirmwareVersionSettings +{ + [CommandOption("--all")] public bool All { get; init; } + [CommandOption("--file ")] public string? File { get; init; } + [CommandOption("--release-version ")] [Description("Firmware release; distinct from the SPN --version option.")] + public string? ReleaseVersion { get; init; } + [CommandOption("--dry-run")] public bool DryRun { get; init; } + [CommandOption("--read-only")] [Description("Use the uncached Windows READ2ME channel for Pro.")] + public bool ReadOnly { get; init; } + public override ValidationResult Validate() => Device is not null && All ? ValidationResult.Error("Choose --device or --all.") + : File is not null && ReleaseVersion is not null ? ValidationResult.Error("Choose --file or --release-version.") : ValidationResult.Success(); +} +public sealed class FirmwareUpgradeCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, FirmwareUpgradeSettings settings, CancellationToken cancellationToken) + { + var devices = Firmware.Discover(settings.Device); + if (devices.Count > 1 && !settings.All) throw new ArgumentException("Multiple devices found. Select --device or explicitly use --all."); + if (!settings.DryRun && (await HostControl.Request("status", cancellationToken, waitForConnection: false)).Running) + throw new IOException("Stop the SPN host before updating firmware: spn host stop."); + using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; + // Verify every selected package/model before starting the first transfer. + var plans = new List<(FirmwareDevice Device, FirmwarePackage Package)>(); + var packages = new Dictionary(StringComparer.Ordinal); + foreach (var device in devices) + { + if (!packages.TryGetValue(device.Product, out var package)) + { + package = await Firmware.LoadPackage(client, device.Product, settings.ReleaseVersion, settings.File, cancellationToken); + packages.Add(device.Product, package); + } + await Firmware.Upgrade(device, package, true, settings.ReadOnly, cancellationToken); + plans.Add((device, package)); + } + var results = new List(); + foreach (var (device, package) in plans) results.Add(await Firmware.Upgrade(device, package, settings.DryRun, settings.ReadOnly, cancellationToken)); + if (settings.Json) Output.Print(results); + else foreach (var result in results) Console.WriteLine(result.DryRun ? $"Verified firmware {result.Version} for {result.Serial}; no device writes." + : result.State == "already-installed" ? $"{result.Serial} is already on {result.Version}." + : $"Firmware {result.Version} transferred to {result.Serial}. Keep connected for at least 10 seconds, then reconnect and run spn firmware version to confirm installation."); + return 0; + } +} +public sealed class StorageSettings : CommandSettings +{ + [CommandArgument(0, "")] public string Action { get; init; } = "status"; + [CommandOption("--device ")] [Description("SPD serial or usb:BUS:ADDRESS. Required when changing one of multiple Dots.")] + public string? Device { get; init; } + [CommandOption("--reconnect")] [Description("Apply immediately only when storage is currently off. Active storage must be safely ejected manually.")] + public bool Reconnect { get; init; } + [CommandOption("--json")] public bool Json { get; init; } + public override ValidationResult Validate() => Action is not "status" and not "on" and not "off" ? ValidationResult.Error("Use storage status, on or off.") + : Reconnect && Action == "status" ? ValidationResult.Error("--reconnect requires on or off.") : ValidationResult.Success(); +} +public sealed class StorageCommand : AsyncCommand +{ + public override async Task ExecuteAsync(CommandContext context, StorageSettings settings, CancellationToken cancellationToken) + { + var results = await UsbStorage.Execute(settings.Action, settings.Device, settings.Reconnect, cancellationToken); + if (settings.Json) Output.Print(results); + else foreach (var result in results) Console.WriteLine($"{result.Serial}: storage {(result.Active ? "on" : "off")} (saved: {(result.Saved ? "on" : "off")}, {result.State})." + + (result.Active != result.Saved ? " Safely eject any mounted Dot drive, then unplug and reconnect to apply." : "")); + return 0; + } +} diff --git a/src/SidePulse.Cli/JsonContracts.cs b/src/SidePulse.Cli/JsonContracts.cs index 9fea715..2fcaf23 100644 --- a/src/SidePulse.Cli/JsonContracts.cs +++ b/src/SidePulse.Cli/JsonContracts.cs @@ -47,6 +47,9 @@ public static JsonTypeInfo Info(JsonSerializerOptions? options = null) } [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata, UseStringEnumConverter = true)] +[JsonSerializable(typeof(IReadOnlyList))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(IReadOnlyList))] [JsonSerializable(typeof(ErrorReply))] [JsonSerializable(typeof(StateReply))] [JsonSerializable(typeof(ScheduledUninstallReply))] diff --git a/src/SidePulse.Cli/MaintenanceArguments.cs b/src/SidePulse.Cli/MaintenanceArguments.cs new file mode 100644 index 0000000..0b20acc --- /dev/null +++ b/src/SidePulse.Cli/MaintenanceArguments.cs @@ -0,0 +1,27 @@ +namespace SidePulse.Cli; + +/// Fail closed on misspelled maintenance options before any hardware access. +public static class MaintenanceArguments +{ + public static void Validate(string[] args) + { + if (args.Length == 0 || args[0] is not "firmware" and not "storage") return; + if (args.Skip(1).Any(a => a is "--help" or "-h" or "-?")) return; + if (args.Length < 2 || (args[0] == "firmware" ? args[1] is not "version" and not "upgrade" : args[1] is not "status" and not "on" and not "off")) + throw new ArgumentException("Use firmware version/upgrade or storage status/on/off."); + var values = args[0] == "firmware" && args[1] == "upgrade" ? new[] { "--device", "--file", "--release-version" } : new[] { "--device" }; + var flags = args[0] == "storage" ? new[] { "--json", "--reconnect" } : args[1] == "upgrade" ? new[] { "--json", "--all", "--dry-run", "--read-only" } : new[] { "--json" }; + var seen = new HashSet(StringComparer.Ordinal); + for (var i = 2; i < args.Length; i++) + { + var option = args[i].Split('=', 2); + if (!seen.Add(option[0])) throw new ArgumentException("Repeated maintenance option: " + option[0]); + if (values.Contains(option[0])) + { + if (option.Length == 2 && option[1].Length > 0) continue; + if (option.Length == 2 || ++i >= args.Length || args[i].StartsWith('-')) throw new ArgumentException("Missing value for " + option[0]); + } + else if (!flags.Contains(option[0]) || option.Length != 1) throw new ArgumentException("Unknown maintenance option: " + args[i]); + } + } +} diff --git a/src/SidePulse.Core/DeviceTransport.cs b/src/SidePulse.Core/DeviceTransport.cs index 407f4b4..6c334f7 100644 --- a/src/SidePulse.Core/DeviceTransport.cs +++ b/src/SidePulse.Core/DeviceTransport.cs @@ -50,6 +50,7 @@ public static string Resolve(string? path) public static void Write(string path, LedProgram program) { + using var lease = DeviceWriteLease.Acquire(System.IO.Path.GetDirectoryName(Resolve(path))!); // Write to the existing virtual file. Atomic rename is unsuitable for the device filesystem. using var stream = new FileStream(Resolve(path), FileMode.Open, FileAccess.Write, FileShare.Read, 4096, FileOptions.WriteThrough); diff --git a/src/SidePulse.Core/DeviceWriteLease.cs b/src/SidePulse.Core/DeviceWriteLease.cs new file mode 100644 index 0000000..0713a39 --- /dev/null +++ b/src/SidePulse.Core/DeviceWriteLease.cs @@ -0,0 +1,18 @@ +using System.Security.Cryptography; +using System.Text; + +namespace SidePulse.Core; + +internal static class DeviceWriteLease +{ + public static FileStream Acquire(string root) + { + var key = root.StartsWith("usb:", StringComparison.Ordinal) ? root : Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); + if (OperatingSystem.IsWindows()) key = key.ToUpperInvariant(); + var directory = Path.Combine(Path.GetDirectoryName(LinkStore.DefaultPath)!, "device-locks"); + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key))) + ".lock"); + try { return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } + catch (IOException) { throw new IOException("The device is busy with another SPN write or firmware update."); } + } +} diff --git a/src/SidePulse.Core/Firmware.cs b/src/SidePulse.Core/Firmware.cs new file mode 100644 index 0000000..bdd7acb --- /dev/null +++ b/src/SidePulse.Core/Firmware.cs @@ -0,0 +1,254 @@ +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace SidePulse.Core; + +public sealed record FirmwareDevice(string Root, string Product, string Version, string Serial); +public sealed record FirmwarePackage(string Product, string Version, byte[] Payload); +public sealed record FirmwareTransfer(string Device, string Serial, string Version, string State, bool DryRun); + +/// Official customer OTA ZIP verification and mounted-device firmware transfer. +public static class Firmware +{ + public const int MaximumBytes = 4 * 1024 * 1024; + private static readonly string[] Files = ["FIRMWARE.BIN", "README.txt", "RELEASE_NOTES.txt", "SHA256SUMS.txt"]; + private const string DownloadRoot = "https://raw.githubusercontent.com/inteliwear/sidepulse/main/firmware"; + + public static string NormalizeVersion(string value) + { + var match = Regex.Match(value, @"^v?(\d+)\.(\d+)(?:\.(\d+))?\z", RegexOptions.CultureInvariant); + if (!match.Success || !int.TryParse(match.Groups[1].Value, out var major) || !int.TryParse(match.Groups[2].Value, out var minor) + || !int.TryParse(match.Groups[3].Success ? match.Groups[3].Value : "0", out var patch)) + throw new ArgumentException("Invalid firmware version. Use a version such as 1.1.17."); + return $"{major}.{minor}.{patch}"; + } + + public static FirmwareDevice ReadDevice(string path) + { + if (path.StartsWith("usb:", StringComparison.Ordinal) || path.StartsWith("SPD-", StringComparison.Ordinal)) + { + using var usb = new DotUsb(); + var matches = usb.Discover().Where(d => d.Serial == path || $"usb:{d.Bus}:{d.Address}" == path).ToArray(); + if (matches.Length != 1) throw new IOException("Select one connected Dot with an unambiguous USB identity."); + var dotDevice = matches[0]; + return new($"usb:{dotDevice.Bus}:{dotDevice.Address}", "dot", dotDevice.Version, dotDevice.Serial); + } + var root = Path.GetFullPath(path); + if (Path.GetFileName(root).Equals("LEDS.LED", StringComparison.OrdinalIgnoreCase)) root = Path.GetDirectoryName(root)!; + var status = Path.Combine(root, "STATUS.TXT"); + RejectLink(root); RejectLink(status); + using var stream = File.OpenRead(status); + if (stream.Length > 65536) throw new IOException("Device status exceeds the size limit."); + using var reader = new StreamReader(stream); + var fields = reader.ReadToEnd().Replace("\0", "").Split('\n').Select(l => l.Trim().Split((char[]?)null, 2, StringSplitOptions.RemoveEmptyEntries)) + .Where(p => p.Length == 2).ToDictionary(p => p[0], p => p[1], StringComparer.Ordinal); + var dot = fields.ContainsKey("app_version") || fields.ContainsKey("app_build") && fields.ContainsKey("fw_state"); + var pro = fields.ContainsKey("release_version") || fields.ContainsKey("firmware_version") && fields.ContainsKey("firmware_slot"); + if (dot == pro) throw new IOException("STATUS.TXT does not identify a SidePulse Dot or Pro."); + return new(root, dot ? "dot" : "pro", fields.GetValueOrDefault(dot ? "app_version" : "release_version", "unknown"), fields.GetValueOrDefault("serial", "unassigned")); + } + + public static IReadOnlyList Discover(string? path = null) + { + if (path is not null) return [ReadDevice(path)]; + var result = new List(); + foreach (var device in DeviceTransport.Discover()) + { + try { result.Add(ReadDevice(device.Path)); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + try + { + using var usb = new DotUsb(); + foreach (var dot in usb.Discover()) + if (!result.Any(d => d.Serial == dot.Serial && dot.Serial != "unassigned")) + result.Add(new($"usb:{dot.Bus}:{dot.Address}", "dot", dot.Version, dot.Serial)); + } + catch (DllNotFoundException) { } + catch (PlatformNotSupportedException) { } + catch (IOException) when (result.Count > 0) { } + if (result.Count == 0) throw new IOException("No mounted SidePulse found. Select its drive with --device."); + return result; + } + + public static Dictionary ParseChecksums(byte[] data) + { + var result = new Dictionary(StringComparer.Ordinal); + foreach (var line in new UTF8Encoding(false, true).GetString(data).Split('\n')) + { + var text = line.TrimEnd('\r'); + if (string.IsNullOrWhiteSpace(text)) continue; + var m = Regex.Match(text, @"^([0-9a-fA-F]{64}) ([A-Za-z0-9_.-]+)\z", RegexOptions.CultureInvariant); + if (!m.Success || !result.TryAdd(m.Groups[2].Value, m.Groups[1].Value)) throw new InvalidDataException("Invalid or duplicate firmware checksum."); + } + return result; + } + + public static FirmwarePackage ReadPackage(byte[] data, string filename) + { + var m = Regex.Match(filename, @"^sidepulse-(dot|pro)-(\d+\.\d+\.\d+)-ota\.zip\z", RegexOptions.CultureInvariant); + if (!m.Success) throw new InvalidDataException("Use a customer OTA ZIP named sidepulse-dot-VERSION-ota.zip or sidepulse-pro-VERSION-ota.zip."); + if (data.Length > MaximumBytes) throw new InvalidDataException("Firmware package exceeds the size limit."); + using var zip = new ZipArchive(new MemoryStream(data), ZipArchiveMode.Read); + var prefix = zip.Entries.Any(e => e.FullName == "FIRMWARE.BIN") ? "" : filename[..^4] + "/"; + if (zip.Entries.Count != Files.Length || !zip.Entries.Select(e => e.FullName).Order().SequenceEqual(Files.Select(f => prefix + f).Order()) + || zip.Entries.Sum(e => e.Length) > MaximumBytes) throw new InvalidDataException("Unexpected or oversized files in firmware package."); + var contents = new Dictionary(); + foreach (var name in Files) + { + using var entry = zip.GetEntry(prefix + name)!.Open(); + using var output = new MemoryStream(); entry.CopyTo(output); contents.Add(name, output.ToArray()); + } + var checksums = ParseChecksums(contents["SHA256SUMS.txt"]); + if (!checksums.Keys.Order().SequenceEqual(Files.Where(f => f != "SHA256SUMS.txt").Order())) throw new InvalidDataException("Firmware package checksums are incomplete."); + foreach (var (name, digest) in checksums) Verify(contents[name], digest); + var title = $"SidePulse {(m.Groups[1].Value == "dot" ? "Dot" : "Pro")} firmware update - version {m.Groups[2].Value}"; + if (Encoding.UTF8.GetString(contents["README.txt"]).Split('\n')[0].TrimEnd('\r') != title || contents["FIRMWARE.BIN"].Length == 0) + throw new InvalidDataException("Firmware image is empty or package model/version does not match its filename."); + return new(m.Groups[1].Value, NormalizeVersion(m.Groups[2].Value), contents["FIRMWARE.BIN"]); + } + + private static void Verify(byte[] data, string digest) + { + if (!Convert.ToHexString(SHA256.HashData(data)).Equals(digest, StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("Firmware checksum mismatch."); + } + + public static async Task LoadPackage(HttpClient client, string product, string? version, string? file, CancellationToken token = default) + { + if (product is not "dot" and not "pro") throw new ArgumentException("Unknown firmware product."); + if (file is not null) + { + using var stream = File.OpenRead(file); + if (stream.Length > MaximumBytes) throw new InvalidDataException("Firmware package exceeds the size limit."); + using var output = new MemoryStream(); await stream.CopyToAsync(output, token); + return ReadPackage(output.ToArray(), Path.GetFileName(file)); + } + string[] versions; + if (version is not null) versions = [NormalizeVersion(version)]; + else + { + var listing = await Download(client, "https://api.github.com/repos/inteliwear/sidepulse/contents/firmware?ref=main", 1024 * 1024, token); + using var document = JsonDocument.Parse(listing); + versions = document.RootElement.EnumerateArray().Where(e => e.GetProperty("type").GetString() == "dir") + .Select(e => e.GetProperty("name").GetString()!).Where(n => Regex.IsMatch(n, @"^v\d+\.\d+\.\d+\z")) + .Select(NormalizeVersion).Distinct().OrderByDescending(Version.Parse).ToArray(); + } + foreach (var release in versions) + { + var name = $"sidepulse-{product}-{release}-ota.zip"; + var checksums = ParseChecksums(await Download(client, $"{DownloadRoot}/v{release}/SHA256SUMS.txt", 65536, token)); + if (!checksums.TryGetValue(name, out var digest)) continue; + var bytes = await Download(client, $"{DownloadRoot}/v{release}/{name}", MaximumBytes, token); + Verify(bytes, digest); return ReadPackage(bytes, name); + } + throw new IOException("No published firmware package found for this model/version."); + } + + private static async Task Download(HttpClient client, string url, int maximum, CancellationToken token) + { + using var request = new HttpRequestMessage(HttpMethod.Get, url); + request.Headers.UserAgent.ParseAdd("SidePulse.NET"); + using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token); + response.EnsureSuccessStatusCode(); + using var stream = await response.Content.ReadAsStreamAsync(token); + using var output = new MemoryStream(); + var buffer = new byte[8192]; int count; + while ((count = await stream.ReadAsync(buffer, token)) > 0) + { + if (output.Length + count > maximum) throw new InvalidDataException("Firmware download exceeds the size limit."); + output.Write(buffer, 0, count); + } + return output.ToArray(); + } + + public static async Task Upgrade(FirmwareDevice device, FirmwarePackage package, bool dryRun, bool readOnly = false, CancellationToken token = default) + { + if (device.Product != package.Product) throw new InvalidDataException("Firmware model does not match the selected device."); + var target = Version.Parse(NormalizeVersion(package.Version)); + var current = Version.Parse(NormalizeVersion(device.Version)); + if (target < current) throw new InvalidDataException("Firmware downgrade refused."); + if (ReadDevice(device.Root) != device) throw new IOException("The selected device changed. Check its version again."); + if (target == current) return new(device.Root, device.Serial, package.Version, "already-installed", dryRun); + if (package.Payload.Length is 0 or > MaximumBytes) throw new InvalidDataException("Invalid firmware image size."); + if (readOnly && device.Product != "pro") throw new InvalidDataException("Read-only firmware transfer is supported only by Pro."); + if (dryRun) return new(device.Root, device.Serial, package.Version, "verified", true); + token.ThrowIfCancellationRequested(); + using var lease = DeviceWriteLease.Acquire(device.Root); + if (ReadDevice(device.Root) != device) throw new IOException("The selected device changed before the transfer."); + if (device.Root.StartsWith("usb:", StringComparison.Ordinal)) + { + var mounted = await PrepareDotDrive(device, token); + return await Upgrade(mounted, package, false, false, token); + } + if (readOnly) + { + using var channel = new WindowsRead2Me(Path.Combine(device.Root, "setup.html")); + await Read2Me.Upload(channel.Read, package.Payload, token); + } + else + { + var path = Path.Combine(device.Root, "FIRMWARE.BIN"); RejectLink(path); + // No rename or directory fsync: the virtual FAT receiver consumes the existing destination. + // FileShare.None also excludes other SPN firmware transfers while this handle is open. + using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough); + try { stream.Write(package.Payload); stream.Flush(true); } + catch (IOException ex) { throw new IOException("Firmware transfer is uncertain. Keep connected for 10 seconds, reconnect and check the version before retrying.", ex); } + } + await Task.Delay(TimeSpan.FromSeconds(10), CancellationToken.None); + // A successful transfer does not prove that the device installed the image. + return new(device.Root, device.Serial, package.Version, "transferred-reconnect-to-confirm", false); + } + + private static async Task PrepareDotDrive(FirmwareDevice device, CancellationToken token) + { + if (device.Serial == "unassigned") throw new IOException("A production serial is required to identify the Dot after reconnecting. Select a mounted drive instead."); + using var usb = new DotUsb(); + var matches = usb.Discover().Where(d => d.Serial == device.Serial).ToArray(); + if (matches.Length != 1 || $"usb:{matches[0].Bus}:{matches[0].Address}" != device.Root || matches[0].Version != device.Version) + throw new IOException("The selected Dot changed before preparing storage."); + var status = usb.Status(matches[0]); + if (status.State != "READY") throw new IOException("Dot storage is busy or failed. Check spn storage status."); + if (!status.Active) + { + try { await UsbStorage.Execute("on", device.Serial, true, token); } + finally + { + // Restore the saved preference before sending any image bytes, including + // when the enable/reconnect acknowledgement was lost. Keep the drive active. + if (!status.Saved) await UsbStorage.Execute("off", device.Serial, false, CancellationToken.None); + } + } + var watch = System.Diagnostics.Stopwatch.StartNew(); + do + { + var drives = new List(); + foreach (var mounted in DeviceTransport.Discover()) + { + try + { + var candidate = ReadDevice(mounted.Path); + if (candidate.Serial == device.Serial && candidate.Product == "dot") drives.Add(candidate); + } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + } + if (drives.Count > 0) + { + if (drives.Count != 1 || drives[0].Version != device.Version) throw new IOException("Cannot uniquely identify the original Dot drive."); + return drives[0]; + } + await Task.Delay(250, token); + } while (watch.Elapsed < TimeSpan.FromSeconds(10)); + throw new IOException("No mounted drive appeared. Check host storage access; reconnect to apply the saved storage preference."); + } + + internal static void RejectLink(string path) + { + if ((File.Exists(path) || Directory.Exists(path)) && (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) + throw new IOException("Device paths must not be symbolic links or reparse points."); + } +} diff --git a/src/SidePulse.Core/Read2Me.cs b/src/SidePulse.Core/Read2Me.cs new file mode 100644 index 0000000..2ba803d --- /dev/null +++ b/src/SidePulse.Core/Read2Me.cs @@ -0,0 +1,140 @@ +using System.Buffers.Binary; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using Microsoft.Win32.SafeHandles; + +namespace SidePulse.Core; + +public sealed record Read2MeStatus(byte State, byte Error, byte Target, uint TransferId, uint Total, uint Received, uint Symbols, uint Capacity, ushort PayloadCrc, uint ReadRequests); + +/// READ2ME v1 framing from the public SidePulse protocol. Never retries a firmware transfer. +public static class Read2Me +{ + private static readonly int[] Start = [16, 16, 1, 2, 3, 4]; + private static readonly int[] Stop = [17, 17, 4, 3, 2, 1]; + public static ushort Crc(ReadOnlySpan bytes) + { + ushort crc = 0xffff; + foreach (var value in bytes) + { + crc ^= (ushort)(value << 8); + for (var i = 0; i < 8; i++) crc = (ushort)((crc & 0x8000) != 0 ? (crc << 1) ^ 0x1021 : crc << 1); + } + return crc; + } + + public static int[] Frame(uint id, int total, int offset, ReadOnlySpan bytes) + { + if (id == 0 || total <= 0 || offset < 0 || bytes.Length is < 1 or > 512 || (long)offset + bytes.Length > total) + throw new ArgumentException("Invalid READ2ME chunk."); + var packet = new byte[30 + bytes.Length]; + packet[0] = 1; BinaryPrimitives.WriteUInt32BigEndian(packet.AsSpan(1), id); packet[5] = 12; + "FIRMWARE.BIN"u8.CopyTo(packet.AsSpan(6)); + // FIRMWARE.BIN is 12 ASCII bytes. + BinaryPrimitives.WriteUInt32BigEndian(packet.AsSpan(18), (uint)total); + BinaryPrimitives.WriteUInt32BigEndian(packet.AsSpan(22), (uint)offset); + BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(26), (ushort)bytes.Length); + bytes.CopyTo(packet.AsSpan(28)); + // Header = 28 bytes; CRC follows the payload. + BinaryPrimitives.WriteUInt16BigEndian(packet.AsSpan(28 + bytes.Length), Crc(packet.AsSpan(0, 28 + bytes.Length))); + return Start.Concat(packet.SelectMany(b => new[] { b >> 4, b & 15 })).Concat(Stop).ToArray(); + } + + public static Read2MeStatus Decode(byte[] sector) + { + if (sector.Length != 512 || !sector.AsSpan(256, 13).SequenceEqual("\n"u8)) + throw new InvalidDataException("Invalid READ2ME status envelope."); + var encoded = System.Text.Encoding.ASCII.GetString(sector, 269, 128); + if (encoded.Any(c => !"0123456789abcdef".Contains(c))) throw new InvalidDataException("Invalid READ2ME status hex."); + var data = Convert.FromHexString(encoded); + uint U(int at) => BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(at)); + if (!data.AsSpan(0, 8).SequenceEqual("READ2ME1"u8) || data[8] != 1 || data[9] > 4 || data[10] > 8 || data[11] > 2 + || Crc(data.AsSpan(0, 62)) != BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(62))) + throw new InvalidDataException("Invalid or torn READ2ME status; firmware may be too old."); + return new(data[9], data[10], data[11], U(12), U(16), U(20), U(32), U(40), BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(44)), U(50)); + } + + public static async Task Upload(Func read, byte[] payload, CancellationToken token = default) + { + var before = Decode(read(18)); + if (payload.Length == 0 || payload.Length > before.Capacity || before.State is 1 or 2) throw new IOException("READ2ME receiver is busy or image exceeds capacity."); + // Verify exact address-symbol delivery before beginning an upload. + foreach (var symbol in Start.Append(16)) read(symbol); + var probe = Decode(read(18)); + if (unchecked(probe.Symbols - before.Symbols) != 7 || probe.ReadRequests == before.ReadRequests) + throw new IOException("Control reads were cached or aggregated. No firmware upload was started."); + uint id; + do { id = BinaryPrimitives.ReadUInt32BigEndian(RandomNumberGenerator.GetBytes(4)); } while (id == 0 || id == before.TransferId); + var final = false; + try + { + Read2MeStatus status = probe; + for (var offset = 0; offset < payload.Length; offset += 512) + { + token.ThrowIfCancellationRequested(); + var length = Math.Min(512, payload.Length - offset); + final |= offset + length == payload.Length; + foreach (var symbol in Frame(id, payload.Length, offset, payload.AsSpan(offset, length))) read(symbol); + var deadline = Stopwatch.StartNew(); + do + { + status = Decode(read(18)); + if (status.TransferId == id && status.Total == payload.Length && status.Target == 2 && status.Received == offset + length && status.Error == 0) break; + if (status.Error != 0 && status.TransferId == id) throw new IOException("READ2ME receiver rejected the firmware chunk."); + await Task.Delay(10, token); + } while (deadline.Elapsed < TimeSpan.FromSeconds(2)); + if (status.TransferId != id || status.Total != payload.Length || status.Target != 2 || status.Received != offset + length) + throw new IOException("Firmware acknowledgement lost. Do not replay; reconnect and check the installed version."); + } + var completion = Stopwatch.StartNew(); + while (status.State == 2 && completion.Elapsed < TimeSpan.FromSeconds(30)) + { await Task.Delay(20, token); status = Decode(read(18)); } + if (status.TransferId != id || status.Total != payload.Length || status.Target != 2 || status.Received != payload.Length || status.State != 3 || status.Error != 0 || status.PayloadCrc != Crc(payload)) + throw new IOException("Firmware completion could not be verified. Reconnect and check its version before retrying."); + } + finally + { + // The final frame can reboot the board even when its acknowledgement is lost. + if (final) await Task.Delay(TimeSpan.FromSeconds(5), CancellationToken.None); + } + } +} + +/// Aligned, uncached Windows sector reads; no writes and no volume driver replacement. +internal sealed class WindowsRead2Me : IDisposable +{ + private readonly SafeFileHandle handle; + private readonly IntPtr allocation; + private readonly IntPtr aligned; + public WindowsRead2Me(string path) + { + if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("The read-only firmware channel currently requires Windows. Use a writable mounted drive on other platforms."); + Firmware.RejectLink(path); + if (new FileInfo(path).Length != 19 * 512) throw new IOException("setup.html must be exactly 19 sectors."); + if (!GetDiskFreeSpace(Path.GetPathRoot(Path.GetFullPath(path))!, out _, out var sector, out _, out _) || sector != 512) + throw new IOException("READ2ME requires a volume with 512-byte sectors; address aggregation would corrupt the transfer."); + handle = CreateFile(path, 0x80000000, 1 | 2, IntPtr.Zero, 3, 0x20000000 | 0x10000000, IntPtr.Zero); + if (handle.IsInvalid) { handle.Dispose(); throw new Win32Exception(Marshal.GetLastWin32Error()); } + allocation = Marshal.AllocHGlobal(8192); + aligned = new IntPtr((allocation.ToInt64() + 4095) & ~4095L); + } + public byte[] Read(int symbol) + { + if (symbol is < 0 or > 18) throw new ArgumentOutOfRangeException(nameof(symbol)); + if (!SetFilePointerEx(handle, symbol * 512L, out _, 0) || !ReadFile(handle, aligned, 512, out var count, IntPtr.Zero)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + if (count != 512) throw new IOException("Short READ2ME sector read."); + var result = new byte[512]; Marshal.Copy(aligned, result, 0, 512); return result; + } + public void Dispose() { handle.Dispose(); Marshal.FreeHGlobal(allocation); } + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CreateFileW")] + private static extern SafeFileHandle CreateFile(string path, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template); + [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool ReadFile(SafeFileHandle handle, IntPtr buffer, uint count, out uint read, IntPtr overlapped); + [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetFilePointerEx(SafeFileHandle handle, long offset, out long position, uint method); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "GetDiskFreeSpaceW")] [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetDiskFreeSpace(string root, out uint cluster, out uint sector, out uint free, out uint total); +} diff --git a/src/SidePulse.Core/UsbStorage.cs b/src/SidePulse.Core/UsbStorage.cs new file mode 100644 index 0000000..47c92f3 --- /dev/null +++ b/src/SidePulse.Core/UsbStorage.cs @@ -0,0 +1,199 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; + +namespace SidePulse.Core; + +public sealed record DotUsbDevice(byte Bus, byte Address, string Serial, string Version); +public sealed record StorageStatus(bool Saved, bool Active, string State); +public sealed record StorageReply(string Serial, string Device, bool Saved, bool Active, string State); + +/// Dot SPS1 storage protocol. OUT commands are never replayed after an uncertain result. +public static class UsbStorage +{ + public static StorageStatus Decode(byte[] bytes) + { + if (bytes.Length != 8 || !bytes.AsSpan(0, 4).SequenceEqual("SPS1"u8) || bytes[4] > 1 || bytes[5] > 1 || bytes[6] > 2 || bytes[7] != 0) + throw new InvalidDataException("Invalid SPS1 status. The Dot may need newer firmware; Pro does not support storage control."); + return new(bytes[4] != 0, bytes[5] != 0, new[] { "READY", "BUSY", "FAILED" }[bytes[6]]); + } + + public static DotUsbDevice DecodeInfo(byte bus, byte address, byte[] data) + { + if (data.Length != 48 || !data.AsSpan(0, 4).SequenceEqual("SPI1"u8) || data[4] != 1 || data[5] is < 1 or > 3 || data[6] is not 2 and not 4 + || (data[7] & ~7) != 0 || data[43] != 0 || data.AsSpan(44).ContainsAnyExcept((byte)0)) throw new InvalidDataException("Invalid Dot USB identity."); + var end = Array.IndexOf(data, (byte)0, 12, 32); + if (end < 0 || data.AsSpan(12, end - 12).ToArray().Any(b => b is < 33 or > 126)) throw new InvalidDataException("Invalid Dot firmware version bytes."); + var version = Encoding.ASCII.GetString(data, 12, end - 12); + if (version.Length == 0 || version.Any(c => c is < '!' or > '~')) throw new InvalidDataException("Invalid Dot firmware version."); + var serial = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8)); + return new(bus, address, serial == 0 ? "unassigned" : $"SPD-{serial:D6}", version); + } + + public static async Task Save(Func read, Action write, bool enabled, CancellationToken token = default) + { + var before = read(); + if (before.State == "BUSY") throw new IOException("Dot is saving a setting. Try again when it finishes."); + if (before.Saved == enabled && before.State == "READY") return before; + token.ThrowIfCancellationRequested(); + write(enabled); // Never retry this OUT, even after a timeout or disconnect. + var watch = Stopwatch.StartNew(); + do + { + var status = read(); + if (status.State == "FAILED") throw new IOException("Dot could not save the storage preference."); + if (status.State == "READY" && status.Saved == enabled) return status; + await Task.Delay(20, token); + } while (watch.Elapsed < TimeSpan.FromSeconds(5)); + throw new IOException("Storage save acknowledgement lost. Check status before retrying."); + } + + public static async Task> Execute(string action, string? selector, bool reconnect, CancellationToken token = default) + { + if (action is not "status" and not "on" and not "off") throw new ArgumentException("Storage action must be status, on or off."); + using var usb = new DotUsb(); + var all = usb.Discover(); + var devices = selector is null ? all : all.Where(d => d.Serial == selector || $"usb:{d.Bus}:{d.Address}" == selector).ToArray(); + if (devices.Count == 0) throw new IOException("No compatible Dot found. Use its SPD serial or usb:BUS:ADDRESS; check USB access and firmware."); + if (action != "status" && devices.Count != 1) throw new IOException("Select one Dot using --device SERIAL or usb:BUS:ADDRESS."); + var results = new List(); + foreach (var device in devices) + { + token.ThrowIfCancellationRequested(); + var currentDevice = device; + var status = usb.Status(device); + if (action != "status") + { + var enabled = action == "on"; + // A saved setting may be changed without disconnecting any mounted filesystem. + // Reconnect is permitted only when storage is currently inactive; disabling an active + // volume requires host ejection first, which this version deliberately leaves manual. + if (reconnect && status.Active && status.Active != enabled) + throw new IOException("Storage is active. Omit --reconnect, safely eject the Dot in your OS, then unplug and reconnect to apply the saved setting."); + if (reconnect && status.Active != enabled && (device.Serial == "unassigned" || all.Count(d => d.Serial == device.Serial) != 1)) + throw new IOException("A unique assigned serial is required to verify reconnect."); + status = await Save(() => usb.Status(device), value => usb.Set(device, value), enabled, token); + if (reconnect && status.Active != enabled) + { + usb.Reconnect(device); + await Task.Delay(2100, token); + var watch = Stopwatch.StartNew(); + var verified = false; + do + { + var matches = usb.Discover().Where(d => d.Serial == device.Serial).ToArray(); + if (matches.Length == 1) + { + status = usb.Status(matches[0]); + if (status == new StorageStatus(enabled, enabled, "READY")) { currentDevice = matches[0]; verified = true; break; } + } + await Task.Delay(200, token); + } while (watch.Elapsed < TimeSpan.FromSeconds(8)); + if (!verified) throw new IOException("Setting saved; USB reconnect was not verified. Check status after reconnecting the Dot."); + } + } + results.Add(new(currentDevice.Serial, $"usb:{currentDevice.Bus}:{currentDevice.Address}", status.Saved, status.Active, status.State)); + } + return results; + } +} + +/// libusb endpoint-zero control requests; never claims, detaches or resets interfaces. +internal sealed class DotUsb : IDisposable +{ + private readonly IntPtr context; + private static readonly Lazy SharedContext = new(CreateContext); + static DotUsb() + { + NativeLibrary.SetDllImportResolver(typeof(DotUsb).Assembly, (name, assembly, path) => + { + if (name != "spn-libusb") return IntPtr.Zero; + var names = OperatingSystem.IsMacOS() ? new[] { "libusb-1.0.dylib", "/opt/homebrew/lib/libusb-1.0.dylib", "/usr/local/lib/libusb-1.0.dylib" } : new[] { "libusb-1.0.so.0", "libusb-1.0.so" }; + foreach (var candidate in names) if (NativeLibrary.TryLoad(candidate, assembly, path, out var handle)) return handle; + throw new DllNotFoundException("Dot USB control requires system libusb 1.0 on Linux/macOS."); + }); + } + public DotUsb() + { + // UsbDk opens detach the complete device from the Windows PnP/storage stack. + // Even a status probe must not capture a mounted disk. Never initialize that backend. + if (OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("Dot USB storage control currently supports Linux/macOS only. A safe Windows control backend is pending; mounted firmware upgrades remain available."); + context = SharedContext.Value; + } + private static IntPtr CreateContext() + { + Check(Init(out var context)); + return context; + } + public IReadOnlyList Discover() + { + var result = new List(); + var count = GetList(context, out var list); + Check(count.ToInt64()); + try + { + for (long i = 0; i < count.ToInt64(); i++) + { + var device = Marshal.ReadIntPtr(list, checked((int)i * IntPtr.Size)); + var descriptor = new byte[18]; Check(GetDescriptor(device, descriptor)); + if (BitConverter.ToUInt16(descriptor, 8) != 0x1a86 || BitConverter.ToUInt16(descriptor, 10) != 0xfe10) continue; + var bus = GetBus(device); var address = GetAddress(device); + Check(Open(device, out var handle)); + try { result.Add(UsbStorage.DecodeInfo(bus, address, Transfer(handle, 0xc0, 0x54, 0, 48))); } + finally { Close(handle); } + } + } + finally { FreeList(list, 1); } + return result; + } + private byte[] On(DotUsbDevice selected, byte type, byte request, ushort value, int size) + { + var count = GetList(context, out var list); Check(count.ToInt64()); + try + { + for (long i = 0; i < count.ToInt64(); i++) + { + var device = Marshal.ReadIntPtr(list, checked((int)i * IntPtr.Size)); + if (GetBus(device) != selected.Bus || GetAddress(device) != selected.Address) continue; + var descriptor = new byte[18]; Check(GetDescriptor(device, descriptor)); + if (BitConverter.ToUInt16(descriptor, 8) != 0x1a86 || BitConverter.ToUInt16(descriptor, 10) != 0xfe10) continue; + Check(Open(device, out var handle)); + try + { + if (UsbStorage.DecodeInfo(selected.Bus, selected.Address, Transfer(handle, 0xc0, 0x54, 0, 48)) != selected) + throw new IOException("The selected USB device changed."); + return Transfer(handle, type, request, value, size); + } + finally { Close(handle); } + } + } + finally { FreeList(list, 1); } + throw new IOException("Selected Dot disconnected."); + } + public StorageStatus Status(DotUsbDevice device) => UsbStorage.Decode(On(device, 0xc0, 0x53, 0, 8)); + public void Set(DotUsbDevice device, bool enabled) => On(device, 0x40, 0x52, (ushort)(enabled ? 1 : 0), 0); + public void Reconnect(DotUsbDevice device) => On(device, 0x40, 0x55, 0, 0); + private static byte[] Transfer(IntPtr handle, byte type, byte request, ushort value, int size) + { + var bytes = new byte[size]; var count = Control(handle, type, request, value, 0x5350, bytes, (ushort)size, 1000); Check(count); + if (count != size) throw new IOException("Short Dot USB transfer. Result may be uncertain; check status before retrying."); + return bytes; + } + private static void Check(long result) + { + if (result < 0) throw new IOException($"Dot USB request failed ({result}). Check permissions, libusb installation and firmware."); + } + // Keep one context for the process lifetime: repeated libusb_exit can hang on macOS. + // All device handles and enumeration lists are still released after each operation. + public void Dispose() { } + [DllImport("spn-libusb", EntryPoint = "libusb_init", CallingConvention = CallingConvention.Cdecl)] private static extern int Init(out IntPtr context); + [DllImport("spn-libusb", EntryPoint = "libusb_get_device_list", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr GetList(IntPtr context, out IntPtr list); + [DllImport("spn-libusb", EntryPoint = "libusb_free_device_list", CallingConvention = CallingConvention.Cdecl)] private static extern void FreeList(IntPtr list, int unref); + [DllImport("spn-libusb", EntryPoint = "libusb_get_device_descriptor", CallingConvention = CallingConvention.Cdecl)] private static extern int GetDescriptor(IntPtr device, [Out] byte[] descriptor); + [DllImport("spn-libusb", EntryPoint = "libusb_get_bus_number", CallingConvention = CallingConvention.Cdecl)] private static extern byte GetBus(IntPtr device); + [DllImport("spn-libusb", EntryPoint = "libusb_get_device_address", CallingConvention = CallingConvention.Cdecl)] private static extern byte GetAddress(IntPtr device); + [DllImport("spn-libusb", EntryPoint = "libusb_open", CallingConvention = CallingConvention.Cdecl)] private static extern int Open(IntPtr device, out IntPtr handle); + [DllImport("spn-libusb", EntryPoint = "libusb_close", CallingConvention = CallingConvention.Cdecl)] private static extern void Close(IntPtr handle); + [DllImport("spn-libusb", EntryPoint = "libusb_control_transfer", CallingConvention = CallingConvention.Cdecl)] private static extern int Control(IntPtr handle, byte type, byte request, ushort value, ushort index, [In, Out] byte[] data, ushort length, uint timeout); +} diff --git a/tests/SidePulse.Tests/FirmwareTests.cs b/tests/SidePulse.Tests/FirmwareTests.cs new file mode 100644 index 0000000..c27d5e8 --- /dev/null +++ b/tests/SidePulse.Tests/FirmwareTests.cs @@ -0,0 +1,170 @@ +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; +using SidePulse.Core; +using Xunit; + +namespace SidePulse.Tests; + +public sealed class FirmwareTests +{ + private static byte[] Package(string product = "dot", bool corrupt = false, bool duplicate = false) + { + var files = new Dictionary + { + ["FIRMWARE.BIN"] = [1, 2, 3, 4], + ["README.txt"] = Encoding.UTF8.GetBytes($"SidePulse {(product == "dot" ? "Dot" : "Pro")} firmware update - version 1.1.17\n"), + ["RELEASE_NOTES.txt"] = "Test release\n"u8.ToArray() + }; + files["SHA256SUMS.txt"] = Encoding.UTF8.GetBytes(string.Join('\n', files.Select(f => $"{Convert.ToHexString(SHA256.HashData(f.Value)).ToLowerInvariant()} {f.Key}"))); + if (corrupt) files["FIRMWARE.BIN"][0] ^= 1; + using var output = new MemoryStream(); + using (var zip = new ZipArchive(output, ZipArchiveMode.Create, true)) + { + foreach (var (name, bytes) in files) { using var entry = zip.CreateEntry(name).Open(); entry.Write(bytes); } + if (duplicate) zip.CreateEntry("FIRMWARE.BIN"); + } + return output.ToArray(); + } + [Fact] + public void OtaPackageChecksEveryFileAndModel() + { + Assert.Equal(new byte[] { 1, 2, 3, 4 }, Firmware.ReadPackage(Package(), "sidepulse-dot-1.1.17-ota.zip").Payload); + Assert.Throws(() => Firmware.ReadPackage(Package(corrupt: true), "sidepulse-dot-1.1.17-ota.zip")); + Assert.Throws(() => Firmware.ReadPackage(Package(duplicate: true), "sidepulse-dot-1.1.17-ota.zip")); + Assert.Throws(() => Firmware.ReadPackage(Package(), "sidepulse-pro-1.1.17-ota.zip")); + Assert.Throws(() => Firmware.ReadPackage(Package(), "../sidepulse-dot-1.1.17-ota.zip")); + Assert.Throws(() => Firmware.ParseChecksums(Encoding.UTF8.GetBytes(new string('0', 64) + " test\n" + new string('0', 64) + " test"))); + } + [Fact] + public async Task TransferGuardsIdentityDowngradeAndDryRun() + { + var root = Path.Combine(Path.GetTempPath(), "SidePulse firmware ü " + Guid.NewGuid()); Directory.CreateDirectory(root); + try + { + var path = Path.Combine(root, "STATUS.TXT"); File.WriteAllText(path, "app_version 1.1.16\nserial SPD-000123\n"); + var device = Firmware.ReadDevice(root); + var package = Firmware.ReadPackage(Package(), "sidepulse-dot-1.1.17-ota.zip"); + Assert.Equal("verified", (await Firmware.Upgrade(device, package, true)).State); + Assert.False(File.Exists(Path.Combine(root, "FIRMWARE.BIN"))); + await Assert.ThrowsAsync(() => Firmware.Upgrade(device, package with { Product = "pro" }, false)); + await Assert.ThrowsAsync(() => Firmware.Upgrade(device, package with { Version = "1.1.15" }, false)); + using (var cancellation = new CancellationTokenSource()) + { + cancellation.Cancel(); await Assert.ThrowsAnyAsync(() => Firmware.Upgrade(device, package, false, token: cancellation.Token)); + } + Assert.False(File.Exists(Path.Combine(root, "FIRMWARE.BIN"))); + File.WriteAllText(Path.Combine(root, "LEDS.LED"), "off"); + var transfer = Firmware.Upgrade(device, package, false); + Assert.Throws(() => DeviceTransport.Write(root, new LedProgram("off"))); + Assert.Equal("transferred-reconnect-to-confirm", (await transfer).State); + DeviceTransport.Write(root, new LedProgram("off")); + Assert.Equal(package.Payload, File.ReadAllBytes(Path.Combine(root, "FIRMWARE.BIN"))); + File.WriteAllText(path, "app_version 1.1.16\nserial SPD-999999\n"); + await Assert.ThrowsAsync(() => Firmware.Upgrade(device, package, false)); + } + finally { Directory.Delete(root, true); } + } + [Theory] + [InlineData("v1.1", "1.1.0")] + [InlineData("1.1.17", "1.1.17")] + public void VersionNormalization(string text, string expected) => Assert.Equal(expected, Firmware.NormalizeVersion(text)); + [Theory] + [InlineData("../1.1.17")] + [InlineData("1.1.17-beta")] + [InlineData("1.1.17\n")] + public void InvalidVersionIsRejected(string text) => Assert.Throws(() => Firmware.NormalizeVersion(text)); + [Fact] + public async Task StorageSaveIsAcknowledgedAndNeverReplaysAnUncertainOut() + { + var ready = new StorageStatus(false, true, "READY"); var writes = 0; var reads = 0; + var result = await UsbStorage.Save(() => ++reads == 1 ? ready : new(true, true, "READY"), value => { Assert.True(value); writes++; }, true); + Assert.True(result.Saved); Assert.Equal(1, writes); + writes = 0; + await Assert.ThrowsAsync(() => UsbStorage.Save(() => ready, _ => { writes++; throw new IOException("lost acknowledgement"); }, true)); + Assert.Equal(1, writes); + await Assert.ThrowsAsync(() => UsbStorage.Save(() => ready with { State = "BUSY" }, _ => writes++, true)); + Assert.Equal(1, writes); + } + [Fact] + public void StorageStatusRejectsOldOrMalformedFirmware() + { + Assert.Equal(new StorageStatus(true, false, "READY"), UsbStorage.Decode([83, 80, 83, 49, 1, 0, 0, 0])); + Assert.Throws(() => UsbStorage.Decode([83, 80, 83, 49, 2, 0, 0, 0])); + Assert.Throws(() => UsbStorage.Decode([83, 80, 83, 49, 1, 0, 0, 1])); + Assert.Throws(() => UsbStorage.Decode(new byte[7])); + } + [Fact] + public void Read2MeFramingMatchesPublicWireFormat() + { + Assert.Equal((ushort)0x29b1, Read2Me.Crc("123456789"u8)); + var symbols = Read2Me.Frame(0x12345678, 3, 0, [1, 2, 3]); + Assert.Equal(new[] { 16, 16, 1, 2, 3, 4 }, symbols[..6]); + Assert.Equal(new[] { 17, 17, 4, 3, 2, 1 }, symbols[^6..]); + var bytes = symbols[6..^6].Chunk(2).Select(p => (byte)(p[0] * 16 + p[1])).ToArray(); + Assert.Equal("01123456780C4649524D574152452E42494E00000003000000000003010203", Convert.ToHexString(bytes[..^2])); + Assert.Equal(Read2Me.Crc(bytes.AsSpan(0, bytes.Length - 2)), System.Buffers.Binary.BinaryPrimitives.ReadUInt16BigEndian(bytes.AsSpan(bytes.Length - 2))); + Assert.Throws(() => Read2Me.Frame(0, 1, 0, [1])); + Assert.Throws(() => Read2Me.Decode(new byte[512])); + } + [Fact] + public async Task Read2MeCacheProbePreventsAnyFirmwareFrames() + { + var data = new byte[64]; "READ2ME1"u8.CopyTo(data); data[8] = 1; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(40), 1024); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(62), Read2Me.Crc(data.AsSpan(0, 62))); + var sector = new byte[512]; "\n"u8.CopyTo(sector.AsSpan(397)); + var reads = new List(); + await Assert.ThrowsAsync(() => Read2Me.Upload(symbol => { reads.Add(symbol); return sector; }, [1, 2, 3])); + Assert.Equal(new[] { 18, 16, 16, 1, 2, 3, 4, 16, 18 }, reads); + } + [Theory] + [InlineData("--dryrun")] + [InlineData("--dry-run=false")] + [InlineData("--file")] + [InlineData("--device=")] + public void MaintenanceTyposFailBeforeHardwareAccess(string option) + { + Assert.Throws(() => SidePulse.Cli.MaintenanceArguments.Validate(["firmware", "upgrade", option])); + } + [Fact] + public void MaintenanceArgumentsAcceptExplicitPathsAndRejectDuplicates() + { + SidePulse.Cli.MaintenanceArguments.Validate(["firmware", "upgrade", "--device", "C:\\SidePulse ü", "--file=sidepulse-dot-1.1.17-ota.zip", "--dry-run", "--json"]); + Assert.Throws(() => SidePulse.Cli.MaintenanceArguments.Validate(["storage", "off", "--device=a", "--device=b"])); + } + [Fact] + public async Task Read2MeValidatesCompleteFirmwareAcknowledgement() + { + var symbols = new List(); var statusReads = 0; + byte[] Read(int symbol) + { + if (symbol != 18) { symbols.Add(symbol); return new byte[512]; } + var data = new byte[64]; "READ2ME1"u8.CopyTo(data); data[8] = 1; + void U(int offset, uint value) => System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(offset), value); + U(40, 1024); + if (++statusReads > 1) { U(32, 7); U(50, 1); } + if (statusReads > 2) + { + var packet = symbols.Skip(7 + 6).Take(66).Chunk(2).Select(p => (byte)((p[0] << 4) | p[1])).ToArray(); + data[9] = 3; data[11] = 2; + packet.AsSpan(1, 4).CopyTo(data.AsSpan(12)); U(16, 3); U(20, 3); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(44), 0xadad); + } + System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(62), Read2Me.Crc(data.AsSpan(0, 62))); + var sector = new byte[512]; "\n"u8.CopyTo(sector.AsSpan(397)); + return sector; + } + await Read2Me.Upload(Read, [1, 2, 3]); + Assert.Equal(3, statusReads); + Assert.Equal(7 + 6 + 66 + 6, symbols.Count); + } + [Fact] + public async Task WindowsStorageStatusCannotInitializeACapturingBackend() + { + if (!OperatingSystem.IsWindows()) return; + var error = await Assert.ThrowsAsync(() => UsbStorage.Execute("status", null, false)); + Assert.Contains("safe Windows control backend", error.Message); + } +}