# Windows client design

The Windows client (`windows/`) is a separate implementation of the same report contract ([ReportFormat.md](ReportFormat.md)) in Windows PowerShell 5.1. It is not a port of the Perl code: it shares the report format, the sensor line format, the configuration key names, the `server.info` format and the transport parameter contract described in [README.md](README.md), and nothing else. Usage and installation steps are in [windows/README.md](../windows/README.md). Section numbers are kept stable because code comments cite them.

## 7.1 Scope and rules

- Target Windows PowerShell 5.1 (Windows 10, Windows Server 2016 and later). No PowerShell 7-only syntax. Every script is pure ASCII (5.1 reads a file with no BOM as ANSI).
- The package name in the report is `sysinfo-client-windows`, so CAMP never confuses its version history with the Unix client's.
- Out of scope in v1: email transport, periodic gating, PCI, virtual-guest and SMART sensors, code signing.

## 7.2 Layout and paths

| | Path |
|---|---|
| source | `windows/`: `sysinfo_client.ps1`, `sysinfo_update.ps1`, `dsEdit.ps1`, `configure.ps1`, `install.ps1`, `lib/SysinfoSensor.psm1`, `sensors/`, `transports/upload_http.ps1`, `sysinfo_client.template.json`, `sysinfo-client.seed.example.json`, `README.md`; everything in it ships (a Subversion checkout of `windows/` carries only these) |
| tests | `t/windows/` at the repository root (`run_tests.ps1`, `fixtures/`); never shipped or checked out on a host |
| bindir | `%ProgramFiles%\camp\sysinfo_client` |
| confdir | `%ProgramData%\camp\sysinfo_client` |
| config | `<confdir>\sysinfo_client.json` |
| log | `<confdir>\sysinfo_client.log` (truncated to empty when over 1 MB at the start of a run); the updater's log is `<confdir>\sysinfo_update.log` (same rule) |
| unsent report | `<confdir>\unsent.json` (written only when every transport fails; deleted by the next successful send) |
| server.info | `%ProgramData%\camp\server.info` (format and key mapping as the `server.info` rules in README.md) |
| test output | `%TEMP%\sysinfo.testing.json` |
| schedule | Task Scheduler task `\camp\sysinfo_client`, daily, as SYSTEM |

## 7.3 Client (`sysinfo_client.ps1`)

- Parameters: `-ConfigFile <path>`, `-Test`, `-Version`, `-Help`, `-LogLevel <0-5>`.
- Config: JSON only, searched as `-ConfigFile`, `<confdir>\sysinfo_client.json`, then the script's own directory. Keys and meaning as the configuration keys in README.md, same names including the `'key for ...'` transport keys. `outputType` is ignored (always JSON); `update` is read only by `sysinfo_update.ps1` (7.7) and is never copied into `system`. Keys not in the excluded list are copied into `system`, as on Unix.
- `server.info` is read every run and overrides config values as the `server.info` rules in README.md. Hostname default: the lower-cased FQDN.
- A real run must be elevated (SYSTEM or Administrator) and needs a `clientName` (from the config or `Owner:` in `server.info`); without one it logs, prints a hint and sends nothing. `-Test` needs neither, skips the ACL check and calls no transport.
- Sensor discovery: each `moduleDirs` entry (default `<bindir>\sensors`), files named `^[A-Za-z0-9][A-Za-z0-9_]*\.ps1$`, sorted, first name wins. ACL check instead of the Unix 0700/root check, on the file, its directory and `..\lib\SysinfoSensor.psm1`: the owner must be SYSTEM, Administrators or TrustedInstaller, and no ACE may grant Write, Modify, FullControl, ChangePermissions or TakeOwnership to anyone else. A failure gives status `skipped_permission`. The same check applies to transport scripts before they are loaded.
- Sensor execution: a child `powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File <sensor> "<dir>\"`, STDOUT and STDERR read asynchronously, `SYSINFO_*` environment as ReportFormat.md §1.3, timeout `sensorTimeout` (default 120 s) enforced with `taskkill /T /F` (status `timeout`). Exit codes and statuses exactly as `unix/sensors/Documentation/README.md`; STDOUT is parsed only on exit 0, with the the sensor line format in README.md rules.
- Report: as in [ReportFormat.md](ReportFormat.md), with `report.client`, `report.date` (`yyyy-MM-dd HH:mm:ss`, local), `report.version` = data version `v3.8.0`; `system.hostname`, `system.serial`, `system.UUID` plus the config keys; the `sysinfo` section as ReportFormat.md §1.5 (`client_version` is the Windows client's version); `software.sysinfo-client-windows.version`. Written with `ConvertTo-Json -Depth 20`, no BOM, one-element lists kept as arrays.
- Transports: the `transports` map in numeric key order; `sendScript` is `<name>.ps1` in `scriptDirs` (default `<bindir>\transports`); each defines `Send-SysinfoReport($Params, [string]$Report)` returning an int; the first return of 1 wins; globals and placeholder substitution as the transport rules in README.md. If all fail, the report is saved as `unsent.json` and the run exits 1. A missing transport script is logged and skipped (so a seed written for Unix hosts, with an email transport, still works).

## 7.4 Transport `upload_http.ps1`

Port of `unix/transports/upload_http`: the same parameter keys, return codes (1 sent; 4 failure; 5-9 missing key) and POST field names, file part `temp.report`, filename `<report date>_<client name>_<host name>_<serial number>.sysinfo.json` with whitespace runs turned into `_`. TLS 1.2 is forced. Success is any 2xx; redirects are not followed. The `URL` must start with `http://` or `https://` (otherwise return 4 with a message saying so).

## 7.5 Sensor library (`lib/SysinfoSensor.psm1`)

`Write-SysinfoFact -Path @(...) -Value <v>` (replaces tab, CR and LF with a space), exit-code constants, `Test-SysinfoWindows`, `Invoke-SysinfoSensor` (an uncaught error exits 4), `Exit-SysinfoSensor`, `ConvertTo-NormalisedUUID`, `Test-PlaceholderUUID` and `Test-PlaceholderSerial` (the lists of `unix/library.pm`, ReportFormat.md §1.3 rules U and P).

## 7.6 Sensors (one thing each, one OS)

Every sensor exits 1 off Windows, 2 if the CIM class or cmdlet it needs is missing, and 4 or more with a one-line STDERR reason on failure. All values are strings.

| Sensor | Keys | Source |
|---|---|---|
| `windows_identity` | `identity.*` as ReportFormat.md §1.3 (`system_uuid_raw`, `system_uuid`, `system_uuid_status`, `system_serial`, `system_serial_status`, `board_serial`, `system_manufacturer`, `system_product`, `machine_id`, `virtualization`, `configured_*`, `server_info_*`, `uuid`, `uuid_source`, `serial`, `serial_source`) | `Win32_ComputerSystemProduct`, `Win32_BIOS`, `Win32_BaseBoard`, `Win32_ComputerSystem`, registry `MachineGuid`; `virtualization` inferred from manufacturer and model (`kvm`, `hyperv`, `vmware`, `xen`, `virtualbox`), else `none` |
| `windows_system` | `system.last_boot` (Unix epoch, UTC), `system.uptime` (seconds); `operatingsystem.os_name` = `Windows`, `.description`, `.os_version`, `.kernel` (version and UBR), `.release` | `Win32_OperatingSystem`, registry `CurrentVersion` |
| `windows_storage` | `diskinfo.<letter>`: `fstype`, `size`, `used` (KiB), `mount` | `Win32_LogicalDisk`, `DriveType = 3` |
| `windows_network` | `network.<InterfaceAlias>`: `address`, `netmask`, `ip6address`, `ip6networkbits`, `mac` (lower case, colon-separated), `mtu` | `Get-NetAdapter` (Up, not loopback), `Get-NetIPAddress`, `Get-NetIPInterface` |
| `windows_software` | `software.<DisplayName>.version`, `.description` (Publisher) | registry Uninstall keys, 64- and 32-bit views; skips entries with no name, `SystemComponent`, a parent key, or an update type; never `Win32_Product` |

There is no `pci`, `xen` or `attributes` on Windows. The old CAMP importer reads `operatingsystem.*`, `system.last_boot`, `network.*`, `software.*` and identifies by `report.date`, `report.client`, `system.hostname` and `system.serial`; `diskinfo`, `identity` and `sysinfo` are ignored by it and kept for campv2.

## 7.7 Install and configuration (`install.ps1`, elevated)

- Install or upgrade (default): copies `sysinfo_client.ps1`, `sysinfo_update.ps1`, `dsEdit.ps1`, `configure.ps1`, `lib`, `sensors` and `transports` to bindir, replacing the previous copy (renamed to `sysinfo_client.old` first and restored if the copy fails, so a locked directory changes nothing; removed once the copy succeeds); locks bindir and confdir (inheritance off; SYSTEM and Administrators full control, nothing else; owner Administrators) and `%ProgramData%\camp` (the same, plus Users read, so nobody can plant a `server.info`); writes `sysinfo_client.json` only when none exists (template, then seed, then parameters, plus the BIOS serial and UUID with placeholders stored blank, hostname, `os_type` = `windows`); registers the task (SYSTEM, highest run level, daily at a random time between 01:00 and 05:00, kept on upgrade, `StartWhenAvailable`, runs on battery, 1 h limit); checks the client's ACL rule against every installed file; runs the client once with `-Test`. Ends with `RESULT: ok|fail <version> <message>`; exit 0 on ok.
- `-ClientName`, `-Location`, `-Seed <path|URL>` (a JSON seed of site-wide settings: transports, logging; never client, location or tags), `-Quiet`, `-DryRun` (prints the actions and the config, changes nothing).
- A missing client name does not block the install: it is asked for (not with `-Quiet`), and when still unknown the install finishes with a warning and the client sends nothing until a name exists.
- `-Configure` edits client name, location and tags of an installed config without reinstalling: with `-ClientName` or `-Location` it applies them silently, otherwise it prompts showing the current values.
- `-Uninstall` removes the task and bindir and keeps the config; `-Uninstall -Purge` removes it too.
- `install.ps1` also copies `sysinfo_update.ps1`. `-UpdateUrl` and `-UpdateSha256Url` set config `update.url` and `update.sha256_url` (over the seed's `update`, which a new config takes like any seed key); with `-Configure` they are applied to an existing config, and with no other change asked for, `-Configure` does not prompt.
- Upgrade by hand means unpacking the new release (or updating the svn checkout) and running `install.ps1` again; `sysinfo_update.ps1` does the same from the release zip (7.10).
- Bootstrap: a host installed before the updater existed has none; run the new release's `install.ps1` once (with `-UpdateUrl`/`-UpdateSha256Url` on an existing config, since an existing config is never changed otherwise).
- `server.info` is not ACL-checked by the client: a writable `server.info` can change the reported client name, hostname, serial and UUID. The installer's lock on `%ProgramData%\camp` is the only protection.

## 7.8 Tests

`t/windows/run_tests.ps1` is a plain script (no Pester), printing one `PASS`, `FAIL` or `SKIP` line per check and a final `RESULT:` line. It runs under PowerShell 5.1 on Windows (all checks) and under `pwsh` on Linux (Windows-only checks are skipped). It covers the the sensor line format in README.md parser cases, the sensor runner (fixture sensors for each exit code, garbage output, timeout), the report (no BOM, arrays, nested depth, required keys), `server.info`, the ACL check, the transport return codes and filename, `unsent.json` cleanup, and an installer dry run. The tests read `windows/` from the repository root, so run them from a checkout or export of the whole repository, not from an installed copy; `windows/` itself holds no tests.

## 7.9 Release

`tools/make_release` writes `sysinfo-client-windows.zip` (single top directory `sysinfo_client_windows/`, the contents of `windows/`) and its `.sha256` beside the Unix tarball (release, [README.md](README.md)), built with `python3 -m zipfile`. The owner publishes the zip, the checksum and a `sysinfo-client.seed.json` beside the existing files. The zip is the primary install route, and the file `sysinfo_update.ps1` fetches (`update.url`); a Subversion checkout of `windows/` is the backup (`windows/README.md`).

## 7.10 Update (`sysinfo_update.ps1`)

The Windows counterpart of the Unix updater in README.md, a `.zip` where Unix uses a `.tgz`. Elevated and non-interactive (`-Check` needs no elevation); parameters `-Url`, `-Sha256Url`, `-Config`, `-Check`, `-Force`, `-RequireChecksum`, `-Quiet`. Its own parameter names differ from the client's because it dot-sources `sysinfo_client.ps1` for the config, JSON and elevation functions.

- URLs: `-Url`/`-Sha256Url`, else config `update.url`/`update.sha256_url`; a URL may also be a local path. There are no built-in URLs (configuration keys, [README.md](README.md)): with none the updater stops and names `update.url`.
- Fetch with `System.Net.WebClient` (TLS 1.2). The checksum file is verified with `Get-FileHash`: a mismatch aborts; a missing file (404) is a logged warning and the update continues, unless `-RequireChecksum`; any other fetch failure aborts.
- Unpack with `System.IO.Compression` into `<confdir>\update_tmp\u_<guid>` (locked with the config directory), after refusing any entry that would land outside it; the directory is removed at the end. The release directory is the one holding `sysinfo_client.ps1` and `install.ps1`.
- The offered version is read from the text of the new `sysinfo_client.ps1` (`$script:CLIENT_VERSION`, compared as `[version]`), never by running downloaded code first. Equal or older: `RESULT: nochange`, exit 1, unless `-Force`. `-Check` reports `update available: <old> -> <new>` and installs nothing.
- Otherwise run the new release's `install.ps1 -Quiet` in a child PowerShell and report its result. The config, `server.info` and the scheduled time are kept.
- Output: `RESULT: ok|nochange|fail <version> <message>`; exit 0, 1, 2. Log: `<confdir>\sysinfo_update.log` (append) and STDOUT.
- Scheduling is not installed (as on Unix); `windows/README.md` has an example `schtasks` line. No svn method.

## 7.11 Config editor (`dsEdit.ps1`, `configure.ps1`)

A Windows PowerShell 5.1 tool so technicians edit the JSON config (or `server.info`) without syntax mistakes. It is a separate implementation of the idea behind the Unix `dsEdit` (`configure` in the Unix README), not a port: exact parity is a non-goal, the Perl `DataSerialization.pm` cannot be used (no Perl on Windows, bug 211), and dsMerge has no Windows version. `configure.ps1` is a thin wrapper that runs `dsEdit.ps1 -ClientConfig` with every parameter passed through.

- Formats: JSON and INI. The format comes from the extension (`.json`; `.ini`, `.conf`, `.info`) or `-Format`; `server.info` is INI with the delimiter `:` (`-Delimiter` overrides). YAML is refused with a message.
- File: first positional parameter or `-Path` (alias `-File`); relative paths start at the current directory and `%VARIABLES%` are expanded, so a desktop shortcut may name any file. With no file: `-ClientConfig` means `<confdir>\sysinfo_client.json`; otherwise the existing client config and `server.info` are offered.
- Interactive navigator (no `-Set`, `-Add`, `-Remove` or `-Show`): `Read-Host` based, so it works in the ISE and a plain console. The file is a tree; numbers open a map or list or change a value (kept as its type: text, number or true/false), `a` adds, `d N` deletes, `u` goes up, `w` writes, `s` writes and quits, `q` quits (asking when changes are unsaved), `v` shows the file, `?` helps. A new entry may be text, number, true/false, list or map (INI: text, or a top-level `[section]`).
- Scripted: `-Set key=value`, `-Add key=value` (append to a list unless already present), `-Remove key` or `-Remove key=value` (a list item); dotted paths (`update.url`); an existing value keeps its type, a new one is a number or true/false only when it looks like one (leading zeros stay text); `-Show` prints the result. From `cmd` or a shortcut (`-File`) each of these takes one value per run; several values need an array (`-Set a=1,b=2`) inside a PowerShell session.
- The structure is serialized by dsEdit itself (3-space indent, no depth limit, `<` and `>` not escaped, LF or the file's own CRLF), re-parsed and compared before anything is written; the previous `ConvertTo-Json -Depth` problem (silent truncation) cannot occur. A JSON file that does not parse is reported (with the parser's message) and never overwritten.
- Writing: UTF-8 without a BOM to `<file>.new` beside the original, read back and compared, then `[IO.File]::Replace(new, file, file.bak)`: atomic, keeps the ACL of the original, and the backup (which may hold transport secrets) is the original file with that same ACL. `-LiteralPath` is used throughout. Exit 0 done, 2 failed.
- Known-key check (client config only: a file named `sysinfo_client*.json` or with a `clientName`): types of `clientName`, `location`, `hostname`, `serialNumber`, `UUID`, `os_type` (text), `tags` (list of text), `sensorTimeout`, `TESTING` (number), `logging`, `transports` (each a map), `update` (map). A mismatch warns and asks "Write it anyway?"; from the command line it refuses unless `-Force`.
- Elevation: a file that cannot be opened by an unelevated user (the locked `C:\ProgramData\camp`) makes dsEdit start an elevated copy of itself (`Start-Process -Verb RunAs`, a UAC prompt, the arguments carried in one `-EncodedCommand`) and exit; the new window pauses at the end. `-NoElevate` turns this off. `-Pause` keeps a window open until Enter (desktop shortcut).
- Desktop shortcut: `powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Program Files\camp\sysinfo_client\dsEdit.ps1" -Pause "<file>"` edits that file; `configure.ps1 -Pause` edits the client config. `install.ps1 -DesktopShortcut` creates "CAMP sysinfo config" (`configure.ps1 -Pause`) and "CAMP sysinfo update" (`sysinfo_update.ps1 -Pause`) on the desktop of the user running the installer, or the public desktop with `-ShortcutAllUsers`; both carry the Run as administrator flag (bit 0x20 of byte 0x15 of the .lnk) because the program directory is unreadable to an unelevated user, so the self-elevation above is only a fallback for an administrator's filtered token. `-Uninstall` removes them from both desktops.
- Comments: INI comment lines before the first entry are kept; other comments, blank lines and lines without a delimiter are not (the tool says how many). INI values are text and keys keep their order.
