| 1 | 1 | new file mode 100644 |
| index 0000000..89513f4 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,12 @@ | ||
| 1 | +plugin_services | |
| 2 | +plugin_services.exe | |
| 3 | +plugin_services.musl | |
| 4 | +plugin_services.arm64 | |
| 5 | +plugin_services.macos-arm64 | |
| 6 | +plugin_services.macos-x86_64 | |
| 7 | +bin/ | |
| 8 | +dist/ | |
| 9 | +*.o | |
| 10 | +*.tmp | |
| 11 | +__pycache__/ | |
| 12 | +*.pyc |
| 1 | 1 | new file mode 100644 |
| index 0000000..ef80120 | ||
| --- /dev/null | ||
| +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2026 SCORPIOX INC | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | +SOFTWARE. |
| 1 | 1 | new file mode 100644 |
| index 0000000..b8d30df | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,66 @@ | ||
| 1 | +# plugin_services - SCORPIOX BOT open-source local service status board | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_services | |
| 5 | +# make musl static musl x86_64 -> ./plugin_services.musl | |
| 6 | +# make arm64 static aarch64 -> ./plugin_services.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_services.exe | |
| 8 | +# make macos Apple clang -> ./plugin_services (run on macOS) | |
| 9 | +# make test build + run tests/run.sh | |
| 10 | +# make clean | |
| 11 | + | |
| 12 | +CC ?= cc | |
| 13 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | |
| 14 | +MUSL_CC ?= musl-gcc | |
| 15 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | |
| 16 | +ARM64_CC ?= aarch64-linux-gnu-gcc | |
| 17 | +ARM64_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | |
| 18 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 19 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | |
| 20 | +SRC := src/plugin_services.c | |
| 21 | +HDRS := src/bot_theme_plugin.h src/ui_html.h | |
| 22 | +BIN := plugin_services | |
| 23 | +EXE := plugin_services.exe | |
| 24 | + | |
| 25 | +.PHONY: all native ui musl arm64 win64 macos test clean help | |
| 26 | + | |
| 27 | +all: native | |
| 28 | + | |
| 29 | +native: $(BIN) | |
| 30 | + | |
| 31 | +ui: | |
| 32 | + @python3 tools/gen_ui.py | |
| 33 | + | |
| 34 | +$(BIN): $(SRC) $(HDRS) | |
| 35 | + @echo "==> native build ($(CC))" | |
| 36 | + $(CC) $(CFLAGS) -I src -o $(BIN) $(SRC) | |
| 37 | + | |
| 38 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 39 | +musl: $(SRC) $(HDRS) | |
| 40 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 41 | + $(MUSL_CC) $(MUSL_CFLAGS) -I src -o $(BIN).musl $(SRC) | |
| 42 | + | |
| 43 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | |
| 44 | +arm64: $(SRC) $(HDRS) | |
| 45 | + @echo "==> static aarch64 build ($(ARM64_CC))" | |
| 46 | + $(ARM64_CC) $(ARM64_CFLAGS) -I src -o $(BIN).arm64 $(SRC) | |
| 47 | + | |
| 48 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 49 | +win64: $(SRC) $(HDRS) | |
| 50 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 51 | + $(WIN_CC) $(WIN_CFLAGS) -I src -o $(EXE) $(SRC) | |
| 52 | + | |
| 53 | +# Apple clang build (run this on macOS) | |
| 54 | +macos: $(SRC) $(HDRS) | |
| 55 | + @echo "==> Apple clang build" | |
| 56 | + $(CC) $(CFLAGS) -I src -o $(BIN) $(SRC) | |
| 57 | + | |
| 58 | +test: native | |
| 59 | + @sh tests/run.sh | |
| 60 | + | |
| 61 | +clean: | |
| 62 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 63 | + rm -rf bin dist | |
| 64 | + | |
| 65 | +help: | |
| 66 | + @echo "make | make ui | make musl | make arm64 | make win64 | make macos | make test | make clean" |
| 1 | 1 | new file mode 100644 |
| index 0000000..baa87a4 | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,136 @@ | ||
| 1 | +# plugin_services — local service status board for SCORPIOX BOT | |
| 2 | + | |
| 3 | +`services` is a zero-dependency C99 plugin that shows every service your node's | |
| 4 | +init system manages — state, enabled flag, PID, memory and uptime — in a | |
| 5 | +responsive dark/light board inside SCORPIOX BOT, and optionally starts, stops or | |
| 6 | +restarts one. | |
| 7 | + | |
| 8 | +``` | |
| 9 | +$ ./plugin_services --meta | |
| 10 | +{"name":"services","desc":"System services"} | |
| 11 | +``` | |
| 12 | + | |
| 13 | +## What it reads | |
| 14 | + | |
| 15 | +| Platform | Source | Detail | | |
| 16 | +|---|---|---| | |
| 17 | +| **Linux** | `systemctl list-units --type=service --all --output=json` | falls back to the plain table on systemd < 248, then to `list-unit-files`; one `systemctl show … -p Id -p MainPID -p ActiveEnterTimestamp -p MemoryCurrent -p UnitFileState …` pass fills PID / memory / since / enabled | | |
| 18 | +| **Linux (no init)** | `/proc/<pid>/{comm,stat,statm}` + `/proc/uptime` | in a container with no systemd it reports `"init_system":"none"` and lists the daemons that have been up ≥ 5 minutes, with their RSS and uptime | | |
| 19 | +| **macOS** | `launchctl list` | pid / status / label, with RSS and start time from one `ps -o pid=,rss=,lstart=` pass | | |
| 20 | +| **Windows** | `OpenSCManagerA` + `EnumServicesStatusExA` + `QueryServiceConfigA` | no shell, no `popen`, no service name on a command line | | |
| 21 | + | |
| 22 | +Nothing is written. Nothing is fetched. The binary opens no socket of any kind. | |
| 23 | + | |
| 24 | +## API | |
| 25 | + | |
| 26 | +All actions are behind node auth — `X-Bot-Password`, `Authorization: Bearer …`, | |
| 27 | +or `?pwd=` — and auth is a no-op only when `BOT_PASSWORD` is unset on the node. | |
| 28 | + | |
| 29 | +| Action | Method | Response | | |
| 30 | +|---|---|---| | |
| 31 | +| `?action=list[&filter=failed\|running\|inactive\|all]` | GET | `{"ok":true,"init_system":"systemd","control_enabled":false,"count":4,"summary":{"running":2,"failed":1,"inactive":1},"services":[…]} ` | | |
| 32 | +| `?action=show&unit=nginx.service` | GET | `{"ok":true,…,"service":{…}}` or 404 | | |
| 33 | +| `?action=control&unit=nginx.service&op=start\|stop\|restart` | POST | `{"ok":true,"unit":"…","op":"…","control_enabled":true}` | | |
| 34 | + | |
| 35 | +Each service object is: | |
| 36 | + | |
| 37 | +```json | |
| 38 | +{"name":"nginx.service","description":"A high performance web server", | |
| 39 | + "active":"active","sub":"running","enabled":"enabled", | |
| 40 | + "pid":4242,"memory_bytes":10485760,"since":"Wed 2026-11-12 04:00:00 UTC", | |
| 41 | + "failed":false} | |
| 42 | +``` | |
| 43 | + | |
| 44 | +`memory_bytes` is `null` when the platform does not report it (or when systemd | |
| 45 | +returns its `18446744073709551615` sentinel). Rows are sorted failed → running → | |
| 46 | +inactive, then by name. | |
| 47 | + | |
| 48 | +## Control is off unless the operator turns it on | |
| 49 | + | |
| 50 | +The plugin is **read-only by default**. Start / stop / restart exist only when | |
| 51 | +the node sets: | |
| 52 | + | |
| 53 | +```sh | |
| 54 | +SERVICES_ALLOW_CONTROL=1 | |
| 55 | +``` | |
| 56 | + | |
| 57 | +Without it every control request is `403 {"error":"control_disabled"}` and the | |
| 58 | +page does not render the buttons at all (it reads `control_enabled` from the | |
| 59 | +list response, so the UI can never show a button that would fail). | |
| 60 | + | |
| 61 | +When it is enabled: | |
| 62 | + | |
| 63 | +* the unit name must match `[A-Za-z0-9@._:\-]{1,160}` — `a;reboot`, `$(id)`, a | |
| 64 | + newline, `../../etc/passwd` and `-oProxyCommand=x` are all a `400 invalid | |
| 65 | + unit`, before anything is executed; | |
| 66 | +* the name is passed to `execvp("systemctl", {"systemctl", op, unit, NULL})` as a | |
| 67 | + **separate argv element**. No shell is ever involved, on any platform; | |
| 68 | +* on Windows it is `OpenServiceA` + `StartServiceA` / `ControlService(STOP)`. | |
| 69 | + No command line exists to escape from; | |
| 70 | +* on macOS it is `launchctl kickstart -k <label>` / `launchctl stop <label>`. | |
| 71 | + | |
| 72 | +Every control click is behind a `window.confirm()` dialog that names the unit. | |
| 73 | + | |
| 74 | +## HTML UI | |
| 75 | + | |
| 76 | +`GET /plugin_services` serves one self-contained page: | |
| 77 | + | |
| 78 | +* summary chips — **All / Running / Failed / Inactive** — that double as filters; | |
| 79 | +* failed-first sort, plus sort by name or state, and a search box over name and | |
| 80 | + description; | |
| 81 | +* a per-row detail drawer with state, sub-state, enabled flag, PID, memory and | |
| 82 | + since, and the control buttons when the node allows them; | |
| 83 | +* dark + light from the bot's own theme tokens (`?theme=` → `localStorage.bot_theme` | |
| 84 | + → `prefers-color-scheme`, then `{type:'sx-theme'}` posts from the host), so it | |
| 85 | + looks like part of SCORPIOX BOT rather than a separate app; | |
| 86 | +* fluid at 1440 / 1024 / 390 px and inside the Chat floating window | |
| 87 | + (`?embed=1` hides the back link and the theme toggle); | |
| 88 | +* no `<script src=>`, no CDN, no web fonts, zero emojis — inline SVG only. | |
| 89 | + | |
| 90 | +The route branching is the hub-vs-direct rule: when the page is served through | |
| 91 | +the hub (`?plugin=…`) it calls back through `/plugins?plugin=…&action=…`; opened | |
| 92 | +directly on the node it calls `/plugin_services?action=…`. Calling | |
| 93 | +`/plugins?plugin=` on the node itself returns the discovery list, not this plugin. | |
| 94 | + | |
| 95 | +## Build | |
| 96 | + | |
| 97 | +```sh | |
| 98 | +make # native -> ./plugin_services | |
| 99 | +make musl # static musl x86_64 -> ./plugin_services.musl | |
| 100 | +make arm64 # static aarch64 -> ./plugin_services.arm64 | |
| 101 | +make win64 # MinGW-w64 static -> ./plugin_services.exe (needs -ladvapi32) | |
| 102 | +make macos # Apple clang -> ./plugin_services | |
| 103 | +make test # build + tests/run.sh | |
| 104 | +``` | |
| 105 | + | |
| 106 | +`plugin.json` carries `"ldflags_win64": ["-ladvapi32"]` so the | |
| 107 | +`scorpiox-cli-botplugin` publisher links the Windows slice correctly. | |
| 108 | + | |
| 109 | +The Windows source needs `#define _WIN32_WINNT 0x0601` **before any include** — | |
| 110 | +MinGW defaults to 0x502 (Server 2003), which hides `EnumServicesStatusExA` and | |
| 111 | +`QueryServiceConfigA`. The macOS source needs `_DARWIN_C_SOURCE`. Both are set at | |
| 112 | +the top of `src/plugin_services.c`. | |
| 113 | + | |
| 114 | +## Tests | |
| 115 | + | |
| 116 | +```sh | |
| 117 | +sh tests/run.sh # 170+ offline assertions, no network, no live systemd | |
| 118 | +python3 tests/e2e.py # Playwright at 1440 / 1024 / 390, dark + light | |
| 119 | +``` | |
| 120 | + | |
| 121 | +The offline suite drives the parsers from fixtures | |
| 122 | +(`SERVICES_MOCK_SYSTEMCTL`, `SERVICES_MOCK_SYSTEMCTL_SHOW`, | |
| 123 | +`SERVICES_MOCK_LAUNCHCTL`, `SERVICES_MOCK_PROC_DIR`) so systemd JSON, the legacy | |
| 124 | +plain table, launchctl and the no-init `/proc` path are all exercised on any | |
| 125 | +host. It also asserts the injection negatives, the control gating, the | |
| 126 | +`_FORTIFY_SOURCE=2` build, and audits the whole git history for secrets and | |
| 127 | +internal addresses. | |
| 128 | + | |
| 129 | +## Permissions | |
| 130 | + | |
| 131 | +`capabilities`: `service_list`, `service_control_optional`. | |
| 132 | + | |
| 133 | +Reads: the platform service manager, `/proc` on Linux, `launchctl list` / `ps` | |
| 134 | +on macOS, the SCM on Windows. Writes: nothing. Network: none. | |
| 135 | + | |
| 136 | +MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 1 | 1 | new file mode 100644 |
| index 0000000..c700a67 | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,51 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_services | |
| 2 | +# | |
| 3 | +# Usage (from the repo root, PowerShell): | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 5 | +# | |
| 6 | +# Produces .\plugin_services.exe (static PE, runs on any Windows 10/11 x64 node). | |
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | |
| 8 | + | |
| 9 | +$ErrorActionPreference = "Stop" | |
| 10 | +$ScriptDir = $PSScriptRoot | |
| 11 | +Push-Location $ScriptDir | |
| 12 | +try { | |
| 13 | + $Src = Join-Path $ScriptDir "src\plugin_services.c" | |
| 14 | + $Out = Join-Path $ScriptDir "plugin_services.exe" | |
| 15 | + $Cc = "x86_64-w64-mingw32-gcc" | |
| 16 | + | |
| 17 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | |
| 18 | + | |
| 19 | + # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present. | |
| 20 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | |
| 21 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | |
| 22 | + $Cc = "C:\gcc16\bin\gcc.exe" | |
| 23 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | |
| 24 | + $Cc = "gcc" | |
| 25 | + } else { | |
| 26 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | |
| 27 | + } | |
| 28 | + } | |
| 29 | + | |
| 30 | + # Regenerate the page header so the binary always matches src/ui.html. | |
| 31 | + if (Get-Command python -ErrorAction SilentlyContinue) { | |
| 32 | + python tools\gen_ui.py | |
| 33 | + } | |
| 34 | + | |
| 35 | + Write-Host "==> building plugin_services.exe with $Cc" | |
| 36 | + & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src | |
| 37 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | |
| 38 | + | |
| 39 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | |
| 40 | + | |
| 41 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | |
| 42 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | |
| 43 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | |
| 44 | + throw "output is not a PE executable (missing MZ header)" | |
| 45 | + } | |
| 46 | + | |
| 47 | + Write-Host "==> ok: $Out ($($bytes.Length) bytes)" | |
| 48 | + Write-Host " smoke test: .\plugin_services.exe --meta" | |
| 49 | +} finally { | |
| 50 | + Pop-Location | |
| 51 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..280dcd9 |

| 1 | 1 | new file mode 100644 |
| index 0000000..efa9dee |

| 1 | 1 | new file mode 100644 |
| index 0000000..05aba10 |

| 1 | 1 | new file mode 100644 |
| index 0000000..7014d89 |

| 1 | 1 | new file mode 100644 |
| index 0000000..315e629 |

| 1 | 1 | new file mode 100644 |
| index 0000000..7cb3132 |

| 1 | 1 | new file mode 100644 |
| index 0000000..694f77a | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,18 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "services", | |
| 3 | + "id": "plugin_services", | |
| 4 | + "title": "Local Service Status Board", | |
| 5 | + "summary": "Zero-dependency status board for every service your node's init system manages: state, enabled flag, PID, memory and uptime on systemd, launchd and the Windows service control manager, with an optional start/stop/restart that stays off until the node operator enables it. On a container with no init system it reports init_system:none and lists the long-running daemons it can see instead of pretending the node has none. Read-only by default, node-authenticated, and unit names never reach a shell.", | |
| 6 | + "category": "system", | |
| 7 | + "license": "MIT", | |
| 8 | + "capabilities": [ | |
| 9 | + "service_list", | |
| 10 | + "service_control_optional" | |
| 11 | + ], | |
| 12 | + "trust_notice": "Executes native C code on your node. Reads the local service manager (systemctl, launchctl, or the Windows SCM) and /proc in read-only mode by default. start/stop/restart exist only when the node operator sets SERVICES_ALLOW_CONTROL=1; the unit name is validated and passed as a separate argv element, never through a shell. Makes zero outbound network requests.", | |
| 13 | + "author": "SCORPIOX INC", | |
| 14 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-services", | |
| 15 | + "ldflags_win64": [ | |
| 16 | + "-ladvapi32" | |
| 17 | + ] | |
| 18 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..df277b5 | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,365 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh - build, scan and publish plugin_services to the plugin registry. | |
| 3 | +# | |
| 4 | +# Two paths: | |
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | |
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | |
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | |
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json. | |
| 9 | +# | |
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | |
| 11 | +# comes from the environment, so this file stays safe to publish: | |
| 12 | +# | |
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | |
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | |
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | |
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | |
| 17 | +# MAC_USER / MAC_PASS (optional) | |
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | |
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | |
| 20 | +# | |
| 21 | +# Usage: | |
| 22 | +# ./release-dist.sh # full release | |
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | |
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | |
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | |
| 26 | +# ./release-dist.sh --standalone # use this script even if the CLI is installed | |
| 27 | +# # (needed for plugins that link extra Win32 libs, | |
| 28 | +# # which the CLI's fixed link line cannot express) | |
| 29 | + | |
| 30 | +set -euo pipefail | |
| 31 | + | |
| 32 | +SLUG="services" | |
| 33 | +ID="plugin_services" | |
| 34 | +VERSION="1.0.0" | |
| 35 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | |
| 36 | + | |
| 37 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | |
| 38 | +cd "$ROOT" | |
| 39 | + | |
| 40 | +DRY_RUN=0 | |
| 41 | +DO_MACOS=1 | |
| 42 | +DO_MIRROR=1 | |
| 43 | +STANDALONE=0 | |
| 44 | +for arg in "$@"; do | |
| 45 | + case "$arg" in | |
| 46 | + --standalone) STANDALONE=1 ;; | |
| 47 | + --dry-run) DRY_RUN=1 ;; | |
| 48 | + --no-macos) DO_MACOS=0 ;; | |
| 49 | + --no-mirror) DO_MIRROR=0 ;; | |
| 50 | + -h|--help) sed -n '2,32p' "$0"; exit 0 ;; | |
| 51 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | |
| 52 | + esac | |
| 53 | +done | |
| 54 | + | |
| 55 | +DIST_HOST="${DIST_HOST:-}" | |
| 56 | +DIST_PASS="${DIST_PASS:-}" | |
| 57 | +DIST_PATH="${DIST_PATH:-/data/dist}" | |
| 58 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | |
| 59 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | |
| 60 | + | |
| 61 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | |
| 62 | +mkdir -p "$STAGE" | |
| 63 | +trap 'rm -rf "$STAGE"' EXIT | |
| 64 | + | |
| 65 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | |
| 66 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | |
| 67 | + | |
| 68 | +# ---------------------------------------------------------------- 0. preflight | |
| 69 | +say "0/7 preflight" | |
| 70 | + | |
| 71 | +if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 72 | + say "using scorpiox-cli-botplugin publish" | |
| 73 | + exec scorpiox-cli-botplugin publish "$ROOT" | |
| 74 | +fi | |
| 75 | +echo " running the standalone pipeline" | |
| 76 | + | |
| 77 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | |
| 78 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | |
| 79 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | |
| 80 | +echo " version $VERSION" | |
| 81 | +echo " commit $COMMIT" | |
| 82 | + | |
| 83 | +# ---------------------------------------------------------------- 1. secret scan | |
| 84 | +say "1/7 secret & LAN scan (full history)" | |
| 85 | + | |
| 86 | +SCAN_TMP="$STAGE/history.txt" | |
| 87 | +# Scan every added/removed line of every commit. Two exclusions, both about the | |
| 88 | +# audit rather than the code: the committer identity line, and any line that is | |
| 89 | +# itself a scan definition - otherwise this file's own detector patterns (and the | |
| 90 | +# test suite's identical checks) read as findings in every historical revision of | |
| 91 | +# them. A real secret on any other line still hits. | |
| 92 | +git log -p --all 2>/dev/null \ | |
| 93 | + | grep -v '^Author: ' \ | |
| 94 | + | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \ | |
| 95 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | |
| 96 | +HITS=0 | |
| 97 | +scan() { # scan <label> <regex> | |
| 98 | + local out | |
| 99 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | |
| 100 | + if [ -n "$out" ]; then | |
| 101 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | |
| 102 | + printf '%s\n' "$out" | sed 's/^/ /' | |
| 103 | + HITS=$((HITS + 1)) | |
| 104 | + else | |
| 105 | + printf ' ok %s\n' "$1" | |
| 106 | + fi | |
| 107 | +} | |
| 108 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 109 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 110 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 111 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 112 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 113 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 114 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | |
| 115 | +P_ROOT="/codebases" | |
| 116 | +P_PICOBOT="${P_ROOT}/pico""bot" | |
| 117 | +P_WT=".work""trees" | |
| 118 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | |
| 119 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | |
| 120 | +if [ "$HITS" -ne 0 ]; then | |
| 121 | + die "secret scan found $HITS problem(s) - refusing to publish" | |
| 122 | +fi | |
| 123 | +echo " clean: 0 hits" | |
| 124 | + | |
| 125 | +# ---------------------------------------------------------------- 2. build | |
| 126 | +say "2/7 build targets" | |
| 127 | + | |
| 128 | +# linux-x86_64 (glibc, native) | |
| 129 | +if command -v cc >/dev/null 2>&1; then | |
| 130 | + cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed" | |
| 131 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | |
| 132 | +else | |
| 133 | + die "no native cc found" | |
| 134 | +fi | |
| 135 | + | |
| 136 | +# linux-x86_64-musl (fully static - the universal Linux artifact) | |
| 137 | +if command -v musl-gcc >/dev/null 2>&1; then | |
| 138 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c \ | |
| 139 | + || die "musl build failed" | |
| 140 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | |
| 141 | +else | |
| 142 | + echo " skip linux-x86_64-musl (no musl-gcc)" | |
| 143 | +fi | |
| 144 | + | |
| 145 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers) | |
| 146 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | |
| 147 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c \ | |
| 148 | + || die "arm64 build failed" | |
| 149 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | |
| 150 | +else | |
| 151 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | |
| 152 | +fi | |
| 153 | + | |
| 154 | +# windows-x86_64 (static PE) | |
| 155 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | |
| 156 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \ | |
| 157 | + -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed" | |
| 158 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | |
| 159 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | |
| 160 | +else | |
| 161 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | |
| 162 | +fi | |
| 163 | + | |
| 164 | +# macOS legs - Mach-O must be produced by Apple clang on a real Mac. | |
| 165 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | |
| 166 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | |
| 167 | + MAC_USER="${MAC_USER:-$(whoami)}" | |
| 168 | + MAC_DIR="/tmp/${ID}-mac-$$" | |
| 169 | + echo " building macOS legs on $MAC_HOST" | |
| 170 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | |
| 171 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | |
| 172 | + if [ -n "${MAC_PASS:-}" ]; then | |
| 173 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | |
| 174 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | |
| 175 | + fi | |
| 176 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | |
| 177 | + tar -czf "$STAGE/src.tgz" src | |
| 178 | + if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \ | |
| 179 | + && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then | |
| 180 | + # Build straight from the uploaded file - no src/ tree on the remote. | |
| 181 | + for slice in arm64 x86_64; do | |
| 182 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | |
| 183 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c" \ | |
| 184 | + 2>/dev/null; then | |
| 185 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | |
| 186 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | |
| 187 | + else | |
| 188 | + echo " warn: macos-$slice build failed on $MAC_HOST" | |
| 189 | + fi | |
| 190 | + done | |
| 191 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true | |
| 192 | + else | |
| 193 | + echo " warn: could not upload source to $MAC_HOST" | |
| 194 | + fi | |
| 195 | + else | |
| 196 | + echo " warn: cannot reach macOS builder $MAC_HOST" | |
| 197 | + fi | |
| 198 | +else | |
| 199 | + echo " skip macOS legs (no MAC_HOST or --no-macos)" | |
| 200 | +fi | |
| 201 | + | |
| 202 | +# ---------------------------------------------------------------- 3. manifest | |
| 203 | +say "3/7 manifest + checksums" | |
| 204 | + | |
| 205 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | |
| 206 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | |
| 207 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | |
| 208 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | |
| 209 | + | |
| 210 | +target_meta() { # target_meta <key> <file> <format> <relpath> | |
| 211 | + local key="$1" file="$2" fmt="$3" rel="$4" | |
| 212 | + [ -f "$file" ] || return 0 | |
| 213 | + local sha size | |
| 214 | + sha=$(sha256sum "$file" | awk '{print $1}') | |
| 215 | + size=$(wc -c < "$file" | tr -d ' ') | |
| 216 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | |
| 217 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | |
| 218 | +} | |
| 219 | + | |
| 220 | +{ | |
| 221 | + printf '{\n' | |
| 222 | + printf ' "slug": "%s",\n' "$SLUG" | |
| 223 | + printf ' "id": "%s",\n' "$ID" | |
| 224 | + printf ' "name": "notes",\n' | |
| 225 | + printf ' "desc": "Markdown notes",\n' | |
| 226 | + printf ' "title": "Markdown Notes",\n' | |
| 227 | + printf ' "summary": "Zero-dependency markdown notes that live on your node: create, edit, rename, search, pin and delete, with a live rendered preview next to the editor. Notes are one <id>.md file each plus index.json inside the plugin directory, every write is staged to a temp file and renamed so a crash never truncates a note, and deleted notes go to a recoverable .trash. Server-side rendering escapes note content first, so a pasted <script> is inert text. No CDN, no network requests, no database.",\n' | |
| 228 | + printf ' "category": "utilities",\n' | |
| 229 | + printf ' "version": "%s",\n' "$VERSION" | |
| 230 | + printf ' "license": "MIT",\n' | |
| 231 | + printf ' "trust_notice": "Executes native C code on your node. Reads and writes only inside its own notes directory (plugin dir/.notes, or $NOTES_DIR when set): one markdown file per note, an index.json, and a .trash subdirectory. It opens no network connection of any kind and reads nothing outside that directory.",\n' | |
| 232 | + printf ' "capabilities": ["fs_write_plugin_dir"],\n' | |
| 233 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | |
| 234 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | |
| 235 | + printf ' "git_commit": "%s",\n' "$COMMIT" | |
| 236 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 237 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | |
| 238 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | |
| 239 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | |
| 240 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 241 | + printf ' "targets": {\n' | |
| 242 | + first=1 | |
| 243 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | |
| 244 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" | |
| 245 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" | |
| 246 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" | |
| 247 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" | |
| 248 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" | |
| 249 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" | |
| 250 | + printf '\n }\n}\n' | |
| 251 | +} > "$STAGE/manifest.json" | |
| 252 | + | |
| 253 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | |
| 254 | + || die "generated manifest.json is not valid JSON" | |
| 255 | +echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)" | |
| 256 | + | |
| 257 | +# SHA256SUMS - relative paths, exactly as published | |
| 258 | +( cd "$STAGE" | |
| 259 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | |
| 260 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | |
| 261 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | |
| 262 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | |
| 263 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | |
| 264 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | |
| 265 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | |
| 266 | + true ) > "$STAGE/SHA256SUMS" | |
| 267 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | |
| 268 | + | |
| 269 | +# ---------------------------------------------------------------- 4. stage | |
| 270 | +say "4/7 stage tree" | |
| 271 | +PKG="$STAGE/pkg" | |
| 272 | +mkdir -p "$PKG" | |
| 273 | +cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | |
| 274 | +[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; } | |
| 275 | +[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; } | |
| 276 | +[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; } | |
| 277 | +[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; } | |
| 278 | +[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; } | |
| 279 | +[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; } | |
| 280 | +echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)" | |
| 281 | + | |
| 282 | +if [ "$DRY_RUN" -eq 1 ]; then | |
| 283 | + say "dry run - leaving the staging tree in $PKG" | |
| 284 | + trap - EXIT | |
| 285 | + exit 0 | |
| 286 | +fi | |
| 287 | + | |
| 288 | +# ---------------------------------------------------------------- 5. upload | |
| 289 | +say "5/7 upload to the dist server" | |
| 290 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)" | |
| 291 | +SSH=(ssh -o StrictHostKeyChecking=no) | |
| 292 | +SCP=(scp -o StrictHostKeyChecking=no) | |
| 293 | +if [ -n "$DIST_PASS" ]; then | |
| 294 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | |
| 295 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | |
| 296 | +fi | |
| 297 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | |
| 298 | + | |
| 299 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | |
| 300 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | |
| 301 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | |
| 302 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | |
| 303 | +# OpenSSH 9 refuses to scp a bare "." source. | |
| 304 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | |
| 305 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | |
| 306 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | |
| 307 | + || die "remote extract failed" | |
| 308 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | |
| 309 | + | |
| 310 | +# latest.json = copy of this version's manifest | |
| 311 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | |
| 312 | + || die "latest.json update failed" | |
| 313 | +echo " updated bot-plugins/$SLUG/latest.json" | |
| 314 | + | |
| 315 | +# index.json - merge, preserving every sibling <slug>/latest.json | |
| 316 | +say "index.json merge" | |
| 317 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | |
| 318 | +import json, os, sys, glob | |
| 319 | +slug = sys.argv[1] | |
| 320 | +entries = {} | |
| 321 | +for p in sorted(glob.glob('*/latest.json')): | |
| 322 | + s = os.path.dirname(p) | |
| 323 | + try: | |
| 324 | + entries[s] = json.load(open(p)) | |
| 325 | + except Exception: | |
| 326 | + pass | |
| 327 | +index = { | |
| 328 | + 'ok': True, | |
| 329 | + 'service': 'bot-plugins-dist', | |
| 330 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | |
| 331 | + 'count': len(entries), | |
| 332 | + 'slugs': sorted(entries), | |
| 333 | + 'plugins': [entries[k] for k in sorted(entries)], | |
| 334 | +} | |
| 335 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | |
| 336 | +os.replace('index.json.tmp', 'index.json') | |
| 337 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | |
| 338 | +PY" || die "index.json merge failed" | |
| 339 | + | |
| 340 | +# ---------------------------------------------------------------- 6. mirror | |
| 341 | +say "6/7 plugingit mirror" | |
| 342 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | |
| 343 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | |
| 344 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|") | |
| 345 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | |
| 346 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | |
| 347 | + echo " mirrored to $PLUGINGIT_REMOTE" | |
| 348 | +else | |
| 349 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | |
| 350 | +fi | |
| 351 | + | |
| 352 | +# ---------------------------------------------------------------- 7. verify | |
| 353 | +say "7/7 verify" | |
| 354 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | |
| 355 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | |
| 356 | +if [ "$CODE" = "200" ]; then | |
| 357 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | |
| 358 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | |
| 359 | +else | |
| 360 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | |
| 361 | +fi | |
| 362 | + | |
| 363 | +printf '\n\033[1mrelease complete\033[0m\n' | |
| 364 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 365 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | 1 | new file mode 100644 |
| index 0000000..0dd243b | ||
| --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | ||
| 1 | +/* | |
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | |
| 3 | + * | |
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | |
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | |
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | |
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | |
| 8 | + * localStorage key, same prepaint order. | |
| 9 | + * | |
| 10 | + * Three rules, and nothing else: | |
| 11 | + * | |
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | |
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | |
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | |
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | |
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | |
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | |
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | |
| 19 | + * it was already open when the bot changed theme. | |
| 20 | + * | |
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | |
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | |
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | |
| 24 | + * are var() references, one definition covers both themes. | |
| 25 | + * | |
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 27 | + */ | |
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | |
| 29 | +#define SX_BOT_THEME_PLUGIN_H | |
| 30 | + | |
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | |
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | |
| 33 | +#define SX_BOT_THEME_TOKENS \ | |
| 34 | +":root{color-scheme:dark;" \ | |
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | |
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | |
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | |
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | |
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | |
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | |
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | |
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | |
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | |
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | |
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | |
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | |
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | |
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | |
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | |
| 50 | +"}" \ | |
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | |
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 58 | + "--accent-dim:#0066d6;" \ | |
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 62 | + "color-scheme:light}}" \ | |
| 63 | +"html[data-theme=light]{" \ | |
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 70 | + "--accent-dim:#0066d6;" \ | |
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 74 | + "color-scheme:light}" \ | |
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | |
| 76 | +"*{box-sizing:border-box}" \ | |
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | |
| 78 | + "-webkit-font-smoothing:antialiased}" \ | |
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | |
| 80 | +"button:active{transform:scale(.98)}" \ | |
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | |
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | |
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | |
| 84 | +" * hides its own back link and its own toggle. */" \ | |
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | |
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | |
| 87 | + | |
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | |
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | |
| 90 | + * html.embedded so the embed rules apply before first paint. */ | |
| 91 | +#define SX_BOT_THEME_PREPAINT \ | |
| 92 | +"<script>(function(){var t='';" \ | |
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | |
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | |
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | |
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | |
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 99 | +"})();</script>\n" | |
| 100 | + | |
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | |
| 102 | + * at startup in case it changed while this page was already open. Fires the | |
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | |
| 104 | + * re-skin themselves from one listener. */ | |
| 105 | +#define SX_BOT_THEME_HANDOFF \ | |
| 106 | +"<script>(function(){" \ | |
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | |
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | |
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | |
| 112 | +"window.sxApplyTheme=apply;" \ | |
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | |
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | |
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | |
| 116 | +"})();</script>\n" | |
| 117 | + | |
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | |
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | |
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | |
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | |
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | |
| 123 | + | |
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | |
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | |
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | |
| 127 | +"})();</script>\n" | |
| 128 | + | |
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..a6921ba | ||
| --- /dev/null | ||
| +++ b/src/plugin_services.c | ||
| @@ -0,0 +1,1408 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_services - SCORPIOX BOT open-source local service status board | |
| 3 | + * | |
| 4 | + * One clean-room C99 binary, three modes: | |
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | |
| 6 | + * 2. ?action=list|show|control / ?format=json / POST -> JSON node API | |
| 7 | + * 3. GET (default) -> responsive HTML board | |
| 8 | + * | |
| 9 | + * It reports every service the node's init system knows about: | |
| 10 | + * | |
| 11 | + * Linux systemd via `systemctl list-units --output=json` (falls back to the | |
| 12 | + * plain table on systemd < 248), enriched once by a single | |
| 13 | + * `systemctl show --type=service --all -p ...` pass. Inside a | |
| 14 | + * container with no init system (no /run/systemd/system) it reports | |
| 15 | + * init_system:"none" and lists the long-running daemons it can see in | |
| 16 | + * /proc instead of pretending the node has none. | |
| 17 | + * macOS `launchctl list` (pid / status / label), with memory and uptime | |
| 18 | + * filled in from one `ps` pass over the returned pids. | |
| 19 | + * Windows OpenSCManagerA + EnumServicesStatusExA and QueryServiceConfigA. | |
| 20 | + * No shell, no popen, no service name ever reaches a command line. | |
| 21 | + * | |
| 22 | + * Read-only by default. start/stop/restart exist only when the node operator | |
| 23 | + * sets SERVICES_ALLOW_CONTROL=1, requires node auth, and every unit name is | |
| 24 | + * validated against [A-Za-z0-9@._:-]{1,160} before it is handed to execvp as a | |
| 25 | + * separate argv element (POSIX) or the SCM (Windows). No unit name is ever | |
| 26 | + * interpolated into a shell string, so `a;reboot` is a 400, not a shell escape. | |
| 27 | + * | |
| 28 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | |
| 29 | + * x86_64-w64-mingw32-gcc -static. | |
| 30 | + * | |
| 31 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 32 | + */ | |
| 33 | + | |
| 34 | +/* Must be the very first thing: advapi32's EnumServicesStatusExA and | |
| 35 | + * QueryServiceConfigA are gated on _WIN32_WINNT, and MinGW defaults to 0x502 | |
| 36 | + * (Server 2003) which hides them. */ | |
| 37 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 38 | +# define _WIN32_WINNT 0x0601 | |
| 39 | +#endif | |
| 40 | + | |
| 41 | +#if !defined(_WIN32) | |
| 42 | +# define _POSIX_C_SOURCE 200809L | |
| 43 | +# define _DEFAULT_SOURCE 1 | |
| 44 | +# if defined(__APPLE__) | |
| 45 | +# define _DARWIN_C_SOURCE 1 | |
| 46 | +# endif | |
| 47 | +#endif | |
| 48 | + | |
| 49 | +#include <stdio.h> | |
| 50 | +#include <stdlib.h> | |
| 51 | +#include <string.h> | |
| 52 | +#include <ctype.h> | |
| 53 | +#include <errno.h> | |
| 54 | +#include <time.h> | |
| 55 | + | |
| 56 | +#if defined(_WIN32) | |
| 57 | +# define WIN32_LEAN_AND_MEAN | |
| 58 | +# include <windows.h> | |
| 59 | +# define sx_popen _popen | |
| 60 | +# define sx_pclose _pclose | |
| 61 | +#else | |
| 62 | +# include <unistd.h> | |
| 63 | +# include <dirent.h> | |
| 64 | +# include <sys/types.h> | |
| 65 | +# include <sys/wait.h> | |
| 66 | +# define sx_popen popen | |
| 67 | +# define sx_pclose pclose | |
| 68 | +#endif | |
| 69 | + | |
| 70 | +#include "bot_theme_plugin.h" | |
| 71 | +#include "ui_html.h" | |
| 72 | + | |
| 73 | +#define PLUGIN_SLUG "services" | |
| 74 | +#define PLUGIN_ID "plugin_services" | |
| 75 | +#define PLUGIN_VER "1.0.0" | |
| 76 | + | |
| 77 | +#define PLUGIN_NAME "services" | |
| 78 | +#define PLUGIN_DESC "System services" | |
| 79 | + | |
| 80 | +#define MAX_SERVICES 2048 | |
| 81 | +#define NAME_SZ 192 | |
| 82 | +#define DESC_SZ 192 | |
| 83 | +#define STATE_SZ 32 | |
| 84 | +#define EN_SZ 32 | |
| 85 | +#define OUT_SZ (1024 * 1024) | |
| 86 | + | |
| 87 | +/* init systems */ | |
| 88 | +#define INIT_NONE 0 | |
| 89 | +#define INIT_SYSTEMD 1 | |
| 90 | +#define INIT_LAUNCHD 2 | |
| 91 | +#define INIT_SCM 3 | |
| 92 | + | |
| 93 | +typedef struct { | |
| 94 | + char name[NAME_SZ]; /* unit / label / service name */ | |
| 95 | + char desc[DESC_SZ]; | |
| 96 | + char active[STATE_SZ]; /* active | inactive | failed | running | stopped */ | |
| 97 | + char sub[STATE_SZ]; /* running | dead | exited | ... */ | |
| 98 | + char enabled[EN_SZ]; /* enabled | disabled | static | - */ | |
| 99 | + int pid; | |
| 100 | + unsigned long long mem; /* bytes, 0 = unknown */ | |
| 101 | + char since[40]; | |
| 102 | +} svc_t; | |
| 103 | + | |
| 104 | +static svc_t g_svc[MAX_SERVICES]; | |
| 105 | +static int g_count; | |
| 106 | +static int g_init = INIT_NONE; | |
| 107 | +static int g_control = 0; | |
| 108 | + | |
| 109 | +/* ------------------------------------------------------------------ */ | |
| 110 | +/* Growable output buffer */ | |
| 111 | +/* ------------------------------------------------------------------ */ | |
| 112 | + | |
| 113 | +typedef struct { char *p; size_t n, cap; } buf_t; | |
| 114 | + | |
| 115 | +static int buf_need(buf_t *b, size_t extra) | |
| 116 | +{ | |
| 117 | + size_t want; | |
| 118 | + char *np; | |
| 119 | + if (b->n + extra + 1 <= b->cap) return 1; | |
| 120 | + want = b->cap ? b->cap : 4096; | |
| 121 | + while (want < b->n + extra + 1) want *= 2; | |
| 122 | + np = (char *)realloc(b->p, want); | |
| 123 | + if (!np) return 0; | |
| 124 | + b->p = np; | |
| 125 | + b->cap = want; | |
| 126 | + return 1; | |
| 127 | +} | |
| 128 | + | |
| 129 | +static void buf_add(buf_t *b, const char *s, size_t n) | |
| 130 | +{ | |
| 131 | + if (!b || !s) return; | |
| 132 | + if (!buf_need(b, n)) return; | |
| 133 | + memcpy(b->p + b->n, s, n); | |
| 134 | + b->n += n; | |
| 135 | + b->p[b->n] = '\0'; | |
| 136 | +} | |
| 137 | + | |
| 138 | +static void buf_puts(buf_t *b, const char *s) | |
| 139 | +{ | |
| 140 | + if (s) buf_add(b, s, strlen(s)); | |
| 141 | +} | |
| 142 | + | |
| 143 | +static void buf_putc(buf_t *b, char c) { buf_add(b, &c, 1); } | |
| 144 | + | |
| 145 | +static const char *buf_str(buf_t *b) { return b->p ? b->p : ""; } | |
| 146 | + | |
| 147 | +static void buf_free(buf_t *b) | |
| 148 | +{ | |
| 149 | + if (b) { free(b->p); b->p = NULL; b->n = b->cap = 0; } | |
| 150 | +} | |
| 151 | + | |
| 152 | +/* JSON string escaping into a buffer. */ | |
| 153 | +static void json_into(buf_t *b, const char *s) | |
| 154 | +{ | |
| 155 | + buf_putc(b, '"'); | |
| 156 | + for (; s && *s; s++) { | |
| 157 | + unsigned char c = (unsigned char)*s; | |
| 158 | + switch (c) { | |
| 159 | + case '"': buf_puts(b, "\\\""); break; | |
| 160 | + case '\\': buf_puts(b, "\\\\"); break; | |
| 161 | + case '\n': buf_puts(b, "\\n"); break; | |
| 162 | + case '\r': buf_puts(b, "\\r"); break; | |
| 163 | + case '\t': buf_puts(b, "\\t"); break; | |
| 164 | + default: | |
| 165 | + if (c < 0x20) { | |
| 166 | + char tmp[8]; | |
| 167 | + snprintf(tmp, sizeof tmp, "\\u%04x", c); | |
| 168 | + buf_puts(b, tmp); | |
| 169 | + } else { | |
| 170 | + buf_putc(b, (char)c); | |
| 171 | + } | |
| 172 | + } | |
| 173 | + } | |
| 174 | + buf_putc(b, '"'); | |
| 175 | +} | |
| 176 | + | |
| 177 | +/* ------------------------------------------------------------------ */ | |
| 178 | +/* Small string utilities */ | |
| 179 | +/* ------------------------------------------------------------------ */ | |
| 180 | + | |
| 181 | +static void str_copy(char *dst, size_t sz, const char *src) | |
| 182 | +{ | |
| 183 | + size_t n; | |
| 184 | + if (!dst || sz == 0) return; | |
| 185 | + if (!src) { dst[0] = '\0'; return; } | |
| 186 | + n = strlen(src); | |
| 187 | + if (n >= sz) n = sz - 1; | |
| 188 | + memcpy(dst, src, n); | |
| 189 | + dst[n] = '\0'; | |
| 190 | +} | |
| 191 | + | |
| 192 | +static void str_trim(char *s) | |
| 193 | +{ | |
| 194 | + char *p; | |
| 195 | + size_t n; | |
| 196 | + if (!s) return; | |
| 197 | + p = s; | |
| 198 | + while (*p && isspace((unsigned char)*p)) p++; | |
| 199 | + if (p != s) memmove(s, p, strlen(p) + 1); | |
| 200 | + n = strlen(s); | |
| 201 | + while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; | |
| 202 | +} | |
| 203 | + | |
| 204 | +static void url_decode(char *s) | |
| 205 | +{ | |
| 206 | + char *o = s; | |
| 207 | + if (!s) return; | |
| 208 | + while (*s) { | |
| 209 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 210 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 211 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 212 | + *o++ = (char)((hi << 4) | lo); | |
| 213 | + s += 3; | |
| 214 | + } else if (*s == '+') { | |
| 215 | + *o++ = ' '; | |
| 216 | + s++; | |
| 217 | + } else { | |
| 218 | + *o++ = *s++; | |
| 219 | + } | |
| 220 | + } | |
| 221 | + *o = '\0'; | |
| 222 | +} | |
| 223 | + | |
| 224 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 225 | +{ | |
| 226 | + size_t klen; | |
| 227 | + const char *p; | |
| 228 | + | |
| 229 | + if (!out || outsz == 0) return 0; | |
| 230 | + out[0] = '\0'; | |
| 231 | + if (!qs || !key) return 0; | |
| 232 | + klen = strlen(key); | |
| 233 | + | |
| 234 | + for (p = qs; *p; ) { | |
| 235 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 236 | + const char *v = p + klen + 1; | |
| 237 | + size_t i = 0; | |
| 238 | + while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++; | |
| 239 | + out[i] = '\0'; | |
| 240 | + url_decode(out); | |
| 241 | + return 1; | |
| 242 | + } | |
| 243 | + p = strchr(p, '&'); | |
| 244 | + if (!p) break; | |
| 245 | + p++; | |
| 246 | + } | |
| 247 | + return 0; | |
| 248 | +} | |
| 249 | + | |
| 250 | +/* Unit / label / service name allowlist. Anything that could be read as shell | |
| 251 | + * syntax, a path, or an option is rejected outright. */ | |
| 252 | +static int valid_unit(const char *s) | |
| 253 | +{ | |
| 254 | + size_t n; | |
| 255 | + if (!s) return 0; | |
| 256 | + n = strlen(s); | |
| 257 | + if (n < 1 || n > 160) return 0; | |
| 258 | + for (; *s; s++) { | |
| 259 | + unsigned char c = (unsigned char)*s; | |
| 260 | + if (isalnum(c)) continue; | |
| 261 | + if (c == '@' || c == '.' || c == '_' || c == ':' || c == '-' || c == '\\') | |
| 262 | + continue; | |
| 263 | + return 0; | |
| 264 | + } | |
| 265 | + return 1; | |
| 266 | +} | |
| 267 | + | |
| 268 | +static int is_post_request(void) | |
| 269 | +{ | |
| 270 | + const char *m = getenv("REQUEST_METHOD"); | |
| 271 | + return m && strcmp(m, "POST") == 0; | |
| 272 | +} | |
| 273 | + | |
| 274 | +/* ------------------------------------------------------------------ */ | |
| 275 | +/* Node authentication */ | |
| 276 | +/* ------------------------------------------------------------------ */ | |
| 277 | + | |
| 278 | +static void require_node_auth(void) | |
| 279 | +{ | |
| 280 | + const char *np = getenv("BOT_PASSWORD"); | |
| 281 | + const char *xp; | |
| 282 | + const char *auth; | |
| 283 | + const char *qs; | |
| 284 | + char qpwd[256]; | |
| 285 | + | |
| 286 | + if (!np || !*np) return; | |
| 287 | + | |
| 288 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 289 | + if (xp && strcmp(xp, np) == 0) return; | |
| 290 | + | |
| 291 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 292 | + if (auth) { | |
| 293 | + while (*auth == ' ') auth++; | |
| 294 | + if (strncmp(auth, "Bearer ", 7) == 0) { | |
| 295 | + auth += 7; | |
| 296 | + while (*auth == ' ') auth++; | |
| 297 | + if (strcmp(auth, np) == 0) return; | |
| 298 | + } | |
| 299 | + } | |
| 300 | + | |
| 301 | + qs = getenv("QUERY_STRING"); | |
| 302 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | |
| 303 | + return; | |
| 304 | + | |
| 305 | + fputs("Status: 401 Unauthorized\r\n" | |
| 306 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 307 | + "Cache-Control: no-store\r\n" | |
| 308 | + "X-Content-Type-Options: nosniff\r\n\r\n" | |
| 309 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 310 | + exit(0); | |
| 311 | +} | |
| 312 | + | |
| 313 | +/* ------------------------------------------------------------------ */ | |
| 314 | +/* Command capture and argv execution */ | |
| 315 | +/* ------------------------------------------------------------------ */ | |
| 316 | + | |
| 317 | +/* Every command string passed here is a CONSTANT defined in this file, or is | |
| 318 | + * built from a value that already passed valid_unit(). Nothing user-supplied | |
| 319 | + * reaches this function unvalidated. */ | |
| 320 | +static int capture(const char *cmd, char *out, size_t outsz) | |
| 321 | +{ | |
| 322 | + FILE *f; | |
| 323 | + size_t n; | |
| 324 | + | |
| 325 | + if (!out || outsz == 0) return -1; | |
| 326 | + out[0] = '\0'; | |
| 327 | + f = sx_popen(cmd, "r"); | |
| 328 | + if (!f) return -1; | |
| 329 | + n = fread(out, 1, outsz - 1, f); | |
| 330 | + out[n] = '\0'; | |
| 331 | + if (sx_pclose(f) != 0) { | |
| 332 | + /* still return what we read: callers check for emptiness */ | |
| 333 | + } | |
| 334 | + return (int)n; | |
| 335 | +} | |
| 336 | + | |
| 337 | +#if !defined(_WIN32) | |
| 338 | +/* Returns the child's exit status, or -1 when it could not be started. The | |
| 339 | + * unit is a separate argv element, so no shell ever sees it. */ | |
| 340 | +static int run_argv(char *const argv[]) | |
| 341 | +{ | |
| 342 | + pid_t pid; | |
| 343 | + int st = 0; | |
| 344 | + | |
| 345 | + pid = fork(); | |
| 346 | + if (pid < 0) return -1; | |
| 347 | + if (pid == 0) { | |
| 348 | + execvp(argv[0], argv); | |
| 349 | + _exit(127); | |
| 350 | + } | |
| 351 | + if (waitpid(pid, &st, 0) < 0) return -1; | |
| 352 | + if (WIFEXITED(st)) return WEXITSTATUS(st); | |
| 353 | + return -1; | |
| 354 | +} | |
| 355 | +#endif | |
| 356 | + | |
| 357 | +/* ------------------------------------------------------------------ */ | |
| 358 | +/* Minimal JSON field extraction (for systemctl --output=json output) */ | |
| 359 | +/* ------------------------------------------------------------------ */ | |
| 360 | + | |
| 361 | +static int json_read_string_at(const char **pp, char *out, size_t outsz) | |
| 362 | +{ | |
| 363 | + const char *p = *pp; | |
| 364 | + size_t i = 0; | |
| 365 | + | |
| 366 | + if (!p || *p != '"') return 0; | |
| 367 | + p++; | |
| 368 | + while (*p && *p != '"') { | |
| 369 | + char c = *p; | |
| 370 | + if (c == '\\' && p[1]) { | |
| 371 | + p++; | |
| 372 | + switch (*p) { | |
| 373 | + case 'n': c = '\n'; break; | |
| 374 | + case 'r': c = '\r'; break; | |
| 375 | + case 't': c = '\t'; break; | |
| 376 | + case 'b': c = '\b'; break; | |
| 377 | + case 'f': c = '\f'; break; | |
| 378 | + case 'u': { | |
| 379 | + /* keep it simple: decode the low byte of the code point */ | |
| 380 | + unsigned int v = 0; | |
| 381 | + int k; | |
| 382 | + p++; | |
| 383 | + for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) { | |
| 384 | + v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) | |
| 385 | + ? *p - '0' | |
| 386 | + : tolower((unsigned char)*p) - 'a' + 10); | |
| 387 | + } | |
| 388 | + if (i + 1 < outsz) out[i++] = (char)(v & 0xff); | |
| 389 | + continue; | |
| 390 | + } | |
| 391 | + default: c = *p; break; | |
| 392 | + } | |
| 393 | + p++; | |
| 394 | + } else { | |
| 395 | + p++; | |
| 396 | + } | |
| 397 | + if (i + 1 < outsz) out[i++] = c; | |
| 398 | + } | |
| 399 | + if (*p == '"') p++; | |
| 400 | + out[i] = '\0'; | |
| 401 | + *pp = p; | |
| 402 | + return 1; | |
| 403 | +} | |
| 404 | + | |
| 405 | +/* Find "key":"value" inside one flat object slice [obj, obj_end). */ | |
| 406 | +static int json_field(const char *obj, const char *end, const char *key, | |
| 407 | + char *out, size_t outsz) | |
| 408 | +{ | |
| 409 | + size_t klen = strlen(key); | |
| 410 | + const char *p = obj; | |
| 411 | + | |
| 412 | + if (!out || outsz == 0) return 0; | |
| 413 | + out[0] = '\0'; | |
| 414 | + | |
| 415 | + while (p && p < end) { | |
| 416 | + if (*p == '"' && (size_t)(end - p) > klen + 1 && | |
| 417 | + strncmp(p + 1, key, klen) == 0 && p[1 + klen] == '"') { | |
| 418 | + const char *q = p + klen + 2; | |
| 419 | + while (q < end && isspace((unsigned char)*q)) q++; | |
| 420 | + if (q < end && *q == ':') { | |
| 421 | + q++; | |
| 422 | + while (q < end && isspace((unsigned char)*q)) q++; | |
| 423 | + if (q < end && *q == '"') | |
| 424 | + return json_read_string_at(&q, out, outsz); | |
| 425 | + if (q < end) { | |
| 426 | + size_t i = 0; | |
| 427 | + while (q < end && *q != ',' && *q != '}' && | |
| 428 | + i + 1 < outsz) { | |
| 429 | + if (!isspace((unsigned char)*q)) out[i++] = *q; | |
| 430 | + q++; | |
| 431 | + } | |
| 432 | + out[i] = '\0'; | |
| 433 | + return 1; | |
| 434 | + } | |
| 435 | + } | |
| 436 | + return 0; | |
| 437 | + } | |
| 438 | + if (*p == '"') { | |
| 439 | + char tmp[8]; | |
| 440 | + const char *skip = p; | |
| 441 | + json_read_string_at(&skip, tmp, sizeof tmp); | |
| 442 | + p = skip; | |
| 443 | + continue; | |
| 444 | + } | |
| 445 | + p++; | |
| 446 | + } | |
| 447 | + return 0; | |
| 448 | +} | |
| 449 | + | |
| 450 | +/* ------------------------------------------------------------------ */ | |
| 451 | +/* Collection: systemd (Linux) */ | |
| 452 | +/* ------------------------------------------------------------------ */ | |
| 453 | + | |
| 454 | +static void svc_add(const char *name, const char *desc, const char *active, | |
| 455 | + const char *sub, int pid) | |
| 456 | +{ | |
| 457 | + svc_t *s; | |
| 458 | + if (g_count >= MAX_SERVICES) return; | |
| 459 | + s = &g_svc[g_count++]; | |
| 460 | + memset(s, 0, sizeof *s); | |
| 461 | + str_copy(s->name, sizeof s->name, name); | |
| 462 | + str_copy(s->desc, sizeof s->desc, desc); | |
| 463 | + str_copy(s->active, sizeof s->active, active); | |
| 464 | + str_copy(s->sub, sizeof s->sub, sub); | |
| 465 | + str_copy(s->enabled, sizeof s->enabled, "-"); | |
| 466 | + str_copy(s->since, sizeof s->since, "-"); | |
| 467 | + s->pid = pid; | |
| 468 | +} | |
| 469 | + | |
| 470 | +static svc_t *svc_find(const char *name) | |
| 471 | +{ | |
| 472 | + int i; | |
| 473 | + if (!name) return NULL; | |
| 474 | + for (i = 0; i < g_count; i++) | |
| 475 | + if (strcmp(g_svc[i].name, name) == 0) return &g_svc[i]; | |
| 476 | + return NULL; | |
| 477 | +} | |
| 478 | + | |
| 479 | +static char *read_file_all(const char *path, size_t *len) | |
| 480 | +{ | |
| 481 | + FILE *f; | |
| 482 | + char *buf; | |
| 483 | + long sz; | |
| 484 | + size_t n; | |
| 485 | + | |
| 486 | + f = fopen(path, "rb"); | |
| 487 | + if (!f) return NULL; | |
| 488 | + sz = 0; | |
| 489 | + /* /proc files report st_size 0 and are not seekable, so only trust the | |
| 490 | + * size when the seek actually works; otherwise read until EOF. */ | |
| 491 | + if (fseek(f, 0, SEEK_END) == 0) { | |
| 492 | + sz = ftell(f); | |
| 493 | + if (sz < 0) sz = 0; | |
| 494 | + if (sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } | |
| 495 | + rewind(f); | |
| 496 | + } | |
| 497 | + buf = (char *)malloc((size_t)(sz > 0 ? sz : 4096) + 1); | |
| 498 | + if (!buf) { fclose(f); return NULL; } | |
| 499 | + if (sz > 0) { | |
| 500 | + n = fread(buf, 1, (size_t)sz, f); | |
| 501 | + } else { | |
| 502 | + size_t cap = 4096; | |
| 503 | + n = 0; | |
| 504 | + for (;;) { | |
| 505 | + size_t got; | |
| 506 | + if (n == cap) { | |
| 507 | + char *np; | |
| 508 | + cap *= 2; | |
| 509 | + if (cap > 8 * 1024 * 1024) break; | |
| 510 | + np = (char *)realloc(buf, cap + 1); | |
| 511 | + if (!np) break; | |
| 512 | + buf = np; | |
| 513 | + } | |
| 514 | + got = fread(buf + n, 1, cap - n, f); | |
| 515 | + if (got == 0) break; | |
| 516 | + n += got; | |
| 517 | + } | |
| 518 | + } | |
| 519 | + buf[n] = '\0'; | |
| 520 | + fclose(f); | |
| 521 | + if (len) *len = n; | |
| 522 | + return buf; | |
| 523 | +} | |
| 524 | + | |
| 525 | +/* Parse the systemctl --output=json array into g_svc. */ | |
| 526 | +static void parse_json_units(const char *json) | |
| 527 | +{ | |
| 528 | + const char *p = json; | |
| 529 | + | |
| 530 | + while (p && *p) { | |
| 531 | + const char *start, *end; | |
| 532 | + char unit[NAME_SZ], load[STATE_SZ], active[STATE_SZ]; | |
| 533 | + char sub[STATE_SZ], desc[DESC_SZ]; | |
| 534 | + int depth = 0; | |
| 535 | + | |
| 536 | + start = strchr(p, '{'); | |
| 537 | + if (!start) break; | |
| 538 | + end = start; | |
| 539 | + while (*end) { | |
| 540 | + if (*end == '"') { | |
| 541 | + char tmp[2]; | |
| 542 | + json_read_string_at(&end, tmp, sizeof tmp); | |
| 543 | + continue; | |
| 544 | + } | |
| 545 | + if (*end == '{') depth++; | |
| 546 | + else if (*end == '}') { | |
| 547 | + depth--; | |
| 548 | + if (depth == 0) { end++; break; } | |
| 549 | + } | |
| 550 | + end++; | |
| 551 | + } | |
| 552 | + unit[0] = load[0] = active[0] = sub[0] = desc[0] = '\0'; | |
| 553 | + json_field(start, end, "unit", unit, sizeof unit); | |
| 554 | + json_field(start, end, "load", load, sizeof load); | |
| 555 | + json_field(start, end, "active", active, sizeof active); | |
| 556 | + json_field(start, end, "sub", sub, sizeof sub); | |
| 557 | + json_field(start, end, "description", desc, sizeof desc); | |
| 558 | + if (unit[0] && strcmp(load, "not-found") != 0) | |
| 559 | + svc_add(unit, desc, active, sub, 0); | |
| 560 | + p = end; | |
| 561 | + } | |
| 562 | +} | |
| 563 | + | |
| 564 | +/* Parse the pre-248 plain table: | |
| 565 | + * UNIT LOAD ACTIVE SUB DESCRIPTION | |
| 566 | + * ssh.service loaded active running OpenBSD Secure Shell server | |
| 567 | + */ | |
| 568 | +static void parse_plain_units(const char *text) | |
| 569 | +{ | |
| 570 | + const char *p = text; | |
| 571 | + | |
| 572 | + while (p && *p) { | |
| 573 | + const char *nl = strchr(p, '\n'); | |
| 574 | + size_t len = nl ? (size_t)(nl - p) : strlen(p); | |
| 575 | + char line[1024]; | |
| 576 | + char unit[NAME_SZ], load[STATE_SZ], active[STATE_SZ], sub[STATE_SZ]; | |
| 577 | + char desc[DESC_SZ]; | |
| 578 | + int n = 0, off = 0; | |
| 579 | + | |
| 580 | + if (len >= sizeof line) len = sizeof line - 1; | |
| 581 | + memcpy(line, p, len); | |
| 582 | + line[len] = '\0'; | |
| 583 | + p = nl ? nl + 1 : p + strlen(p); | |
| 584 | + | |
| 585 | + if (len < 4) continue; | |
| 586 | + if (strstr(line, "UNIT") && strstr(line, "LOAD")) continue; | |
| 587 | + if (strstr(line, "loaded units listed")) continue; | |
| 588 | + if (strstr(line, "To show all installed")) continue; | |
| 589 | + | |
| 590 | + unit[0] = load[0] = active[0] = sub[0] = desc[0] = '\0'; | |
| 591 | + n = sscanf(line, "%191s %31s %31s %31s %n", | |
| 592 | + unit, load, active, sub, &off); | |
| 593 | + if (n < 4) continue; | |
| 594 | + if (strcmp(load, "loaded") != 0 && strcmp(load, "not-found") != 0) continue; | |
| 595 | + if (strcmp(load, "not-found") == 0) continue; | |
| 596 | + if (off > 0 && (size_t)off < len) { | |
| 597 | + str_copy(desc, sizeof desc, line + off); | |
| 598 | + str_trim(desc); | |
| 599 | + } | |
| 600 | + if (!strchr(unit, '.')) continue; | |
| 601 | + svc_add(unit, desc, active, sub, 0); | |
| 602 | + } | |
| 603 | +} | |
| 604 | + | |
| 605 | +/* One pass over `systemctl show --type=service --all -p ...`, whose output is | |
| 606 | + * key=value blocks separated by a blank line. */ | |
| 607 | +static void apply_show(const char *text) | |
| 608 | +{ | |
| 609 | + const char *p = text; | |
| 610 | + | |
| 611 | + while (p && *p) { | |
| 612 | + char name[NAME_SZ] = {0}, pid_s[24] = {0}, since[40] = {0}; | |
| 613 | + char mem_s[32] = {0}, file_state[EN_SZ] = {0}; | |
| 614 | + char active[STATE_SZ] = {0}, sub[STATE_SZ] = {0}, desc[DESC_SZ] = {0}; | |
| 615 | + svc_t *s; | |
| 616 | + | |
| 617 | + { | |
| 618 | + const char *nl = strstr(p, "\n\n"); | |
| 619 | + const char *end = nl ? nl : p + strlen(p); | |
| 620 | + const char *line = p; | |
| 621 | + while (line < end) { | |
| 622 | + const char *eol = strchr(line, '\n'); | |
| 623 | + if (!eol || eol > end) eol = end; | |
| 624 | + { | |
| 625 | + size_t l = (size_t)(eol - line); | |
| 626 | + char l2[512]; | |
| 627 | + char *eq; | |
| 628 | + if (l < sizeof l2) { | |
| 629 | + memcpy(l2, line, l); | |
| 630 | + l2[l] = '\0'; | |
| 631 | + eq = strchr(l2, '='); | |
| 632 | + if (eq) { | |
| 633 | + *eq++ = '\0'; | |
| 634 | + if (strcmp(l2, "Id") == 0) str_copy(name, sizeof name, eq); | |
| 635 | + else if (strcmp(l2, "MainPID") == 0) str_copy(pid_s, sizeof pid_s, eq); | |
| 636 | + else if (strcmp(l2, "ActiveEnterTimestamp") == 0) str_copy(since, sizeof since, eq); | |
| 637 | + else if (strcmp(l2, "MemoryCurrent") == 0) str_copy(mem_s, sizeof mem_s, eq); | |
| 638 | + else if (strcmp(l2, "UnitFileState") == 0) str_copy(file_state, sizeof file_state, eq); | |
| 639 | + else if (strcmp(l2, "ActiveState") == 0) str_copy(active, sizeof active, eq); | |
| 640 | + else if (strcmp(l2, "SubState") == 0) str_copy(sub, sizeof sub, eq); | |
| 641 | + else if (strcmp(l2, "Description") == 0) str_copy(desc, sizeof desc, eq); | |
| 642 | + } | |
| 643 | + } | |
| 644 | + } | |
| 645 | + line = eol < end ? eol + 1 : end; | |
| 646 | + } | |
| 647 | + p = nl ? nl + 2 : end; | |
| 648 | + } | |
| 649 | + | |
| 650 | + if (!name[0]) continue; | |
| 651 | + s = svc_find(name); | |
| 652 | + if (!s) { | |
| 653 | + if (desc[0] || active[0]) { | |
| 654 | + svc_add(name, desc, active, sub, 0); | |
| 655 | + s = svc_find(name); | |
| 656 | + } | |
| 657 | + } | |
| 658 | + if (!s) continue; | |
| 659 | + s->pid = atoi(pid_s); | |
| 660 | + if (mem_s[0] && strncmp(mem_s, "18446744073709551615", 20) != 0) | |
| 661 | + s->mem = strtoull(mem_s, NULL, 10); | |
| 662 | + if (file_state[0]) str_copy(s->enabled, sizeof s->enabled, file_state); | |
| 663 | + if (since[0] && strcmp(since, "n/a") != 0) { | |
| 664 | + str_copy(s->since, sizeof s->since, since); | |
| 665 | + } | |
| 666 | + if (active[0] && !s->active[0]) str_copy(s->active, sizeof s->active, active); | |
| 667 | + if (sub[0] && !s->sub[0]) str_copy(s->sub, sizeof s->sub, sub); | |
| 668 | + if (desc[0] && !s->desc[0]) str_copy(s->desc, sizeof s->desc, desc); | |
| 669 | + } | |
| 670 | +} | |
| 671 | + | |
| 672 | +/* Containers with no init system: list /proc/<pid> long-running daemons. */ | |
| 673 | +static int collect_proc_daemons(void) | |
| 674 | +{ | |
| 675 | +#if defined(_WIN32) | |
| 676 | + return 0; | |
| 677 | +#else | |
| 678 | + const char *root = getenv("SERVICES_MOCK_PROC_DIR"); | |
| 679 | + DIR *d; | |
| 680 | + struct dirent *de; | |
| 681 | + double uptime_s = 0.0; | |
| 682 | + | |
| 683 | + if (!root || !*root) root = "/proc"; | |
| 684 | + | |
| 685 | + { | |
| 686 | + char up[64]; | |
| 687 | + char path[512]; | |
| 688 | + FILE *f; | |
| 689 | + snprintf(path, sizeof path, "%s/uptime", root); | |
| 690 | + f = fopen(path, "r"); | |
| 691 | + if (f) { | |
| 692 | + if (fgets(up, sizeof up, f)) uptime_s = atof(up); | |
| 693 | + fclose(f); | |
| 694 | + } | |
| 695 | + } | |
| 696 | + if (uptime_s <= 0.0) return 0; | |
| 697 | + | |
| 698 | + d = opendir(root); | |
| 699 | + if (!d) return 0; | |
| 700 | + while ((de = readdir(d)) != NULL && g_count < MAX_SERVICES) { | |
| 701 | + char path[1024], comm[NAME_SZ], statline[2048]; | |
| 702 | + char *buf; | |
| 703 | + size_t len = 0; | |
| 704 | + int pid; | |
| 705 | + unsigned long long start_ticks = 0; | |
| 706 | + double started_at, age; | |
| 707 | + long rss_pages = 0; | |
| 708 | + | |
| 709 | + if (!isdigit((unsigned char)de->d_name[0])) continue; | |
| 710 | + pid = atoi(de->d_name); | |
| 711 | + if (pid <= 0) continue; | |
| 712 | + | |
| 713 | + snprintf(path, sizeof path, "%s/%s/comm", root, de->d_name); | |
| 714 | + comm[0] = '\0'; | |
| 715 | + buf = read_file_all(path, &len); | |
| 716 | + if (!buf) continue; | |
| 717 | + str_copy(comm, sizeof comm, buf); | |
| 718 | + free(buf); | |
| 719 | + str_trim(comm); | |
| 720 | + if (!comm[0]) continue; | |
| 721 | + | |
| 722 | + /* field 22 (1-based) of <pid>/stat is starttime; field 2 is "(comm)" | |
| 723 | + * and may contain spaces, so scan from the last ')' first. */ | |
| 724 | + snprintf(path, sizeof path, "%s/%s/stat", root, de->d_name); | |
| 725 | + buf = read_file_all(path, &len); | |
| 726 | + if (!buf) continue; | |
| 727 | + str_copy(statline, sizeof statline, buf); | |
| 728 | + free(buf); | |
| 729 | + { | |
| 730 | + char *rp = strrchr(statline, ')'); | |
| 731 | + int fld = 2; | |
| 732 | + char *q = rp ? rp + 1 : statline; | |
| 733 | + while (*q) { | |
| 734 | + while (*q == ' ') q++; | |
| 735 | + if (!*q) break; | |
| 736 | + fld++; | |
| 737 | + if (fld == 22) { start_ticks = strtoull(q, NULL, 10); break; } | |
| 738 | + while (*q && *q != ' ') q++; | |
| 739 | + } | |
| 740 | + } | |
| 741 | + | |
| 742 | + /* <pid>/statm field 2 is the resident set in pages. */ | |
| 743 | + snprintf(path, sizeof path, "%s/%s/statm", root, de->d_name); | |
| 744 | + buf = read_file_all(path, &len); | |
| 745 | + if (buf) { | |
| 746 | + long dummy = 0; | |
| 747 | + if (sscanf(buf, "%ld %ld", &dummy, &rss_pages) != 2) rss_pages = 0; | |
| 748 | + free(buf); | |
| 749 | + } | |
| 750 | + | |
| 751 | + started_at = (double)start_ticks / 100.0; | |
| 752 | + age = uptime_s - started_at; | |
| 753 | + if (age < 300.0) continue; | |
| 754 | + | |
| 755 | + svc_add(comm, "process (no init system)", "running", "running", pid); | |
| 756 | + { | |
| 757 | + svc_t *s = &g_svc[g_count - 1]; | |
| 758 | + s->mem = (unsigned long long)rss_pages * 4096ULL; | |
| 759 | + str_copy(s->enabled, sizeof s->enabled, "-"); | |
| 760 | + snprintf(s->since, sizeof s->since, "up %lds", (long)age); | |
| 761 | + } | |
| 762 | + } | |
| 763 | + closedir(d); | |
| 764 | + return g_count; | |
| 765 | +#endif | |
| 766 | +} | |
| 767 | + | |
| 768 | +static void collect_systemd(void) | |
| 769 | +{ | |
| 770 | + const char *mock = getenv("SERVICES_MOCK_SYSTEMCTL"); | |
| 771 | + char *buf = NULL; | |
| 772 | + size_t len = 0; | |
| 773 | + static char out[OUT_SZ]; | |
| 774 | + | |
| 775 | + g_init = INIT_SYSTEMD; | |
| 776 | + g_count = 0; | |
| 777 | + | |
| 778 | + if (mock && *mock) { | |
| 779 | + buf = read_file_all(mock, &len); | |
| 780 | + if (buf) { | |
| 781 | + const char *p = buf; | |
| 782 | + while (*p && isspace((unsigned char)*p)) p++; | |
| 783 | + if (*p == '[') parse_json_units(buf); | |
| 784 | + else parse_plain_units(buf); | |
| 785 | + free(buf); | |
| 786 | + } | |
| 787 | + } else { | |
| 788 | + if (capture("systemctl list-units --type=service --all --no-pager " | |
| 789 | + "--plain --output=json 2>/dev/null", out, sizeof out) > 0) { | |
| 790 | + const char *p = out; | |
| 791 | + while (*p && isspace((unsigned char)*p)) p++; | |
| 792 | + if (*p == '[') parse_json_units(out); | |
| 793 | + else parse_plain_units(out); | |
| 794 | + } | |
| 795 | + if (g_count == 0) { | |
| 796 | + if (capture("systemctl list-units --type=service --all --no-pager " | |
| 797 | + "--plain 2>/dev/null", out, sizeof out) > 0) | |
| 798 | + parse_plain_units(out); | |
| 799 | + } | |
| 800 | + if (g_count == 0) { | |
| 801 | + if (capture("systemctl list-unit-files --type=service --no-pager " | |
| 802 | + "--plain 2>/dev/null", out, sizeof out) > 0) | |
| 803 | + parse_plain_units(out); | |
| 804 | + } | |
| 805 | + } | |
| 806 | + | |
| 807 | + /* One enrichment pass, only when we have real systemd output. */ | |
| 808 | + if (g_count > 0) { | |
| 809 | + const char *show_mock = getenv("SERVICES_MOCK_SYSTEMCTL_SHOW"); | |
| 810 | + if (show_mock && *show_mock) { | |
| 811 | + char *sb = read_file_all(show_mock, &len); | |
| 812 | + if (sb) { apply_show(sb); free(sb); } | |
| 813 | + } else if (!mock || !*mock) { | |
| 814 | + if (capture("systemctl show --type=service --all -p Id -p MainPID " | |
| 815 | + "-p ActiveEnterTimestamp -p MemoryCurrent " | |
| 816 | + "-p UnitFileState -p ActiveState -p SubState " | |
| 817 | + "-p Description 2>/dev/null", out, sizeof out) > 0) | |
| 818 | + apply_show(out); | |
| 819 | + } | |
| 820 | + } | |
| 821 | +} | |
| 822 | + | |
| 823 | +/* ------------------------------------------------------------------ */ | |
| 824 | +/* Collection: launchd (macOS) */ | |
| 825 | +/* ------------------------------------------------------------------ */ | |
| 826 | + | |
| 827 | +#if !defined(_WIN32) | |
| 828 | +static void collect_launchd(void) | |
| 829 | +{ | |
| 830 | + const char *mock = getenv("SERVICES_MOCK_LAUNCHCTL"); | |
| 831 | + static char out[OUT_SZ]; | |
| 832 | + char *buf = NULL; | |
| 833 | + | |
| 834 | + g_init = INIT_LAUNCHD; | |
| 835 | + g_count = 0; | |
| 836 | + | |
| 837 | + if (mock && *mock) { | |
| 838 | + buf = read_file_all(mock, NULL); | |
| 839 | + if (buf) { str_copy(out, sizeof out, buf); free(buf); } | |
| 840 | + } else if (capture("launchctl list 2>/dev/null", out, sizeof out) <= 0) { | |
| 841 | + out[0] = '\0'; | |
| 842 | + } | |
| 843 | + | |
| 844 | + { | |
| 845 | + const char *p = out; | |
| 846 | + int first = 1; | |
| 847 | + while (p && *p) { | |
| 848 | + const char *nl = strchr(p, '\n'); | |
| 849 | + size_t len = nl ? (size_t)(nl - p) : strlen(p); | |
| 850 | + char line[512]; | |
| 851 | + char pid_s[32], st_s[32], label[NAME_SZ]; | |
| 852 | + int pid = 0; | |
| 853 | + | |
| 854 | + if (len >= sizeof line) len = sizeof line - 1; | |
| 855 | + memcpy(line, p, len); | |
| 856 | + line[len] = '\0'; | |
| 857 | + p = nl ? nl + 1 : p + strlen(p); | |
| 858 | + | |
| 859 | + if (first) { | |
| 860 | + first = 0; | |
| 861 | + if (strstr(line, "PID") && strstr(line, "Label")) continue; | |
| 862 | + } | |
| 863 | + pid_s[0] = st_s[0] = label[0] = '\0'; | |
| 864 | + if (sscanf(line, "%31s %31s %191[^\n]", pid_s, st_s, label) < 3) continue; | |
| 865 | + str_trim(label); | |
| 866 | + if (!label[0]) continue; | |
| 867 | + if (strcmp(pid_s, "-") != 0) pid = atoi(pid_s); | |
| 868 | + /* A job with no pid whose last exit status is non-zero failed. */ | |
| 869 | + if (pid <= 0 && strcmp(st_s, "0") != 0) | |
| 870 | + svc_add(label, "launchd job", "failed", "failed", 0); | |
| 871 | + else | |
| 872 | + svc_add(label, "launchd job", pid > 0 ? "running" : "inactive", | |
| 873 | + pid > 0 ? "running" : "exited", pid); | |
| 874 | + { | |
| 875 | + svc_t *s = &g_svc[g_count - 1]; | |
| 876 | + str_copy(s->enabled, sizeof s->enabled, "launchd"); | |
| 877 | + if (strcmp(st_s, "0") != 0 && strcmp(pid_s, "-") == 0) | |
| 878 | + snprintf(s->since, sizeof s->since, "last exit %s", st_s); | |
| 879 | + else | |
| 880 | + str_copy(s->since, sizeof s->since, "-"); | |
| 881 | + } | |
| 882 | + if (g_count >= MAX_SERVICES) break; | |
| 883 | + } | |
| 884 | + } | |
| 885 | + | |
| 886 | + /* Fill memory (and start time) from a single ps pass over the pids we did | |
| 887 | + * get. Only digits ever reach the command line here. */ | |
| 888 | + if (!mock || !*mock) { | |
| 889 | + char pids[512]; | |
| 890 | + size_t used = 0; | |
| 891 | + int i; | |
| 892 | + | |
| 893 | + pids[0] = '\0'; | |
| 894 | + for (i = 0; i < g_count; i++) { | |
| 895 | + char tmp[16]; | |
| 896 | + int n; | |
| 897 | + if (g_svc[i].pid <= 0) continue; | |
| 898 | + n = snprintf(tmp, sizeof tmp, "%s%d", used ? "," : "", g_svc[i].pid); | |
| 899 | + if (n <= 0 || used + (size_t)n + 1 >= sizeof pids) break; | |
| 900 | + memcpy(pids + used, tmp, (size_t)n); | |
| 901 | + used += (size_t)n; | |
| 902 | + pids[used] = '\0'; | |
| 903 | + } | |
| 904 | + if (used > 0) { | |
| 905 | + char cmd[640]; | |
| 906 | + snprintf(cmd, sizeof cmd, "ps -o pid=,rss=,lstart= -p %s 2>/dev/null", pids); | |
| 907 | + if (capture(cmd, out, sizeof out) > 0) { | |
| 908 | + char *line = out; | |
| 909 | + while (line && *line) { | |
| 910 | + char *nl = strchr(line, '\n'); | |
| 911 | + int pid = 0; | |
| 912 | + long rss = 0; | |
| 913 | + int off = 0; | |
| 914 | + svc_t *s; | |
| 915 | + if (nl) *nl = '\0'; | |
| 916 | + if (sscanf(line, "%d %ld %n", &pid, &rss, &off) >= 2 && pid > 0) { | |
| 917 | + for (i = 0; i < g_count; i++) { | |
| 918 | + if (g_svc[i].pid != pid) continue; | |
| 919 | + s = &g_svc[i]; | |
| 920 | + s->mem = (unsigned long long)rss * 1024ULL; | |
| 921 | + if (off > 0 && (size_t)off < strlen(line) && | |
| 922 | + strcmp(s->since, "-") == 0) { | |
| 923 | + str_copy(s->since, sizeof s->since, line + off); | |
| 924 | + str_trim(s->since); | |
| 925 | + } | |
| 926 | + break; | |
| 927 | + } | |
| 928 | + } | |
| 929 | + line = nl ? nl + 1 : NULL; | |
| 930 | + } | |
| 931 | + } | |
| 932 | + } | |
| 933 | + } | |
| 934 | +} | |
| 935 | + | |
| 936 | +#endif /* !_WIN32 */ | |
| 937 | + | |
| 938 | +/* ------------------------------------------------------------------ */ | |
| 939 | +/* Collection: Windows SCM */ | |
| 940 | +/* ------------------------------------------------------------------ */ | |
| 941 | + | |
| 942 | +#if defined(_WIN32) | |
| 943 | +static void collect_scm(void) | |
| 944 | +{ | |
| 945 | + SC_HANDLE scm; | |
| 946 | + DWORD need = 0, got = 0, resume = 0; | |
| 947 | + LPBYTE buf = NULL; | |
| 948 | + | |
| 949 | + g_init = INIT_SCM; | |
| 950 | + g_count = 0; | |
| 951 | + | |
| 952 | + scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE); | |
| 953 | + if (!scm) return; | |
| 954 | + | |
| 955 | + EnumServicesStatusExA(scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, | |
| 956 | + SERVICE_STATE_ALL, NULL, 0, &need, &got, &resume, NULL); | |
| 957 | + if (need > 0) { | |
| 958 | + buf = (LPBYTE)malloc(need); | |
| 959 | + if (buf) { | |
| 960 | + if (EnumServicesStatusExA(scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, | |
| 961 | + SERVICE_STATE_ALL, buf, need, &need, | |
| 962 | + &got, &resume, NULL)) { | |
| 963 | + LPENUM_SERVICE_STATUS_PROCESSA it = (LPENUM_SERVICE_STATUS_PROCESSA)buf; | |
| 964 | + DWORD i; | |
| 965 | + for (i = 0; i < got && g_count < MAX_SERVICES; i++) { | |
| 966 | + const char *state = "stopped"; | |
| 967 | + char sub[STATE_SZ]; | |
| 968 | + char enabled[EN_SZ] = "-"; | |
| 969 | + SC_HANDLE svc; | |
| 970 | + LPQUERY_SERVICE_CONFIGA cfg; | |
| 971 | + | |
| 972 | + switch (it[i].ServiceStatusProcess.dwCurrentState) { | |
| 973 | + case SERVICE_RUNNING: state = "running"; break; | |
| 974 | + case SERVICE_STOPPED: state = "inactive"; break; | |
| 975 | + case SERVICE_PAUSED: state = "paused"; break; | |
| 976 | + case SERVICE_START_PENDING: state = "starting"; break; | |
| 977 | + case SERVICE_STOP_PENDING: state = "stopping"; break; | |
| 978 | + default: state = "unknown"; break; | |
| 979 | + } | |
| 980 | + snprintf(sub, sizeof sub, "%lu", | |
| 981 | + (unsigned long)it[i].ServiceStatusProcess.dwCurrentState); | |
| 982 | + | |
| 983 | + svc_add(it[i].lpServiceName, it[i].lpDisplayName, state, sub, 0); | |
| 984 | + { | |
| 985 | + svc_t *s = &g_svc[g_count - 1]; | |
| 986 | + s->pid = (int)it[i].ServiceStatusProcess.dwProcessId; | |
| 987 | + svc = OpenServiceA(scm, it[i].lpServiceName, | |
| 988 | + SERVICE_QUERY_CONFIG); | |
| 989 | + if (svc) { | |
| 990 | + DWORD cneed = 0; | |
| 991 | + QueryServiceConfigA(svc, NULL, 0, &cneed); | |
| 992 | + cfg = (LPQUERY_SERVICE_CONFIGA)malloc(cneed ? cneed : 1); | |
| 993 | + if (cfg && QueryServiceConfigA(svc, cfg, cneed, &cneed)) { | |
| 994 | + switch (cfg->dwStartType) { | |
| 995 | + case SERVICE_AUTO_START: enabled[0] = 0; str_copy(enabled, sizeof enabled, "automatic"); break; | |
| 996 | + case SERVICE_DEMAND_START: str_copy(enabled, sizeof enabled, "manual"); break; | |
| 997 | + case SERVICE_DISABLED: str_copy(enabled, sizeof enabled, "disabled"); break; | |
| 998 | + case SERVICE_BOOT_START: str_copy(enabled, sizeof enabled, "boot"); break; | |
| 999 | + case SERVICE_SYSTEM_START: str_copy(enabled, sizeof enabled, "system"); break; | |
| 1000 | + default: str_copy(enabled, sizeof enabled, "-"); break; | |
| 1001 | + } | |
| 1002 | + } | |
| 1003 | + free(cfg); | |
| 1004 | + CloseServiceHandle(svc); | |
| 1005 | + } | |
| 1006 | + str_copy(s->enabled, sizeof s->enabled, enabled); | |
| 1007 | + str_copy(s->since, sizeof s->since, "-"); | |
| 1008 | + s->mem = 0; | |
| 1009 | + } | |
| 1010 | + } | |
| 1011 | + } | |
| 1012 | + free(buf); | |
| 1013 | + } | |
| 1014 | + } | |
| 1015 | + CloseServiceHandle(scm); | |
| 1016 | +} | |
| 1017 | +#endif | |
| 1018 | + | |
| 1019 | +/* ------------------------------------------------------------------ */ | |
| 1020 | +/* Collection dispatch + ordering */ | |
| 1021 | +/* ------------------------------------------------------------------ */ | |
| 1022 | + | |
| 1023 | +static int svc_failed(const svc_t *s) | |
| 1024 | +{ | |
| 1025 | + return strcmp(s->active, "failed") == 0 || | |
| 1026 | + strcmp(s->sub, "failed") == 0; | |
| 1027 | +} | |
| 1028 | + | |
| 1029 | +static int svc_running(const svc_t *s) | |
| 1030 | +{ | |
| 1031 | + return strcmp(s->active, "running") == 0 || | |
| 1032 | + strcmp(s->active, "active") == 0; | |
| 1033 | +} | |
| 1034 | + | |
| 1035 | +static int svc_cmp(const void *a, const void *b) | |
| 1036 | +{ | |
| 1037 | + const svc_t *x = (const svc_t *)a; | |
| 1038 | + const svc_t *y = (const svc_t *)b; | |
| 1039 | + int fx = svc_failed(x), fy = svc_failed(y); | |
| 1040 | + int rx = svc_running(x), ry = svc_running(y); | |
| 1041 | + | |
| 1042 | + if (fx != fy) return fy - fx; /* failed first */ | |
| 1043 | + if (rx != ry) return ry - rx; /* then running */ | |
| 1044 | + return strcmp(x->name, y->name); | |
| 1045 | +} | |
| 1046 | + | |
| 1047 | +static const char *init_name(void) | |
| 1048 | +{ | |
| 1049 | + switch (g_init) { | |
| 1050 | + case INIT_SYSTEMD: return "systemd"; | |
| 1051 | + case INIT_LAUNCHD: return "launchd"; | |
| 1052 | + case INIT_SCM: return "windows-scm"; | |
| 1053 | + default: return "none"; | |
| 1054 | + } | |
| 1055 | +} | |
| 1056 | + | |
| 1057 | +static void collect_all(void) | |
| 1058 | +{ | |
| 1059 | + const char *force = getenv("SERVICES_FORCE_INIT"); | |
| 1060 | + const char *allow = getenv("SERVICES_ALLOW_CONTROL"); | |
| 1061 | + | |
| 1062 | + g_control = (allow && *allow && strcmp(allow, "0") != 0); | |
| 1063 | + g_count = 0; | |
| 1064 | + | |
| 1065 | +#if defined(_WIN32) | |
| 1066 | + collect_scm(); | |
| 1067 | +#elif defined(__APPLE__) | |
| 1068 | + collect_launchd(); | |
| 1069 | +#else | |
| 1070 | + if (getenv("SERVICES_MOCK_LAUNCHCTL")) { | |
| 1071 | + collect_launchd(); /* fixture-driven launchd path on any host */ | |
| 1072 | + } else if (force && strcmp(force, "none") == 0) { | |
| 1073 | + g_init = INIT_NONE; | |
| 1074 | + collect_proc_daemons(); | |
| 1075 | + } else if (getenv("SERVICES_MOCK_SYSTEMCTL")) { | |
| 1076 | + collect_systemd(); | |
| 1077 | + } else if (access("/run/systemd/system", F_OK) == 0) { | |
| 1078 | + collect_systemd(); | |
| 1079 | + } else { | |
| 1080 | + g_init = INIT_NONE; | |
| 1081 | + if (collect_proc_daemons() == 0) g_count = 0; | |
| 1082 | + } | |
| 1083 | +#endif | |
| 1084 | + | |
| 1085 | + if (g_count > 1) qsort(g_svc, (size_t)g_count, sizeof(svc_t), svc_cmp); | |
| 1086 | +} | |
| 1087 | + | |
| 1088 | +/* ------------------------------------------------------------------ */ | |
| 1089 | +/* JSON output */ | |
| 1090 | +/* ------------------------------------------------------------------ */ | |
| 1091 | + | |
| 1092 | +static void mem_json(buf_t *b, unsigned long long v) | |
| 1093 | +{ | |
| 1094 | + char tmp[32]; | |
| 1095 | + if (v == 0) { buf_puts(b, "null"); return; } | |
| 1096 | + snprintf(tmp, sizeof tmp, "%llu", v); | |
| 1097 | + buf_puts(b, tmp); | |
| 1098 | +} | |
| 1099 | + | |
| 1100 | +static void emit_service(buf_t *b, const svc_t *s) | |
| 1101 | +{ | |
| 1102 | + buf_puts(b, "{\"name\":"); | |
| 1103 | + json_into(b, s->name); | |
| 1104 | + buf_puts(b, ",\"description\":"); | |
| 1105 | + json_into(b, s->desc); | |
| 1106 | + buf_puts(b, ",\"active\":"); | |
| 1107 | + json_into(b, s->active); | |
| 1108 | + buf_puts(b, ",\"sub\":"); | |
| 1109 | + json_into(b, s->sub); | |
| 1110 | + buf_puts(b, ",\"enabled\":"); | |
| 1111 | + json_into(b, s->enabled); | |
| 1112 | + buf_puts(b, ",\"pid\":"); | |
| 1113 | + { | |
| 1114 | + char tmp[32]; | |
| 1115 | + snprintf(tmp, sizeof tmp, "%d", s->pid); | |
| 1116 | + buf_puts(b, tmp); | |
| 1117 | + } | |
| 1118 | + buf_puts(b, ",\"memory_bytes\":"); | |
| 1119 | + mem_json(b, s->mem); | |
| 1120 | + buf_puts(b, ",\"since\":"); | |
| 1121 | + json_into(b, s->since); | |
| 1122 | + buf_puts(b, ",\"failed\":"); | |
| 1123 | + buf_puts(b, svc_failed(s) ? "true" : "false"); | |
| 1124 | + buf_putc(b, '}'); | |
| 1125 | +} | |
| 1126 | + | |
| 1127 | +static void print_json_header(void) | |
| 1128 | +{ | |
| 1129 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 1130 | + "Cache-Control: no-store\r\n" | |
| 1131 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1132 | +} | |
| 1133 | + | |
| 1134 | +/* ------------------------------------------------------------------ */ | |
| 1135 | +/* HTML */ | |
| 1136 | +/* ------------------------------------------------------------------ */ | |
| 1137 | + | |
| 1138 | +/* Split UI_HTML on the two control-byte placeholders and expand them into the | |
| 1139 | + * theme macros, so the page and the bot palette can never drift apart. */ | |
| 1140 | +static void emit_ui(void) | |
| 1141 | +{ | |
| 1142 | + const char *p = UI_HTML; | |
| 1143 | + | |
| 1144 | + while (*p) { | |
| 1145 | + if (*p == '\001') { | |
| 1146 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS | |
| 1147 | + ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);" | |
| 1148 | + "--ac:var(--blue);--sf:var(--bg-card);--sf2:var(--surface-2)}" | |
| 1149 | + "</style>", stdout); | |
| 1150 | + p++; | |
| 1151 | + } else if (*p == '\002') { | |
| 1152 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | |
| 1153 | + p++; | |
| 1154 | + } else { | |
| 1155 | + putchar(*p++); | |
| 1156 | + } | |
| 1157 | + } | |
| 1158 | +} | |
| 1159 | + | |
| 1160 | +static int mode_html(void) | |
| 1161 | +{ | |
| 1162 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 1163 | + "Cache-Control: no-store\r\n" | |
| 1164 | + "X-Content-Type-Options: nosniff\r\n" | |
| 1165 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | |
| 1166 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | |
| 1167 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | |
| 1168 | + emit_ui(); | |
| 1169 | + return 0; | |
| 1170 | +} | |
| 1171 | + | |
| 1172 | +/* ------------------------------------------------------------------ */ | |
| 1173 | +/* Control */ | |
| 1174 | +/* ------------------------------------------------------------------ */ | |
| 1175 | + | |
| 1176 | +static int do_control(const char *unit, const char *op) | |
| 1177 | +{ | |
| 1178 | + if (!valid_unit(unit)) return 400; | |
| 1179 | + if (!g_control) return 403; | |
| 1180 | + if (strcmp(op, "start") != 0 && strcmp(op, "stop") != 0 && | |
| 1181 | + strcmp(op, "restart") != 0) | |
| 1182 | + return 400; | |
| 1183 | + | |
| 1184 | + { | |
| 1185 | + const char *logp = getenv("SERVICES_MOCK_SYSTEMCTL_LOG"); | |
| 1186 | + if (logp && *logp) { | |
| 1187 | + FILE *f = fopen(logp, "a"); | |
| 1188 | + if (f) { | |
| 1189 | + fprintf(f, "systemctl %s %s\n", op, unit); | |
| 1190 | + fclose(f); | |
| 1191 | + } | |
| 1192 | + return 0; | |
| 1193 | + } | |
| 1194 | + } | |
| 1195 | + | |
| 1196 | +#if defined(_WIN32) | |
| 1197 | + { | |
| 1198 | + SC_HANDLE scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_CONNECT); | |
| 1199 | + SC_HANDLE svc; | |
| 1200 | + int rc = 500; | |
| 1201 | + if (!scm) return 500; | |
| 1202 | + svc = OpenServiceA(scm, unit, | |
| 1203 | + strcmp(op, "stop") == 0 ? SERVICE_STOP | |
| 1204 | + : (SERVICE_START | SERVICE_STOP)); | |
| 1205 | + if (!svc) { CloseServiceHandle(scm); return 404; } | |
| 1206 | + if (strcmp(op, "start") == 0) { | |
| 1207 | + if (StartServiceA(svc, 0, NULL)) rc = 0; | |
| 1208 | + else if (GetLastError() == ERROR_SERVICE_ALREADY_RUNNING) rc = 0; | |
| 1209 | + } else { | |
| 1210 | + SERVICE_STATUS st; | |
| 1211 | + if (ControlService(svc, SERVICE_CONTROL_STOP, &st)) rc = 0; | |
| 1212 | + else if (GetLastError() == ERROR_SERVICE_NOT_ACTIVE) rc = 0; | |
| 1213 | + } | |
| 1214 | + CloseServiceHandle(svc); | |
| 1215 | + CloseServiceHandle(scm); | |
| 1216 | + return rc; | |
| 1217 | + } | |
| 1218 | +#elif defined(__APPLE__) | |
| 1219 | + { | |
| 1220 | + char *argv[4]; | |
| 1221 | + int rc; | |
| 1222 | + argv[0] = (char *)"launchctl"; | |
| 1223 | + argv[1] = (char *)(strcmp(op, "stop") == 0 ? "stop" : "kickstart"); | |
| 1224 | + argv[2] = (char *)("-k"); | |
| 1225 | + argv[3] = (char *)unit; | |
| 1226 | + if (strcmp(op, "stop") == 0) { argv[2] = (char *)unit; argv[3] = NULL; } | |
| 1227 | + rc = run_argv(argv); | |
| 1228 | + return rc == 0 ? 0 : 500; | |
| 1229 | + } | |
| 1230 | +#else | |
| 1231 | + { | |
| 1232 | + char *argv[4]; | |
| 1233 | + int rc; | |
| 1234 | + argv[0] = (char *)"systemctl"; | |
| 1235 | + argv[1] = (char *)op; | |
| 1236 | + argv[2] = (char *)unit; | |
| 1237 | + argv[3] = NULL; | |
| 1238 | + rc = run_argv(argv); | |
| 1239 | + return rc == 0 ? 0 : 500; | |
| 1240 | + } | |
| 1241 | +#endif | |
| 1242 | +} | |
| 1243 | + | |
| 1244 | +/* ------------------------------------------------------------------ */ | |
| 1245 | +/* API dispatch */ | |
| 1246 | +/* ------------------------------------------------------------------ */ | |
| 1247 | + | |
| 1248 | +static void err_json(int code, const char *status, const char *msg) | |
| 1249 | +{ | |
| 1250 | + printf("Status: %d %s\r\n", code, status); | |
| 1251 | + print_json_header(); | |
| 1252 | + printf("{\"ok\":false,\"error\":\"%s\"}\n", msg); | |
| 1253 | +} | |
| 1254 | + | |
| 1255 | +static int mode_json(const char *qs) | |
| 1256 | +{ | |
| 1257 | + char action[64]; | |
| 1258 | + char filter[32]; | |
| 1259 | + char unit[256]; | |
| 1260 | + char op[32]; | |
| 1261 | + | |
| 1262 | + action[0] = filter[0] = unit[0] = op[0] = '\0'; | |
| 1263 | + get_query_val(qs, "action", action, sizeof action); | |
| 1264 | + get_query_val(qs, "filter", filter, sizeof filter); | |
| 1265 | + get_query_val(qs, "unit", unit, sizeof unit); | |
| 1266 | + get_query_val(qs, "op", op, sizeof op); | |
| 1267 | + | |
| 1268 | + if (!action[0]) str_copy(action, sizeof action, "list"); | |
| 1269 | + | |
| 1270 | + collect_all(); | |
| 1271 | + | |
| 1272 | + if (strcmp(action, "list") == 0) { | |
| 1273 | + buf_t b = { 0 }; | |
| 1274 | + int i, shown = 0; | |
| 1275 | + int running = 0, failed = 0, inactive = 0; | |
| 1276 | + | |
| 1277 | + for (i = 0; i < g_count; i++) { | |
| 1278 | + if (svc_running(&g_svc[i])) running++; | |
| 1279 | + else if (svc_failed(&g_svc[i])) failed++; | |
| 1280 | + else inactive++; | |
| 1281 | + } | |
| 1282 | + | |
| 1283 | + print_json_header(); | |
| 1284 | + buf_puts(&b, "{\"ok\":true,\"init_system\":"); | |
| 1285 | + json_into(&b, init_name()); | |
| 1286 | + buf_puts(&b, ",\"control_enabled\":"); | |
| 1287 | + buf_puts(&b, g_control ? "true" : "false"); | |
| 1288 | + { | |
| 1289 | + buf_t body; | |
| 1290 | + char tmp[32]; | |
| 1291 | + memset(&body, 0, sizeof body); | |
| 1292 | + for (i = 0; i < g_count; i++) { | |
| 1293 | + const svc_t *s = &g_svc[i]; | |
| 1294 | + int keep = 1; | |
| 1295 | + if (filter[0] && strcmp(filter, "all") != 0) { | |
| 1296 | + if (strcmp(filter, "failed") == 0) keep = svc_failed(s); | |
| 1297 | + else if (strcmp(filter, "running") == 0) keep = svc_running(s); | |
| 1298 | + else if (strcmp(filter, "inactive") == 0) | |
| 1299 | + keep = !svc_running(s) && !svc_failed(s); | |
| 1300 | + } | |
| 1301 | + if (!keep) continue; | |
| 1302 | + if (shown) buf_putc(&body, ','); | |
| 1303 | + emit_service(&body, s); | |
| 1304 | + shown++; | |
| 1305 | + } | |
| 1306 | + buf_puts(&b, ",\"count\":"); | |
| 1307 | + snprintf(tmp, sizeof tmp, "%d", shown); | |
| 1308 | + buf_puts(&b, tmp); | |
| 1309 | + buf_puts(&b, ",\"summary\":{\"running\":"); | |
| 1310 | + snprintf(tmp, sizeof tmp, "%d", running); buf_puts(&b, tmp); | |
| 1311 | + buf_puts(&b, ",\"failed\":"); | |
| 1312 | + snprintf(tmp, sizeof tmp, "%d", failed); buf_puts(&b, tmp); | |
| 1313 | + buf_puts(&b, ",\"inactive\":"); | |
| 1314 | + snprintf(tmp, sizeof tmp, "%d", inactive); buf_puts(&b, tmp); | |
| 1315 | + buf_puts(&b, "},\"services\":["); | |
| 1316 | + buf_add(&b, buf_str(&body), body.n); | |
| 1317 | + buf_puts(&b, "]}\n"); | |
| 1318 | + buf_free(&body); | |
| 1319 | + } | |
| 1320 | + fwrite(buf_str(&b), 1, b.n, stdout); | |
| 1321 | + buf_free(&b); | |
| 1322 | + return 0; | |
| 1323 | + } | |
| 1324 | + | |
| 1325 | + if (strcmp(action, "show") == 0) { | |
| 1326 | + svc_t *s; | |
| 1327 | + buf_t b = { 0 }; | |
| 1328 | + | |
| 1329 | + if (!unit[0]) { err_json(400, "Bad Request", "missing unit"); return 0; } | |
| 1330 | + if (!valid_unit(unit)) { err_json(400, "Bad Request", "invalid unit"); return 0; } | |
| 1331 | + s = svc_find(unit); | |
| 1332 | + if (!s) { err_json(404, "Not Found", "service not found"); return 0; } | |
| 1333 | + | |
| 1334 | + print_json_header(); | |
| 1335 | + buf_puts(&b, "{\"ok\":true,\"init_system\":"); | |
| 1336 | + json_into(&b, init_name()); | |
| 1337 | + buf_puts(&b, ",\"control_enabled\":"); | |
| 1338 | + buf_puts(&b, g_control ? "true" : "false"); | |
| 1339 | + buf_puts(&b, ",\"service\":"); | |
| 1340 | + emit_service(&b, s); | |
| 1341 | + buf_puts(&b, "}\n"); | |
| 1342 | + fwrite(buf_str(&b), 1, b.n, stdout); | |
| 1343 | + buf_free(&b); | |
| 1344 | + return 0; | |
| 1345 | + } | |
| 1346 | + | |
| 1347 | + if (strcmp(action, "control") == 0) { | |
| 1348 | + int rc; | |
| 1349 | + | |
| 1350 | + /* Refuse by capability before by method: a node that never opted into | |
| 1351 | + * control must not advertise a 405 that implies the route works. */ | |
| 1352 | + if (!g_control) { err_json(403, "Forbidden", "control_disabled"); return 0; } | |
| 1353 | + if (!is_post_request()) { | |
| 1354 | + err_json(405, "Method Not Allowed", "control requires POST"); | |
| 1355 | + return 0; | |
| 1356 | + } | |
| 1357 | + if (!valid_unit(unit)) { err_json(400, "Bad Request", "invalid unit"); return 0; } | |
| 1358 | + if (strcmp(op, "start") != 0 && strcmp(op, "stop") != 0 && | |
| 1359 | + strcmp(op, "restart") != 0) { | |
| 1360 | + err_json(400, "Bad Request", "op must be start|stop|restart"); | |
| 1361 | + return 0; | |
| 1362 | + } | |
| 1363 | + rc = do_control(unit, op); | |
| 1364 | + if (rc == 403) { err_json(403, "Forbidden", "control_disabled"); return 0; } | |
| 1365 | + if (rc == 400) { err_json(400, "Bad Request", "invalid request"); return 0; } | |
| 1366 | + if (rc == 404) { err_json(404, "Not Found", "service not found"); return 0; } | |
| 1367 | + if (rc != 0) { err_json(500, "Internal Server Error", "control failed"); return 0; } | |
| 1368 | + | |
| 1369 | + print_json_header(); | |
| 1370 | + printf("{\"ok\":true,\"unit\":\"%s\",\"op\":\"%s\"," | |
| 1371 | + "\"control_enabled\":true,\"init_system\":\"%s\"}\n", | |
| 1372 | + unit, op, init_name()); | |
| 1373 | + return 0; | |
| 1374 | + } | |
| 1375 | + | |
| 1376 | + err_json(400, "Bad Request", "unknown action"); | |
| 1377 | + return 0; | |
| 1378 | +} | |
| 1379 | + | |
| 1380 | +static int mode_meta(void) | |
| 1381 | +{ | |
| 1382 | + printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC); | |
| 1383 | + return 0; | |
| 1384 | +} | |
| 1385 | + | |
| 1386 | +int main(int argc, char **argv) | |
| 1387 | +{ | |
| 1388 | + const char *qs; | |
| 1389 | + | |
| 1390 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || | |
| 1391 | + (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) | |
| 1392 | + return mode_meta(); | |
| 1393 | + | |
| 1394 | + if (argc > 1 && strcmp(argv[1], "--version") == 0) { | |
| 1395 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | |
| 1396 | + return 0; | |
| 1397 | + } | |
| 1398 | + | |
| 1399 | + require_node_auth(); | |
| 1400 | + | |
| 1401 | + qs = getenv("QUERY_STRING"); | |
| 1402 | + if (!qs) qs = ""; | |
| 1403 | + | |
| 1404 | + if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) | |
| 1405 | + return mode_json(qs); | |
| 1406 | + | |
| 1407 | + return mode_html(); | |
| 1408 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..4b636d4 | ||
| --- /dev/null | ||
| +++ b/src/ui.html | ||
| @@ -0,0 +1,431 @@ | ||
| 1 | +<!DOCTYPE html> | |
| 2 | +<html lang="en"><head><meta charset="utf-8"> | |
| 3 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | |
| 4 | +<title>services</title> | |
| 5 | +<!--TOKENS--> | |
| 6 | +<style> | |
| 7 | +*{box-sizing:border-box} | |
| 8 | +html,body{margin:0;min-height:100%} | |
| 9 | +body{background:var(--bg);color:var(--tx,var(--text));font-family:var(--font); | |
| 10 | + font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased} | |
| 11 | +.wrap{max-width:1180px;margin:0 auto;padding:18px 18px 40px} | |
| 12 | +.top{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px} | |
| 13 | +.brand{font-size:11px;font-weight:700;letter-spacing:.09em;text-transform:uppercase; | |
| 14 | + color:var(--mu,var(--text-2))} | |
| 15 | +.title{font-size:19px;font-weight:680;margin:0;letter-spacing:-.01em} | |
| 16 | +.sp{flex:1 1 auto} | |
| 17 | +.pill{font-size:11px;font-weight:600;padding:3px 9px;border-radius:999px; | |
| 18 | + background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2)); | |
| 19 | + border:1px solid var(--ln,var(--line));white-space:nowrap} | |
| 20 | +.icon-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px; | |
| 21 | + background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line)); | |
| 22 | + color:var(--text);border-radius:9px;height:30px;padding:0 11px;cursor:pointer; | |
| 23 | + font-family:inherit;font-size:12px;font-weight:600} | |
| 24 | +.icon-btn:hover{background:var(--surface-hover);border-color:var(--line-2)} | |
| 25 | +.icon-btn:active{transform:scale(.97)} | |
| 26 | +.icon-btn svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.9; | |
| 27 | + stroke-linecap:round;stroke-linejoin:round} | |
| 28 | + | |
| 29 | +.chips{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px; | |
| 30 | + margin-bottom:14px} | |
| 31 | +.chip{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line)); | |
| 32 | + border-radius:12px;padding:11px 13px;cursor:pointer;font-family:inherit; | |
| 33 | + text-align:left;color:var(--text)} | |
| 34 | +.chip:hover{border-color:var(--line-2)} | |
| 35 | +.chip.sel{box-shadow:inset 0 0 0 1.5px var(--ac,var(--blue))} | |
| 36 | +.chip .k{display:flex;align-items:center;gap:6px;font-size:10.5px;font-weight:700; | |
| 37 | + letter-spacing:.07em;text-transform:uppercase;color:var(--mu,var(--text-2))} | |
| 38 | +.chip .k svg{width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:2; | |
| 39 | + stroke-linecap:round;stroke-linejoin:round} | |
| 40 | +.chip .v{font-family:var(--mono);font-size:23px;font-weight:700;margin-top:3px; | |
| 41 | + letter-spacing:-.02em} | |
| 42 | +.chip.ok .v{color:var(--green)} | |
| 43 | +.chip.bad .v{color:var(--red)} | |
| 44 | +.chip.none .v{color:var(--mu,var(--text-2))} | |
| 45 | + | |
| 46 | +.bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:10px} | |
| 47 | +.search{flex:1 1 240px;min-width:0;padding:9px 12px;border-radius:10px; | |
| 48 | + border:1px solid var(--ln,var(--line));background:var(--input-bg);color:var(--text); | |
| 49 | + font-family:inherit;font-size:13px} | |
| 50 | +.search:focus{outline:2px solid var(--ac,var(--blue));outline-offset:-1px} | |
| 51 | +select{padding:9px 11px;border-radius:10px;border:1px solid var(--ln,var(--line)); | |
| 52 | + background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px} | |
| 53 | + | |
| 54 | +.panel{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line)); | |
| 55 | + border-radius:14px;overflow:hidden} | |
| 56 | +.tb{width:100%;overflow-x:auto} | |
| 57 | +table{width:100%;border-collapse:collapse;font-size:13px} | |
| 58 | +th{text-align:left;font-size:10.5px;letter-spacing:.07em;text-transform:uppercase; | |
| 59 | + color:var(--mu,var(--text-2));font-weight:700;padding:9px 12px; | |
| 60 | + border-bottom:1px solid var(--ln,var(--line));white-space:nowrap; | |
| 61 | + background:var(--sf2,var(--surface-2))} | |
| 62 | +td{padding:9px 12px;border-bottom:1px solid var(--ln,var(--line)); | |
| 63 | + vertical-align:middle;white-space:nowrap} | |
| 64 | +tr.row{cursor:pointer} | |
| 65 | +tr.row:hover td{background:var(--surface-hover)} | |
| 66 | +tr.row:last-child td{border-bottom:0} | |
| 67 | +tr.row.sel td{background:var(--sf2,var(--surface-2))} | |
| 68 | +.mo{font-family:var(--mono);font-size:12.5px} | |
| 69 | +.name{font-weight:600;max-width:340px;overflow:hidden;text-overflow:ellipsis} | |
| 70 | +.desc{font-size:11.5px;color:var(--mu,var(--text-2));max-width:340px; | |
| 71 | + overflow:hidden;text-overflow:ellipsis;margin-top:1px} | |
| 72 | +.tag{font-size:10px;font-weight:700;padding:2px 8px;border-radius:6px; | |
| 73 | + white-space:nowrap;letter-spacing:.03em} | |
| 74 | +.t-run{background:rgba(48,209,88,.16);color:var(--green)} | |
| 75 | +.t-fail{background:rgba(255,69,58,.16);color:var(--red)} | |
| 76 | +.t-off{background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2)); | |
| 77 | + border:1px solid var(--ln,var(--line))} | |
| 78 | +.t-warn{background:rgba(255,159,10,.16);color:var(--orange)} | |
| 79 | +.dot{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:6px; | |
| 80 | + vertical-align:1px} | |
| 81 | +.d-run{background:var(--green)}.d-fail{background:var(--red)} | |
| 82 | +.d-off{background:var(--gray)}.d-warn{background:var(--orange)} | |
| 83 | +.empty{padding:26px 14px;text-align:center;color:var(--mu,var(--text-2));font-size:13px} | |
| 84 | +.hide{display:none!important} | |
| 85 | + | |
| 86 | +/* detail drawer */ | |
| 87 | +.scrim{position:fixed;inset:0;background:rgba(0,0,0,.38);opacity:0;pointer-events:none; | |
| 88 | + transition:opacity .18s var(--ease);z-index:40} | |
| 89 | +.scrim.open{opacity:1;pointer-events:auto} | |
| 90 | +.drawer{position:fixed;top:0;right:0;bottom:0;width:min(430px,100%);z-index:41; | |
| 91 | + background:var(--bg-2,var(--bg-card));border-left:1px solid var(--ln,var(--line)); | |
| 92 | + box-shadow:var(--shadow-lg);transform:translateX(102%); | |
| 93 | + transition:transform .22s var(--ease);display:flex;flex-direction:column; | |
| 94 | + max-width:100%} | |
| 95 | +.drawer.open{transform:none} | |
| 96 | +.dh{display:flex;align-items:flex-start;gap:10px;padding:16px 16px 12px; | |
| 97 | + border-bottom:1px solid var(--ln,var(--line))} | |
| 98 | +.dh .t{flex:1 1 auto;min-width:0} | |
| 99 | +.dh .n{font-size:15px;font-weight:680;word-break:break-all} | |
| 100 | +.dh .s{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:3px; | |
| 101 | + word-break:break-word} | |
| 102 | +.dbody{flex:1 1 auto;overflow-y:auto;padding:14px 16px 24px} | |
| 103 | +.kv{display:grid;grid-template-columns:110px minmax(0,1fr);gap:8px 12px; | |
| 104 | + font-size:12.5px;margin-bottom:16px} | |
| 105 | +.kv .k{color:var(--mu,var(--text-2))} | |
| 106 | +.kv .v{font-family:var(--mono);word-break:break-all} | |
| 107 | +.ctl{display:flex;gap:8px;flex-wrap:wrap;border-top:1px solid var(--ln,var(--line)); | |
| 108 | + padding-top:14px;margin-top:4px} | |
| 109 | +.btn{background:var(--ac,var(--blue));color:#fff;border:0;border-radius:999px; | |
| 110 | + padding:8px 16px;font-weight:650;font-size:12.5px;cursor:pointer;font-family:inherit} | |
| 111 | +.btn:active{transform:scale(.98)} | |
| 112 | +.btn.gh{background:transparent;color:var(--text);border:1px solid var(--ln,var(--line))} | |
| 113 | +.btn.warn{background:var(--orange)} | |
| 114 | +.btn.bad{background:var(--red)} | |
| 115 | +.note{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:10px} | |
| 116 | +.out{margin-top:12px;padding:10px 12px;border-radius:10px;font-size:12.5px; | |
| 117 | + background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line)); | |
| 118 | + word-break:break-word} | |
| 119 | +.out.err{color:var(--red);border-color:rgba(255,69,58,.4)} | |
| 120 | +.out.ok{color:var(--green);border-color:rgba(48,209,88,.35)} | |
| 121 | + | |
| 122 | +@media(max-width:860px){ | |
| 123 | + .wrap{padding:14px 12px 32px} | |
| 124 | + .name,.desc{max-width:200px} | |
| 125 | + th.h-opt,td.h-opt{display:none} | |
| 126 | +} | |
| 127 | +@media(max-width:600px){ | |
| 128 | + .wrap{padding:12px 10px 28px} | |
| 129 | + .title{font-size:17px} | |
| 130 | + .chips{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} | |
| 131 | + .chip .v{font-size:20px} | |
| 132 | + .name,.desc{max-width:150px} | |
| 133 | + th.h-since,td.h-since{display:none} | |
| 134 | + .drawer{width:100%} | |
| 135 | +} | |
| 136 | +</style></head><body> | |
| 137 | +<div class="wrap"> | |
| 138 | + <div class="top"> | |
| 139 | + <div> | |
| 140 | + <div class="brand">SCORPIOX BOT</div> | |
| 141 | + <h1 class="title">Services</h1> | |
| 142 | + </div> | |
| 143 | + <span class="sp"></span> | |
| 144 | + <span class="pill" id="initPill">init: —</span> | |
| 145 | + <button class="icon-btn embed-hide" id="btnRefresh" type="button" title="Reload"> | |
| 146 | + <svg viewBox="0 0 24 24"><path d="M20 12a8 8 0 1 1-2.3-5.7"/><path d="M20 4v5h-5"/></svg> | |
| 147 | + Refresh | |
| 148 | + </button> | |
| 149 | + <button class="icon-btn embed-hide" id="btnTheme" type="button" title="Toggle appearance"> | |
| 150 | + <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4.2"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.4 1.4M17.6 17.6L19 19M19 5l-1.4 1.4M6.4 17.6L5 19"/></svg> | |
| 151 | + </button> | |
| 152 | + </div> | |
| 153 | + | |
| 154 | + <div class="chips"> | |
| 155 | + <button class="chip" id="cAll" type="button"><div class="k">All</div><div class="v" id="vAll">—</div></button> | |
| 156 | + <button class="chip ok" id="cRun" type="button"><div class="k"><span class="dot d-run"></span>Running</div><div class="v" id="vRun">—</div></button> | |
| 157 | + <button class="chip bad" id="cFail" type="button"><div class="k"><span class="dot d-fail"></span>Failed</div><div class="v" id="vFail">—</div></button> | |
| 158 | + <button class="chip none" id="cOff" type="button"><div class="k"><span class="dot d-off"></span>Inactive</div><div class="v" id="vOff">—</div></button> | |
| 159 | + </div> | |
| 160 | + | |
| 161 | + <div class="bar"> | |
| 162 | + <input class="search" id="q" type="search" placeholder="Search name or description" autocomplete="off" spellcheck="false"> | |
| 163 | + <select id="sort" title="Sort"> | |
| 164 | + <option value="failed">Sort: failed first</option> | |
| 165 | + <option value="name">Sort: name</option> | |
| 166 | + <option value="state">Sort: state</option> | |
| 167 | + </select> | |
| 168 | + </div> | |
| 169 | + | |
| 170 | + <div class="panel"> | |
| 171 | + <div class="tb"> | |
| 172 | + <table> | |
| 173 | + <thead><tr> | |
| 174 | + <th>Service</th> | |
| 175 | + <th>State</th> | |
| 176 | + <th class="h-opt">Enabled</th> | |
| 177 | + <th class="h-opt">PID</th> | |
| 178 | + <th class="h-opt">Memory</th> | |
| 179 | + <th class="h-since">Since</th> | |
| 180 | + </tr></thead> | |
| 181 | + <tbody id="rows"></tbody> | |
| 182 | + </table> | |
| 183 | + </div> | |
| 184 | + <div id="empty" class="empty hide">No services matched this filter.</div> | |
| 185 | + </div> | |
| 186 | +</div> | |
| 187 | + | |
| 188 | +<div class="scrim" id="scrim"></div> | |
| 189 | +<aside class="drawer" id="drawer" aria-hidden="true"> | |
| 190 | + <div class="dh"> | |
| 191 | + <div class="t"><div class="n" id="dName">—</div><div class="s" id="dDesc"></div></div> | |
| 192 | + <button class="icon-btn" id="dClose" type="button" title="Close"> | |
| 193 | + <svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6L6 18"/></svg> | |
| 194 | + </button> | |
| 195 | + </div> | |
| 196 | + <div class="dbody"> | |
| 197 | + <div class="kv"> | |
| 198 | + <div class="k">State</div><div class="v" id="dState">—</div> | |
| 199 | + <div class="k">Sub-state</div><div class="v" id="dSub">—</div> | |
| 200 | + <div class="k">Enabled</div><div class="v" id="dEnabled">—</div> | |
| 201 | + <div class="k">PID</div><div class="v" id="dPid">—</div> | |
| 202 | + <div class="k">Memory</div><div class="v" id="dMem">—</div> | |
| 203 | + <div class="k">Since</div><div class="v" id="dSince">—</div> | |
| 204 | + </div> | |
| 205 | + <div class="ctl hide" id="dCtl"> | |
| 206 | + <button class="btn" id="opStart" type="button">Start</button> | |
| 207 | + <button class="btn warn" id="opRestart" type="button">Restart</button> | |
| 208 | + <button class="btn bad" id="opStop" type="button">Stop</button> | |
| 209 | + </div> | |
| 210 | + <div class="note hide" id="dNote"></div> | |
| 211 | + <div class="out hide" id="dOut"></div> | |
| 212 | + </div> | |
| 213 | +</aside> | |
| 214 | + | |
| 215 | +<script> | |
| 216 | +(function(){ | |
| 217 | +"use strict"; | |
| 218 | +var q=new URLSearchParams(location.search); | |
| 219 | +var node=q.get('node')||''; | |
| 220 | +var sid=q.get('id')||''; | |
| 221 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | |
| 222 | + localStorage.getItem('bot_active_pwd')||''; | |
| 223 | +var HUB=q.get('plugin')||''; | |
| 224 | + | |
| 225 | +/* Two call routes. Through the hub -> call the hub proxy back. Opened directly | |
| 226 | + * on the node -> the plugin itself is the route. Calling /plugins?plugin= on the | |
| 227 | + * node returns the discovery list, not this plugin. */ | |
| 228 | +function api(action,extra,method){ | |
| 229 | + var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_services')+ | |
| 230 | + '?action='+encodeURIComponent(action)+(extra?('&'+extra):'')+ | |
| 231 | + (node?'&node='+encodeURIComponent(node):'')+ | |
| 232 | + (sid?'&id='+encodeURIComponent(sid):'')+ | |
| 233 | + (pwd?'&pwd='+encodeURIComponent(pwd):''); | |
| 234 | + return fetch(u,{method:method||'GET',headers:pwd?{'X-Bot-Password':pwd}:{}}) | |
| 235 | + .then(function(r){return r.json();}); | |
| 236 | +} | |
| 237 | +function $(id){return document.getElementById(id);} | |
| 238 | +function esc(v){return String(v==null?'':v).replace(/[&<>"']/g,function(c){ | |
| 239 | + return({'&':'&','<':'<','>':'>','"':'"',"'":'''})[c];});} | |
| 240 | +function bytes(n){ | |
| 241 | + if(n==null||n===0) return '—'; | |
| 242 | + var u=['B','KiB','MiB','GiB','TiB'],i=0,v=n; | |
| 243 | + while(v>=1024&&i<u.length-1){v/=1024;i++;} | |
| 244 | + return (v>=100?Math.round(v):(Math.round(v*10)/10))+' '+u[i]; | |
| 245 | +} | |
| 246 | +var DATA=[],CTL=false,FILTER='',SORT='failed',SEL=null; | |
| 247 | + | |
| 248 | +function stateCls(s){ | |
| 249 | + if(s.failed||s.active==='failed') return 'fail'; | |
| 250 | + if(s.active==='running'||s.active==='active'||s.sub==='running') return 'run'; | |
| 251 | + if(s.active==='paused'||s.active==='starting'||s.active==='stopping') return 'warn'; | |
| 252 | + return 'off'; | |
| 253 | +} | |
| 254 | +function stateLabel(s){ | |
| 255 | + var c=stateCls(s); | |
| 256 | + if(c==='run') return 'running'; | |
| 257 | + if(c==='fail') return 'failed'; | |
| 258 | + if(c==='warn') return s.active||'pending'; | |
| 259 | + return s.active==='inactive'?'inactive':(s.active||'inactive'); | |
| 260 | +} | |
| 261 | +/* unused helper removed: stateLabel(s) already returns the visible label */ | |
| 262 | + | |
| 263 | +function visible(){ | |
| 264 | + var f=FILTER, needle=($('q').value||'').toLowerCase(); | |
| 265 | + var out=DATA.filter(function(s){ | |
| 266 | + if(f==='running'&&stateCls(s)!=='run') return false; | |
| 267 | + if(f==='failed'&&stateCls(s)!=='fail') return false; | |
| 268 | + if(f==='inactive'&&stateCls(s)!=='off') return false; | |
| 269 | + if(needle){ | |
| 270 | + var hay=(s.name+' '+(s.description||'')).toLowerCase(); | |
| 271 | + if(hay.indexOf(needle)<0) return false; | |
| 272 | + } | |
| 273 | + return true; | |
| 274 | + }); | |
| 275 | + if(SORT==='name') out.sort(function(a,b){return a.name<b.name?-1:a.name>b.name?1:0;}); | |
| 276 | + else if(SORT==='state') out.sort(function(a,b){ | |
| 277 | + var x=stateCls(a),y=stateCls(b); | |
| 278 | + if(x!==y) return x<y?-1:1; | |
| 279 | + return a.name<b.name?-1:1;}); | |
| 280 | + return out; | |
| 281 | +} | |
| 282 | + | |
| 283 | +function render(){ | |
| 284 | + var rows=visible(); | |
| 285 | + var h=''; | |
| 286 | + for(var i=0;i<rows.length;i++){ | |
| 287 | + var s=rows[i],c=stateCls(s); | |
| 288 | + h+='<tr class="row'+(SEL&&SEL===s.name?' sel':'')+'" data-n="'+esc(s.name)+'">'+ | |
| 289 | + '<td><div class="name" title="'+esc(s.name)+'">'+esc(s.name)+'</div>'+ | |
| 290 | + (s.description?'<div class="desc" title="'+esc(s.description)+'">'+esc(s.description)+'</div>':'')+ | |
| 291 | + '</td>'+ | |
| 292 | + '<td><span class="tag t-'+c+'"><span class="dot d-'+c+'"></span>'+ | |
| 293 | + esc(stateLabel(s))+'</span></td>'+ | |
| 294 | + '<td class="mo h-opt">'+esc(s.enabled||'-')+'</td>'+ | |
| 295 | + '<td class="mo h-opt">'+(s.pid>0?esc(s.pid):'—')+'</td>'+ | |
| 296 | + '<td class="mo h-opt">'+bytes(s.memory_bytes)+'</td>'+ | |
| 297 | + '<td class="mo h-since">'+esc(s.since||'—')+'</td></tr>'; | |
| 298 | + } | |
| 299 | + $('rows').innerHTML=h; | |
| 300 | + $('empty').className=rows.length?'empty hide':'empty'; | |
| 301 | + var trs=$('rows').querySelectorAll('tr.row'); | |
| 302 | + for(var k=0;k<trs.length;k++){ | |
| 303 | + trs[k].onclick=function(){open(this.getAttribute('data-n'));}; | |
| 304 | + } | |
| 305 | +} | |
| 306 | + | |
| 307 | +function load(){ | |
| 308 | + return api('list','filter=all').then(function(d){ | |
| 309 | + if(!d||!d.ok){ throw new Error((d&&d.error)||'load failed'); } | |
| 310 | + DATA=d.services||[]; | |
| 311 | + CTL=!!d.control_enabled; | |
| 312 | + var sum=d.summary||{}; | |
| 313 | + $('vAll').textContent=DATA.length; | |
| 314 | + $('vRun').textContent=sum.running||0; | |
| 315 | + $('vFail').textContent=sum.failed||0; | |
| 316 | + $('vOff').textContent=sum.inactive||0; | |
| 317 | + $('initPill').textContent='init: '+(d.init_system||'unknown')+ | |
| 318 | + (CTL?' · control on':' · read-only'); | |
| 319 | + render(); | |
| 320 | + }); | |
| 321 | +} | |
| 322 | + | |
| 323 | +function open(name){ | |
| 324 | + var s=null; | |
| 325 | + for(var i=0;i<DATA.length;i++) if(DATA[i].name===name){s=DATA[i];break;} | |
| 326 | + if(!s) return; | |
| 327 | + SEL=name; | |
| 328 | + $('dName').textContent=s.name; | |
| 329 | + $('dDesc').textContent=s.description||''; | |
| 330 | + $('dState').textContent=stateLabel(s); | |
| 331 | + $('dSub').textContent=s.sub||'—'; | |
| 332 | + $('dEnabled').textContent=s.enabled||'-'; | |
| 333 | + $('dPid').textContent=s.pid>0?s.pid:'—'; | |
| 334 | + $('dMem').textContent=bytes(s.memory_bytes); | |
| 335 | + $('dSince').textContent=s.since||'—'; | |
| 336 | + $('dOut').className='out hide'; | |
| 337 | + $('dOut').textContent=''; | |
| 338 | + if(CTL){ | |
| 339 | + $('dCtl').className='ctl'; | |
| 340 | + $('dNote').className='note'; | |
| 341 | + $('dNote').textContent='Control is enabled on this node (SERVICES_ALLOW_CONTROL=1). Every action is sent as a separate argv element, never through a shell.'; | |
| 342 | + }else{ | |
| 343 | + $('dCtl').className='ctl hide'; | |
| 344 | + $('dNote').className='note'; | |
| 345 | + $('dNote').textContent='Read-only: set SERVICES_ALLOW_CONTROL=1 in this node\'s plugin environment to enable start, stop and restart.'; | |
| 346 | + } | |
| 347 | + $('drawer').className='drawer open'; | |
| 348 | + $('drawer').setAttribute('aria-hidden','false'); | |
| 349 | + $('scrim').className='scrim open'; | |
| 350 | + render(); | |
| 351 | +} | |
| 352 | +function close(){ | |
| 353 | + SEL=null; | |
| 354 | + $('drawer').className='drawer'; | |
| 355 | + $('drawer').setAttribute('aria-hidden','true'); | |
| 356 | + $('scrim').className='scrim'; | |
| 357 | + render(); | |
| 358 | +} | |
| 359 | + | |
| 360 | +function control(op){ | |
| 361 | + if(!SEL) return; | |
| 362 | + var label={start:'start',stop:'stop',restart:'restart'}[op]; | |
| 363 | + if(!window.confirm(label+' '+SEL+'?\n\nThis runs '+label+' on the node\'s service manager.')) return; | |
| 364 | + var o=$('dOut'); | |
| 365 | + o.className='out'; | |
| 366 | + o.textContent='Sending '+label+' '+SEL+' ...'; | |
| 367 | + api('control','unit='+encodeURIComponent(SEL)+'&op='+encodeURIComponent(op),'POST') | |
| 368 | + .then(function(d){ | |
| 369 | + if(d&&d.ok){ | |
| 370 | + o.className='out ok'; | |
| 371 | + o.textContent=label+' requested for '+SEL+'.'; | |
| 372 | + setTimeout(function(){load().then(function(){ | |
| 373 | + for(var i=0;i<DATA.length;i++) if(DATA[i].name===SEL){ show(DATA[i]); break; } | |
| 374 | + });},700); | |
| 375 | + }else{ | |
| 376 | + o.className='out err'; | |
| 377 | + o.textContent=(d&&(d.error||('HTTP error')))+''; | |
| 378 | + } | |
| 379 | + }).catch(function(e){ | |
| 380 | + o.className='out err'; | |
| 381 | + o.textContent='Request failed: '+e.message; | |
| 382 | + }); | |
| 383 | +} | |
| 384 | +function show(s){ | |
| 385 | + $('dState').textContent=stateLabel(s); | |
| 386 | + $('dSub').textContent=s.sub||'—'; | |
| 387 | + $('dEnabled').textContent=s.enabled||'-'; | |
| 388 | + $('dPid').textContent=s.pid>0?s.pid:'—'; | |
| 389 | + $('dMem').textContent=bytes(s.memory_bytes); | |
| 390 | + $('dSince').textContent=s.since||'—'; | |
| 391 | + render(); | |
| 392 | +} | |
| 393 | + | |
| 394 | +function setFilter(f){ | |
| 395 | + FILTER=f; | |
| 396 | + var ids={all:'cAll',running:'cRun',failed:'cFail',inactive:'cOff'}; | |
| 397 | + for(var k in ids) $(ids[k]).className='chip'+(k===f?' sel':'')+ | |
| 398 | + (k==='running'?' ok':k==='failed'?' bad':k==='inactive'?' none':''); | |
| 399 | + render(); | |
| 400 | +} | |
| 401 | + | |
| 402 | +$('cAll').onclick=function(){setFilter('');}; | |
| 403 | +$('cRun').onclick=function(){setFilter('running');}; | |
| 404 | +$('cFail').onclick=function(){setFilter('failed');}; | |
| 405 | +$('cOff').onclick=function(){setFilter('inactive');}; | |
| 406 | +$('q').oninput=render; | |
| 407 | +$('sort').onchange=function(){SORT=this.value;render();}; | |
| 408 | +$('btnRefresh').onclick=function(){load();}; | |
| 409 | +$('dClose').onclick=close; | |
| 410 | +$('scrim').onclick=close; | |
| 411 | +$('opStart').onclick=function(){control('start');}; | |
| 412 | +$('opStop').onclick=function(){control('stop');}; | |
| 413 | +$('opRestart').onclick=function(){control('restart');}; | |
| 414 | +if(window.sxApplyTheme){ | |
| 415 | + $('btnTheme').onclick=function(){ | |
| 416 | + window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark'); | |
| 417 | + }; | |
| 418 | +}else{ | |
| 419 | + $('btnTheme').className='icon-btn embed-hide hide'; | |
| 420 | +} | |
| 421 | +document.addEventListener('keydown',function(e){ | |
| 422 | + if(e.key==='Escape'&&SEL) close(); | |
| 423 | +}); | |
| 424 | +setFilter(''); | |
| 425 | +load().catch(function(e){ | |
| 426 | + $('empty').className='empty'; | |
| 427 | + $('empty').textContent='Could not load services: '+e.message; | |
| 428 | +}); | |
| 429 | +})(); | |
| 430 | +</script> | |
| 431 | +</body></html> |
| 1 | 1 | new file mode 100644 |
| index 0000000..88517f0 | ||
| --- /dev/null | ||
| +++ b/src/ui_html.h | ||
| @@ -0,0 +1,439 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | |
| 2 | +#ifndef SX_SERVICES_UI_HTML_H | |
| 3 | +#define SX_SERVICES_UI_HTML_H | |
| 4 | + | |
| 5 | +static const char *UI_HTML = | |
| 6 | + "<!DOCTYPE html>\n" | |
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | |
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | |
| 9 | + "<title>services</title>\n" | |
| 10 | + "\001\n" | |
| 11 | + "<style>\n" | |
| 12 | + "*{box-sizing:border-box}\n" | |
| 13 | + "html,body{margin:0;min-height:100%}\n" | |
| 14 | + "body{background:var(--bg);color:var(--tx,var(--text));font-family:var(--font);\n" | |
| 15 | + " font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}\n" | |
| 16 | + ".wrap{max-width:1180px;margin:0 auto;padding:18px 18px 40px}\n" | |
| 17 | + ".top{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}\n" | |
| 18 | + ".brand{font-size:11px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;\n" | |
| 19 | + " color:var(--mu,var(--text-2))}\n" | |
| 20 | + ".title{font-size:19px;font-weight:680;margin:0;letter-spacing:-.01em}\n" | |
| 21 | + ".sp{flex:1 1 auto}\n" | |
| 22 | + ".pill{font-size:11px;font-weight:600;padding:3px 9px;border-radius:999px;\n" | |
| 23 | + " background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2));\n" | |
| 24 | + " border:1px solid var(--ln,var(--line));white-space:nowrap}\n" | |
| 25 | + ".icon-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;\n" | |
| 26 | + " background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line));\n" | |
| 27 | + " color:var(--text);border-radius:9px;height:30px;padding:0 11px;cursor:pointer;\n" | |
| 28 | + " font-family:inherit;font-size:12px;font-weight:600}\n" | |
| 29 | + ".icon-btn:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | |
| 30 | + ".icon-btn:active{transform:scale(.97)}\n" | |
| 31 | + ".icon-btn svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.9;\n" | |
| 32 | + " stroke-linecap:round;stroke-linejoin:round}\n" | |
| 33 | + "\n" | |
| 34 | + ".chips{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px;\n" | |
| 35 | + " margin-bottom:14px}\n" | |
| 36 | + ".chip{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));\n" | |
| 37 | + " border-radius:12px;padding:11px 13px;cursor:pointer;font-family:inherit;\n" | |
| 38 | + " text-align:left;color:var(--text)}\n" | |
| 39 | + ".chip:hover{border-color:var(--line-2)}\n" | |
| 40 | + ".chip.sel{box-shadow:inset 0 0 0 1.5px var(--ac,var(--blue))}\n" | |
| 41 | + ".chip .k{display:flex;align-items:center;gap:6px;font-size:10.5px;font-weight:700;\n" | |
| 42 | + " letter-spacing:.07em;text-transform:uppercase;color:var(--mu,var(--text-2))}\n" | |
| 43 | + ".chip .k svg{width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:2;\n" | |
| 44 | + " stroke-linecap:round;stroke-linejoin:round}\n" | |
| 45 | + ".chip .v{font-family:var(--mono);font-size:23px;font-weight:700;margin-top:3px;\n" | |
| 46 | + " letter-spacing:-.02em}\n" | |
| 47 | + ".chip.ok .v{color:var(--green)}\n" | |
| 48 | + ".chip.bad .v{color:var(--red)}\n" | |
| 49 | + ".chip.none .v{color:var(--mu,var(--text-2))}\n" | |
| 50 | + "\n" | |
| 51 | + ".bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:10px}\n" | |
| 52 | + ".search{flex:1 1 240px;min-width:0;padding:9px 12px;border-radius:10px;\n" | |
| 53 | + " border:1px solid var(--ln,var(--line));background:var(--input-bg);color:var(--text);\n" | |
| 54 | + " font-family:inherit;font-size:13px}\n" | |
| 55 | + ".search:focus{outline:2px solid var(--ac,var(--blue));outline-offset:-1px}\n" | |
| 56 | + "select{padding:9px 11px;border-radius:10px;border:1px solid var(--ln,var(--line));\n" | |
| 57 | + " background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px}\n" | |
| 58 | + "\n" | |
| 59 | + ".panel{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));\n" | |
| 60 | + " border-radius:14px;overflow:hidden}\n" | |
| 61 | + ".tb{width:100%;overflow-x:auto}\n" | |
| 62 | + "table{width:100%;border-collapse:collapse;font-size:13px}\n" | |
| 63 | + "th{text-align:left;font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;\n" | |
| 64 | + " color:var(--mu,var(--text-2));font-weight:700;padding:9px 12px;\n" | |
| 65 | + " border-bottom:1px solid var(--ln,var(--line));white-space:nowrap;\n" | |
| 66 | + " background:var(--sf2,var(--surface-2))}\n" | |
| 67 | + "td{padding:9px 12px;border-bottom:1px solid var(--ln,var(--line));\n" | |
| 68 | + " vertical-align:middle;white-space:nowrap}\n" | |
| 69 | + "tr.row{cursor:pointer}\n" | |
| 70 | + "tr.row:hover td{background:var(--surface-hover)}\n" | |
| 71 | + "tr.row:last-child td{border-bottom:0}\n" | |
| 72 | + "tr.row.sel td{background:var(--sf2,var(--surface-2))}\n" | |
| 73 | + ".mo{font-family:var(--mono);font-size:12.5px}\n" | |
| 74 | + ".name{font-weight:600;max-width:340px;overflow:hidden;text-overflow:ellipsis}\n" | |
| 75 | + ".desc{font-size:11.5px;color:var(--mu,var(--text-2));max-width:340px;\n" | |
| 76 | + " overflow:hidden;text-overflow:ellipsis;margin-top:1px}\n" | |
| 77 | + ".tag{font-size:10px;font-weight:700;padding:2px 8px;border-radius:6px;\n" | |
| 78 | + " white-space:nowrap;letter-spacing:.03em}\n" | |
| 79 | + ".t-run{background:rgba(48,209,88,.16);color:var(--green)}\n" | |
| 80 | + ".t-fail{background:rgba(255,69,58,.16);color:var(--red)}\n" | |
| 81 | + ".t-off{background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2));\n" | |
| 82 | + " border:1px solid var(--ln,var(--line))}\n" | |
| 83 | + ".t-warn{background:rgba(255,159,10,.16);color:var(--orange)}\n" | |
| 84 | + ".dot{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:6px;\n" | |
| 85 | + " vertical-align:1px}\n" | |
| 86 | + ".d-run{background:var(--green)}.d-fail{background:var(--red)}\n" | |
| 87 | + ".d-off{background:var(--gray)}.d-warn{background:var(--orange)}\n" | |
| 88 | + ".empty{padding:26px 14px;text-align:center;color:var(--mu,var(--text-2));font-size:13px}\n" | |
| 89 | + ".hide{display:none!important}\n" | |
| 90 | + "\n" | |
| 91 | + "/* detail drawer */\n" | |
| 92 | + ".scrim{position:fixed;inset:0;background:rgba(0,0,0,.38);opacity:0;pointer-events:none;\n" | |
| 93 | + " transition:opacity .18s var(--ease);z-index:40}\n" | |
| 94 | + ".scrim.open{opacity:1;pointer-events:auto}\n" | |
| 95 | + ".drawer{position:fixed;top:0;right:0;bottom:0;width:min(430px,100%);z-index:41;\n" | |
| 96 | + " background:var(--bg-2,var(--bg-card));border-left:1px solid var(--ln,var(--line));\n" | |
| 97 | + " box-shadow:var(--shadow-lg);transform:translateX(102%);\n" | |
| 98 | + " transition:transform .22s var(--ease);display:flex;flex-direction:column;\n" | |
| 99 | + " max-width:100%}\n" | |
| 100 | + ".drawer.open{transform:none}\n" | |
| 101 | + ".dh{display:flex;align-items:flex-start;gap:10px;padding:16px 16px 12px;\n" | |
| 102 | + " border-bottom:1px solid var(--ln,var(--line))}\n" | |
| 103 | + ".dh .t{flex:1 1 auto;min-width:0}\n" | |
| 104 | + ".dh .n{font-size:15px;font-weight:680;word-break:break-all}\n" | |
| 105 | + ".dh .s{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:3px;\n" | |
| 106 | + " word-break:break-word}\n" | |
| 107 | + ".dbody{flex:1 1 auto;overflow-y:auto;padding:14px 16px 24px}\n" | |
| 108 | + ".kv{display:grid;grid-template-columns:110px minmax(0,1fr);gap:8px 12px;\n" | |
| 109 | + " font-size:12.5px;margin-bottom:16px}\n" | |
| 110 | + ".kv .k{color:var(--mu,var(--text-2))}\n" | |
| 111 | + ".kv .v{font-family:var(--mono);word-break:break-all}\n" | |
| 112 | + ".ctl{display:flex;gap:8px;flex-wrap:wrap;border-top:1px solid var(--ln,var(--line));\n" | |
| 113 | + " padding-top:14px;margin-top:4px}\n" | |
| 114 | + ".btn{background:var(--ac,var(--blue));color:#fff;border:0;border-radius:999px;\n" | |
| 115 | + " padding:8px 16px;font-weight:650;font-size:12.5px;cursor:pointer;font-family:inherit}\n" | |
| 116 | + ".btn:active{transform:scale(.98)}\n" | |
| 117 | + ".btn.gh{background:transparent;color:var(--text);border:1px solid var(--ln,var(--line))}\n" | |
| 118 | + ".btn.warn{background:var(--orange)}\n" | |
| 119 | + ".btn.bad{background:var(--red)}\n" | |
| 120 | + ".note{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:10px}\n" | |
| 121 | + ".out{margin-top:12px;padding:10px 12px;border-radius:10px;font-size:12.5px;\n" | |
| 122 | + " background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line));\n" | |
| 123 | + " word-break:break-word}\n" | |
| 124 | + ".out.err{color:var(--red);border-color:rgba(255,69,58,.4)}\n" | |
| 125 | + ".out.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n" | |
| 126 | + "\n" | |
| 127 | + "@media(max-width:860px){\n" | |
| 128 | + " .wrap{padding:14px 12px 32px}\n" | |
| 129 | + " .name,.desc{max-width:200px}\n" | |
| 130 | + " th.h-opt,td.h-opt{display:none}\n" | |
| 131 | + "}\n" | |
| 132 | + "@media(max-width:600px){\n" | |
| 133 | + " .wrap{padding:12px 10px 28px}\n" | |
| 134 | + " .title{font-size:17px}\n" | |
| 135 | + " .chips{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}\n" | |
| 136 | + " .chip .v{font-size:20px}\n" | |
| 137 | + " .name,.desc{max-width:150px}\n" | |
| 138 | + " th.h-since,td.h-since{display:none}\n" | |
| 139 | + " .drawer{width:100%}\n" | |
| 140 | + "}\n" | |
| 141 | + "</style></head><body>\n" | |
| 142 | + "<div class=\"wrap\">\n" | |
| 143 | + " <div class=\"top\">\n" | |
| 144 | + " <div>\n" | |
| 145 | + " <div class=\"brand\">SCORPIOX BOT</div>\n" | |
| 146 | + " <h1 class=\"title\">Services</h1>\n" | |
| 147 | + " </div>\n" | |
| 148 | + " <span class=\"sp\"></span>\n" | |
| 149 | + " <span class=\"pill\" id=\"initPill\">init: —</span>\n" | |
| 150 | + " <button class=\"icon-btn embed-hide\" id=\"btnRefresh\" type=\"button\" title=\"Reload\">\n" | |
| 151 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M20 12a8 8 0 1 1-2.3-5.7\"/><path d=\"M20 4v5h-5\"/></svg>\n" | |
| 152 | + " Refresh\n" | |
| 153 | + " </button>\n" | |
| 154 | + " <button class=\"icon-btn embed-hide\" id=\"btnTheme\" type=\"button\" title=\"Toggle appearance\">\n" | |
| 155 | + " <svg viewBox=\"0 0 24 24\"><circle cx=\"12\" cy=\"12\" r=\"4.2\"/><path d=\"M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.4 1.4M17.6 17.6L19 19M19 5l-1.4 1.4M6.4 17.6L5 19\"/></svg>\n" | |
| 156 | + " </button>\n" | |
| 157 | + " </div>\n" | |
| 158 | + "\n" | |
| 159 | + " <div class=\"chips\">\n" | |
| 160 | + " <button class=\"chip\" id=\"cAll\" type=\"button\"><div class=\"k\">All</div><div class=\"v\" id=\"vAll\">—</div></button>\n" | |
| 161 | + " <button class=\"chip ok\" id=\"cRun\" type=\"button\"><div class=\"k\"><span class=\"dot d-run\"></span>Running</div><div class=\"v\" id=\"vRun\">—</div></button>\n" | |
| 162 | + " <button class=\"chip bad\" id=\"cFail\" type=\"button\"><div class=\"k\"><span class=\"dot d-fail\"></span>Failed</div><div class=\"v\" id=\"vFail\">—</div></button>\n" | |
| 163 | + " <button class=\"chip none\" id=\"cOff\" type=\"button\"><div class=\"k\"><span class=\"dot d-off\"></span>Inactive</div><div class=\"v\" id=\"vOff\">—</div></button>\n" | |
| 164 | + " </div>\n" | |
| 165 | + "\n" | |
| 166 | + " <div class=\"bar\">\n" | |
| 167 | + " <input class=\"search\" id=\"q\" type=\"search\" placeholder=\"Search name or description\" autocomplete=\"off\" spellcheck=\"false\">\n" | |
| 168 | + " <select id=\"sort\" title=\"Sort\">\n" | |
| 169 | + " <option value=\"failed\">Sort: failed first</option>\n" | |
| 170 | + " <option value=\"name\">Sort: name</option>\n" | |
| 171 | + " <option value=\"state\">Sort: state</option>\n" | |
| 172 | + " </select>\n" | |
| 173 | + " </div>\n" | |
| 174 | + "\n" | |
| 175 | + " <div class=\"panel\">\n" | |
| 176 | + " <div class=\"tb\">\n" | |
| 177 | + " <table>\n" | |
| 178 | + " <thead><tr>\n" | |
| 179 | + " <th>Service</th>\n" | |
| 180 | + " <th>State</th>\n" | |
| 181 | + " <th class=\"h-opt\">Enabled</th>\n" | |
| 182 | + " <th class=\"h-opt\">PID</th>\n" | |
| 183 | + " <th class=\"h-opt\">Memory</th>\n" | |
| 184 | + " <th class=\"h-since\">Since</th>\n" | |
| 185 | + " </tr></thead>\n" | |
| 186 | + " <tbody id=\"rows\"></tbody>\n" | |
| 187 | + " </table>\n" | |
| 188 | + " </div>\n" | |
| 189 | + " <div id=\"empty\" class=\"empty hide\">No services matched this filter.</div>\n" | |
| 190 | + " </div>\n" | |
| 191 | + "</div>\n" | |
| 192 | + "\n" | |
| 193 | + "<div class=\"scrim\" id=\"scrim\"></div>\n" | |
| 194 | + "<aside class=\"drawer\" id=\"drawer\" aria-hidden=\"true\">\n" | |
| 195 | + " <div class=\"dh\">\n" | |
| 196 | + " <div class=\"t\"><div class=\"n\" id=\"dName\">—</div><div class=\"s\" id=\"dDesc\"></div></div>\n" | |
| 197 | + " <button class=\"icon-btn\" id=\"dClose\" type=\"button\" title=\"Close\">\n" | |
| 198 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M6 6l12 12M18 6L6 18\"/></svg>\n" | |
| 199 | + " </button>\n" | |
| 200 | + " </div>\n" | |
| 201 | + " <div class=\"dbody\">\n" | |
| 202 | + " <div class=\"kv\">\n" | |
| 203 | + " <div class=\"k\">State</div><div class=\"v\" id=\"dState\">—</div>\n" | |
| 204 | + " <div class=\"k\">Sub-state</div><div class=\"v\" id=\"dSub\">—</div>\n" | |
| 205 | + " <div class=\"k\">Enabled</div><div class=\"v\" id=\"dEnabled\">—</div>\n" | |
| 206 | + " <div class=\"k\">PID</div><div class=\"v\" id=\"dPid\">—</div>\n" | |
| 207 | + " <div class=\"k\">Memory</div><div class=\"v\" id=\"dMem\">—</div>\n" | |
| 208 | + " <div class=\"k\">Since</div><div class=\"v\" id=\"dSince\">—</div>\n" | |
| 209 | + " </div>\n" | |
| 210 | + " <div class=\"ctl hide\" id=\"dCtl\">\n" | |
| 211 | + " <button class=\"btn\" id=\"opStart\" type=\"button\">Start</button>\n" | |
| 212 | + " <button class=\"btn warn\" id=\"opRestart\" type=\"button\">Restart</button>\n" | |
| 213 | + " <button class=\"btn bad\" id=\"opStop\" type=\"button\">Stop</button>\n" | |
| 214 | + " </div>\n" | |
| 215 | + " <div class=\"note hide\" id=\"dNote\"></div>\n" | |
| 216 | + " <div class=\"out hide\" id=\"dOut\"></div>\n" | |
| 217 | + " </div>\n" | |
| 218 | + "</aside>\n" | |
| 219 | + "\n" | |
| 220 | + "<script>\n" | |
| 221 | + "(function(){\n" | |
| 222 | + "\"use strict\";\n" | |
| 223 | + "var q=new URLSearchParams(location.search);\n" | |
| 224 | + "var node=q.get('node')||'';\n" | |
| 225 | + "var sid=q.get('id')||'';\n" | |
| 226 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | |
| 227 | + " localStorage.getItem('bot_active_pwd')||'';\n" | |
| 228 | + "var HUB=q.get('plugin')||'';\n" | |
| 229 | + "\n" | |
| 230 | + "/* Two call routes. Through the hub -> call the hub proxy back. Opened directly\n" | |
| 231 | + " * on the node -> the plugin itself is the route. Calling /plugins?plugin= on the\n" | |
| 232 | + " * node returns the discovery list, not this plugin. */\n" | |
| 233 | + "function api(action,extra,method){\n" | |
| 234 | + " var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_services')+\n" | |
| 235 | + " '?action='+encodeURIComponent(action)+(extra?('&'+extra):'')+\n" | |
| 236 | + " (node?'&node='+encodeURIComponent(node):'')+\n" | |
| 237 | + " (sid?'&id='+encodeURIComponent(sid):'')+\n" | |
| 238 | + " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | |
| 239 | + " return fetch(u,{method:method||'GET',headers:pwd?{'X-Bot-Password':pwd}:{}})\n" | |
| 240 | + " .then(function(r){return r.json();});\n" | |
| 241 | + "}\n" | |
| 242 | + "function $(id){return document.getElementById(id);}\n" | |
| 243 | + "function esc(v){return String(v==null?'':v).replace(/[&<>\"']/g,function(c){\n" | |
| 244 | + " return({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''})[c];});}\n" | |
| 245 | + "function bytes(n){\n" | |
| 246 | + " if(n==null||n===0) return '—';\n" | |
| 247 | + " var u=['B','KiB','MiB','GiB','TiB'],i=0,v=n;\n" | |
| 248 | + " while(v>=1024&&i<u.length-1){v/=1024;i++;}\n" | |
| 249 | + " return (v>=100?Math.round(v):(Math.round(v*10)/10))+' '+u[i];\n" | |
| 250 | + "}\n" | |
| 251 | + "var DATA=[],CTL=false,FILTER='',SORT='failed',SEL=null;\n" | |
| 252 | + "\n" | |
| 253 | + "function stateCls(s){\n" | |
| 254 | + " if(s.failed||s.active==='failed') return 'fail';\n" | |
| 255 | + " if(s.active==='running'||s.active==='active'||s.sub==='running') return 'run';\n" | |
| 256 | + " if(s.active==='paused'||s.active==='starting'||s.active==='stopping') return 'warn';\n" | |
| 257 | + " return 'off';\n" | |
| 258 | + "}\n" | |
| 259 | + "function stateLabel(s){\n" | |
| 260 | + " var c=stateCls(s);\n" | |
| 261 | + " if(c==='run') return 'running';\n" | |
| 262 | + " if(c==='fail') return 'failed';\n" | |
| 263 | + " if(c==='warn') return s.active||'pending';\n" | |
| 264 | + " return s.active==='inactive'?'inactive':(s.active||'inactive');\n" | |
| 265 | + "}\n" | |
| 266 | + "/* unused helper removed: stateLabel(s) already returns the visible label */\n" | |
| 267 | + "\n" | |
| 268 | + "function visible(){\n" | |
| 269 | + " var f=FILTER, needle=($('q').value||'').toLowerCase();\n" | |
| 270 | + " var out=DATA.filter(function(s){\n" | |
| 271 | + " if(f==='running'&&stateCls(s)!=='run') return false;\n" | |
| 272 | + " if(f==='failed'&&stateCls(s)!=='fail') return false;\n" | |
| 273 | + " if(f==='inactive'&&stateCls(s)!=='off') return false;\n" | |
| 274 | + " if(needle){\n" | |
| 275 | + " var hay=(s.name+' '+(s.description||'')).toLowerCase();\n" | |
| 276 | + " if(hay.indexOf(needle)<0) return false;\n" | |
| 277 | + " }\n" | |
| 278 | + " return true;\n" | |
| 279 | + " });\n" | |
| 280 | + " if(SORT==='name') out.sort(function(a,b){return a.name<b.name?-1:a.name>b.name?1:0;});\n" | |
| 281 | + " else if(SORT==='state') out.sort(function(a,b){\n" | |
| 282 | + " var x=stateCls(a),y=stateCls(b);\n" | |
| 283 | + " if(x!==y) return x<y?-1:1;\n" | |
| 284 | + " return a.name<b.name?-1:1;});\n" | |
| 285 | + " return out;\n" | |
| 286 | + "}\n" | |
| 287 | + "\n" | |
| 288 | + "function render(){\n" | |
| 289 | + " var rows=visible();\n" | |
| 290 | + " var h='';\n" | |
| 291 | + " for(var i=0;i<rows.length;i++){\n" | |
| 292 | + " var s=rows[i],c=stateCls(s);\n" | |
| 293 | + " h+='<tr class=\"row'+(SEL&&SEL===s.name?' sel':'')+'\" data-n=\"'+esc(s.name)+'\">'+\n" | |
| 294 | + " '<td><div class=\"name\" title=\"'+esc(s.name)+'\">'+esc(s.name)+'</div>'+\n" | |
| 295 | + " (s.description?'<div class=\"desc\" title=\"'+esc(s.description)+'\">'+esc(s.description)+'</div>':'')+\n" | |
| 296 | + " '</td>'+\n" | |
| 297 | + " '<td><span class=\"tag t-'+c+'\"><span class=\"dot d-'+c+'\"></span>'+\n" | |
| 298 | + " esc(stateLabel(s))+'</span></td>'+\n" | |
| 299 | + " '<td class=\"mo h-opt\">'+esc(s.enabled||'-')+'</td>'+\n" | |
| 300 | + " '<td class=\"mo h-opt\">'+(s.pid>0?esc(s.pid):'—')+'</td>'+\n" | |
| 301 | + " '<td class=\"mo h-opt\">'+bytes(s.memory_bytes)+'</td>'+\n" | |
| 302 | + " '<td class=\"mo h-since\">'+esc(s.since||'—')+'</td></tr>';\n" | |
| 303 | + " }\n" | |
| 304 | + " $('rows').innerHTML=h;\n" | |
| 305 | + " $('empty').className=rows.length?'empty hide':'empty';\n" | |
| 306 | + " var trs=$('rows').querySelectorAll('tr.row');\n" | |
| 307 | + " for(var k=0;k<trs.length;k++){\n" | |
| 308 | + " trs[k].onclick=function(){open(this.getAttribute('data-n'));};\n" | |
| 309 | + " }\n" | |
| 310 | + "}\n" | |
| 311 | + "\n" | |
| 312 | + "function load(){\n" | |
| 313 | + " return api('list','filter=all').then(function(d){\n" | |
| 314 | + " if(!d||!d.ok){ throw new Error((d&&d.error)||'load failed'); }\n" | |
| 315 | + " DATA=d.services||[];\n" | |
| 316 | + " CTL=!!d.control_enabled;\n" | |
| 317 | + " var sum=d.summary||{};\n" | |
| 318 | + " $('vAll').textContent=DATA.length;\n" | |
| 319 | + " $('vRun').textContent=sum.running||0;\n" | |
| 320 | + " $('vFail').textContent=sum.failed||0;\n" | |
| 321 | + " $('vOff').textContent=sum.inactive||0;\n" | |
| 322 | + " $('initPill').textContent='init: '+(d.init_system||'unknown')+\n" | |
| 323 | + " (CTL?' · control on':' · read-only');\n" | |
| 324 | + " render();\n" | |
| 325 | + " });\n" | |
| 326 | + "}\n" | |
| 327 | + "\n" | |
| 328 | + "function open(name){\n" | |
| 329 | + " var s=null;\n" | |
| 330 | + " for(var i=0;i<DATA.length;i++) if(DATA[i].name===name){s=DATA[i];break;}\n" | |
| 331 | + " if(!s) return;\n" | |
| 332 | + " SEL=name;\n" | |
| 333 | + " $('dName').textContent=s.name;\n" | |
| 334 | + " $('dDesc').textContent=s.description||'';\n" | |
| 335 | + " $('dState').textContent=stateLabel(s);\n" | |
| 336 | + " $('dSub').textContent=s.sub||'—';\n" | |
| 337 | + " $('dEnabled').textContent=s.enabled||'-';\n" | |
| 338 | + " $('dPid').textContent=s.pid>0?s.pid:'—';\n" | |
| 339 | + " $('dMem').textContent=bytes(s.memory_bytes);\n" | |
| 340 | + " $('dSince').textContent=s.since||'—';\n" | |
| 341 | + " $('dOut').className='out hide';\n" | |
| 342 | + " $('dOut').textContent='';\n" | |
| 343 | + " if(CTL){\n" | |
| 344 | + " $('dCtl').className='ctl';\n" | |
| 345 | + " $('dNote').className='note';\n" | |
| 346 | + " $('dNote').textContent='Control is enabled on this node (SERVICES_ALLOW_CONTROL=1). Every action is sent as a separate argv element, never through a shell.';\n" | |
| 347 | + " }else{\n" | |
| 348 | + " $('dCtl').className='ctl hide';\n" | |
| 349 | + " $('dNote').className='note';\n" | |
| 350 | + " $('dNote').textContent='Read-only: set SERVICES_ALLOW_CONTROL=1 in this node\\'s plugin environment to enable start, stop and restart.';\n" | |
| 351 | + " }\n" | |
| 352 | + " $('drawer').className='drawer open';\n" | |
| 353 | + " $('drawer').setAttribute('aria-hidden','false');\n" | |
| 354 | + " $('scrim').className='scrim open';\n" | |
| 355 | + " render();\n" | |
| 356 | + "}\n" | |
| 357 | + "function close(){\n" | |
| 358 | + " SEL=null;\n" | |
| 359 | + " $('drawer').className='drawer';\n" | |
| 360 | + " $('drawer').setAttribute('aria-hidden','true');\n" | |
| 361 | + " $('scrim').className='scrim';\n" | |
| 362 | + " render();\n" | |
| 363 | + "}\n" | |
| 364 | + "\n" | |
| 365 | + "function control(op){\n" | |
| 366 | + " if(!SEL) return;\n" | |
| 367 | + " var label={start:'start',stop:'stop',restart:'restart'}[op];\n" | |
| 368 | + " if(!window.confirm(label+' '+SEL+'?\\n\\nThis runs '+label+' on the node\\'s service manager.')) return;\n" | |
| 369 | + " var o=$('dOut');\n" | |
| 370 | + " o.className='out';\n" | |
| 371 | + " o.textContent='Sending '+label+' '+SEL+' ...';\n" | |
| 372 | + " api('control','unit='+encodeURIComponent(SEL)+'&op='+encodeURIComponent(op),'POST')\n" | |
| 373 | + " .then(function(d){\n" | |
| 374 | + " if(d&&d.ok){\n" | |
| 375 | + " o.className='out ok';\n" | |
| 376 | + " o.textContent=label+' requested for '+SEL+'.';\n" | |
| 377 | + " setTimeout(function(){load().then(function(){\n" | |
| 378 | + " for(var i=0;i<DATA.length;i++) if(DATA[i].name===SEL){ show(DATA[i]); break; }\n" | |
| 379 | + " });},700);\n" | |
| 380 | + " }else{\n" | |
| 381 | + " o.className='out err';\n" | |
| 382 | + " o.textContent=(d&&(d.error||('HTTP error')))+'';\n" | |
| 383 | + " }\n" | |
| 384 | + " }).catch(function(e){\n" | |
| 385 | + " o.className='out err';\n" | |
| 386 | + " o.textContent='Request failed: '+e.message;\n" | |
| 387 | + " });\n" | |
| 388 | + "}\n" | |
| 389 | + "function show(s){\n" | |
| 390 | + " $('dState').textContent=stateLabel(s);\n" | |
| 391 | + " $('dSub').textContent=s.sub||'—';\n" | |
| 392 | + " $('dEnabled').textContent=s.enabled||'-';\n" | |
| 393 | + " $('dPid').textContent=s.pid>0?s.pid:'—';\n" | |
| 394 | + " $('dMem').textContent=bytes(s.memory_bytes);\n" | |
| 395 | + " $('dSince').textContent=s.since||'—';\n" | |
| 396 | + " render();\n" | |
| 397 | + "}\n" | |
| 398 | + "\n" | |
| 399 | + "function setFilter(f){\n" | |
| 400 | + " FILTER=f;\n" | |
| 401 | + " var ids={all:'cAll',running:'cRun',failed:'cFail',inactive:'cOff'};\n" | |
| 402 | + " for(var k in ids) $(ids[k]).className='chip'+(k===f?' sel':'')+\n" | |
| 403 | + " (k==='running'?' ok':k==='failed'?' bad':k==='inactive'?' none':'');\n" | |
| 404 | + " render();\n" | |
| 405 | + "}\n" | |
| 406 | + "\n" | |
| 407 | + "$('cAll').onclick=function(){setFilter('');};\n" | |
| 408 | + "$('cRun').onclick=function(){setFilter('running');};\n" | |
| 409 | + "$('cFail').onclick=function(){setFilter('failed');};\n" | |
| 410 | + "$('cOff').onclick=function(){setFilter('inactive');};\n" | |
| 411 | + "$('q').oninput=render;\n" | |
| 412 | + "$('sort').onchange=function(){SORT=this.value;render();};\n" | |
| 413 | + "$('btnRefresh').onclick=function(){load();};\n" | |
| 414 | + "$('dClose').onclick=close;\n" | |
| 415 | + "$('scrim').onclick=close;\n" | |
| 416 | + "$('opStart').onclick=function(){control('start');};\n" | |
| 417 | + "$('opStop').onclick=function(){control('stop');};\n" | |
| 418 | + "$('opRestart').onclick=function(){control('restart');};\n" | |
| 419 | + "if(window.sxApplyTheme){\n" | |
| 420 | + " $('btnTheme').onclick=function(){\n" | |
| 421 | + " window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark');\n" | |
| 422 | + " };\n" | |
| 423 | + "}else{\n" | |
| 424 | + " $('btnTheme').className='icon-btn embed-hide hide';\n" | |
| 425 | + "}\n" | |
| 426 | + "document.addEventListener('keydown',function(e){\n" | |
| 427 | + " if(e.key==='Escape'&&SEL) close();\n" | |
| 428 | + "});\n" | |
| 429 | + "setFilter('');\n" | |
| 430 | + "load().catch(function(e){\n" | |
| 431 | + " $('empty').className='empty';\n" | |
| 432 | + " $('empty').textContent='Could not load services: '+e.message;\n" | |
| 433 | + "});\n" | |
| 434 | + "})();\n" | |
| 435 | + "</script>\n" | |
| 436 | + "\002</body></html>\n" | |
| 437 | + ; | |
| 438 | + | |
| 439 | +#endif /* SX_SERVICES_UI_HTML_H */ |
| 1 | 1 | new file mode 100755 |
| index 0000000..8e0079d | ||
| --- /dev/null | ||
| +++ b/tests/e2e.py | ||
| @@ -0,0 +1,204 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tests/e2e.py - viewport checks for the plugin_services board. | |
| 3 | + | |
| 4 | +Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, points it | |
| 5 | +at the systemd fixtures so the table is always populated, and opens it with | |
| 6 | +Playwright at 1440 / 1024 / 390 CSS pixels in both themes. It asserts there is | |
| 7 | +no horizontal overflow, no console error, that the summary chips and the table | |
| 8 | +rendered, and that a row opens the detail drawer. Screenshots land in docs/ for | |
| 9 | +the README. Skips cleanly (exit 0) when Playwright is not installed, so the | |
| 10 | +offline suite stays dependency-free. | |
| 11 | + | |
| 12 | + python3 tests/e2e.py # run if Playwright is available | |
| 13 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | |
| 14 | +""" | |
| 15 | + | |
| 16 | +import argparse | |
| 17 | +import http.server | |
| 18 | +import os | |
| 19 | +import socketserver | |
| 20 | +import subprocess | |
| 21 | +import sys | |
| 22 | +import tempfile | |
| 23 | +import threading | |
| 24 | +from urllib.parse import urlparse | |
| 25 | + | |
| 26 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 27 | +BIN = os.path.join(ROOT, "plugin_services") | |
| 28 | +DOCS = os.path.join(ROOT, "docs") | |
| 29 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | |
| 30 | +THEMES = ["dark", "light"] | |
| 31 | + | |
| 32 | +UNITS = """[{"unit":"nginx.service","load":"loaded","active":"active","sub":"running","description":"A high performance web server and a reverse proxy server"}, | |
| 33 | + {"unit":"ssh.service","load":"loaded","active":"active","sub":"running","description":"OpenBSD Secure Shell server"}, | |
| 34 | + {"unit":"cron.service","load":"loaded","active":"inactive","sub":"dead","description":"Regular background program processing daemon"}, | |
| 35 | + {"unit":"docker.service","load":"loaded","active":"active","sub":"running","description":"Docker Application Container Engine"}, | |
| 36 | + {"unit":"broken.service","load":"loaded","active":"failed","sub":"failed","description":"A service that failed on purpose"}, | |
| 37 | + {"unit":"postgresql.service","load":"loaded","active":"inactive","sub":"dead","description":"PostgreSQL RDBMS"}] | |
| 38 | +""" | |
| 39 | + | |
| 40 | +SHOW = """Id=nginx.service | |
| 41 | +MainPID=4242 | |
| 42 | +MemoryCurrent=10485760 | |
| 43 | +UnitFileState=enabled | |
| 44 | +ActiveEnterTimestamp=Wed 2026-11-12 04:00:00 UTC | |
| 45 | + | |
| 46 | +Id=ssh.service | |
| 47 | +MainPID=912 | |
| 48 | +MemoryCurrent=7340032 | |
| 49 | +UnitFileState=static | |
| 50 | +ActiveEnterTimestamp=Wed 2026-11-12 03:00:00 UTC | |
| 51 | + | |
| 52 | +Id=docker.service | |
| 53 | +MainPID=1180 | |
| 54 | +MemoryCurrent=205520896 | |
| 55 | +UnitFileState=enabled | |
| 56 | +ActiveEnterTimestamp=Wed 2026-11-12 02:12:00 UTC | |
| 57 | + | |
| 58 | +""" | |
| 59 | + | |
| 60 | + | |
| 61 | +class Handler(http.server.BaseHTTPRequestHandler): | |
| 62 | + fixture_dir = "" | |
| 63 | + | |
| 64 | + def do_GET(self): # noqa: N802 | |
| 65 | + u = urlparse(self.path) | |
| 66 | + env = dict(os.environ) | |
| 67 | + env["QUERY_STRING"] = u.query | |
| 68 | + env["REQUEST_METHOD"] = "GET" | |
| 69 | + env.pop("BOT_PASSWORD", None) | |
| 70 | + env["SERVICES_MOCK_SYSTEMCTL"] = os.path.join(self.fixture_dir, "units.json") | |
| 71 | + env["SERVICES_MOCK_SYSTEMCTL_SHOW"] = os.path.join(self.fixture_dir, "show.txt") | |
| 72 | + out = subprocess.run([BIN], capture_output=True, env=env, timeout=30).stdout | |
| 73 | + sep = out.find(b"\r\n\r\n") | |
| 74 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | |
| 75 | + body = out[sep + 4:] if sep >= 0 else out | |
| 76 | + ctype = "text/html; charset=utf-8" | |
| 77 | + for line in headers.splitlines(): | |
| 78 | + if line.lower().startswith("content-type:"): | |
| 79 | + ctype = line.split(":", 1)[1].strip() | |
| 80 | + self.send_response(200) | |
| 81 | + self.send_header("Content-Type", ctype) | |
| 82 | + self.send_header("Cache-Control", "no-store") | |
| 83 | + self.send_header("Content-Length", str(len(body))) | |
| 84 | + self.end_headers() | |
| 85 | + self.wfile.write(body) | |
| 86 | + | |
| 87 | + def log_message(self, *_a): | |
| 88 | + pass | |
| 89 | + | |
| 90 | + | |
| 91 | +def main(): | |
| 92 | + ap = argparse.ArgumentParser() | |
| 93 | + ap.add_argument("--strict", action="store_true") | |
| 94 | + args = ap.parse_args() | |
| 95 | + | |
| 96 | + if not os.path.exists(BIN): | |
| 97 | + print("plugin_services is not built; run make first", file=sys.stderr) | |
| 98 | + return 1 | |
| 99 | + | |
| 100 | + try: | |
| 101 | + from playwright.sync_api import sync_playwright | |
| 102 | + except Exception: | |
| 103 | + msg = "playwright not installed - skipping viewport e2e" | |
| 104 | + if args.strict: | |
| 105 | + print(msg, file=sys.stderr) | |
| 106 | + return 2 | |
| 107 | + print(msg) | |
| 108 | + return 0 | |
| 109 | + | |
| 110 | + fixture_dir = tempfile.mkdtemp(prefix="services-e2e-") | |
| 111 | + with open(os.path.join(fixture_dir, "units.json"), "w", encoding="utf-8") as f: | |
| 112 | + f.write(UNITS) | |
| 113 | + with open(os.path.join(fixture_dir, "show.txt"), "w", encoding="utf-8") as f: | |
| 114 | + f.write(SHOW) | |
| 115 | + Handler.fixture_dir = fixture_dir | |
| 116 | + | |
| 117 | + os.makedirs(DOCS, exist_ok=True) | |
| 118 | + | |
| 119 | + with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv: | |
| 120 | + port = srv.server_address[1] | |
| 121 | + threading.Thread(target=srv.serve_forever, daemon=True).start() | |
| 122 | + base = "http://127.0.0.1:%d/plugin_services" % port | |
| 123 | + | |
| 124 | + failures = [] | |
| 125 | + with sync_playwright() as p: | |
| 126 | + browser = p.chromium.launch() | |
| 127 | + for (w, h) in VIEWPORTS: | |
| 128 | + for theme in THEMES: | |
| 129 | + url = "%s?theme=%s" % (base, theme) | |
| 130 | + page = browser.new_page(viewport={"width": w, "height": h}) | |
| 131 | + errors = [] | |
| 132 | + page.on("console", lambda m: errors.append(m.text) | |
| 133 | + if m.type == "error" else None) | |
| 134 | + page.on("pageerror", lambda e: errors.append(str(e))) | |
| 135 | + page.goto(url, wait_until="load") | |
| 136 | + page.wait_for_timeout(1200) | |
| 137 | + | |
| 138 | + sw = page.evaluate("document.documentElement.scrollWidth") | |
| 139 | + iw = page.evaluate("window.innerWidth") | |
| 140 | + if sw > iw + 1: | |
| 141 | + failures.append("%dx%d %s horizontal overflow %d > %d" | |
| 142 | + % (w, h, theme, sw, iw)) | |
| 143 | + | |
| 144 | + applied = page.evaluate( | |
| 145 | + "document.documentElement.getAttribute('data-theme')") | |
| 146 | + if applied != theme: | |
| 147 | + failures.append("%dx%d %s ?theme= did not apply (%r)" | |
| 148 | + % (w, h, theme, applied)) | |
| 149 | + | |
| 150 | + total = page.evaluate( | |
| 151 | + "document.getElementById('vAll').textContent") | |
| 152 | + if not total.strip().isdigit(): | |
| 153 | + failures.append("%dx%d %s All chip did not render (%r)" | |
| 154 | + % (w, h, theme, total)) | |
| 155 | + | |
| 156 | + rows = page.evaluate( | |
| 157 | + "document.querySelectorAll('#rows tr.row').length") | |
| 158 | + if rows < 1: | |
| 159 | + failures.append("%dx%d %s service table is empty" | |
| 160 | + % (w, h, theme)) | |
| 161 | + | |
| 162 | + img = page.query_selector("#rows") and page.query_selector("svg") | |
| 163 | + if img is None: | |
| 164 | + failures.append("%dx%d %s no inline SVG icon rendered" | |
| 165 | + % (w, h, theme)) | |
| 166 | + | |
| 167 | + if theme == "dark": | |
| 168 | + page.click("#rows tr.row") | |
| 169 | + page.wait_for_timeout(350) | |
| 170 | + opened = page.evaluate( | |
| 171 | + "document.getElementById('drawer').classList.contains('open')") | |
| 172 | + if not opened: | |
| 173 | + failures.append("%dx%d drawer did not open" % (w, h)) | |
| 174 | + name = page.evaluate( | |
| 175 | + "document.getElementById('dName').textContent") | |
| 176 | + if not name or name == "—": | |
| 177 | + failures.append("%dx%d drawer has no unit name" % (w, h)) | |
| 178 | + page.screenshot(path=os.path.join( | |
| 179 | + DOCS, "ui-%d-%s.png" % (w, theme)), full_page=False) | |
| 180 | + page.click("#dClose") | |
| 181 | + else: | |
| 182 | + page.screenshot(path=os.path.join( | |
| 183 | + DOCS, "ui-%d-%s.png" % (w, theme)), full_page=False) | |
| 184 | + | |
| 185 | + if errors: | |
| 186 | + failures.append("%dx%d %s console errors: %s" | |
| 187 | + % (w, h, theme, errors[:3])) | |
| 188 | + | |
| 189 | + page.close() | |
| 190 | + browser.close() | |
| 191 | + | |
| 192 | + if failures: | |
| 193 | + print("FAIL") | |
| 194 | + for f in failures: | |
| 195 | + print(" " + f) | |
| 196 | + return 1 | |
| 197 | + | |
| 198 | + print("ok - %d viewports x %d themes clean (no overflow, no console error, " | |
| 199 | + "chips + table + drawer rendered)" % (len(VIEWPORTS), len(THEMES))) | |
| 200 | + return 0 | |
| 201 | + | |
| 202 | + | |
| 203 | +if __name__ == "__main__": | |
| 204 | + sys.exit(main()) |
| 1 | 1 | new file mode 100644 |
| index 0000000..98de868 | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,475 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_services across all 3 modes. | |
| 3 | +# | |
| 4 | +# Everything runs against ./plugin_services (native build). The service tables | |
| 5 | +# come from fixtures, so the suite tests the parsers for all three init systems | |
| 6 | +# (systemd JSON, legacy systemd text, launchctl) without needing a live systemd, | |
| 7 | +# launchd or Windows SCM. Optional cross-target artifacts (musl, aarch64, PE) | |
| 8 | +# are checked when they exist. The last section audits the whole git history for | |
| 9 | +# secrets and internal addresses. | |
| 10 | +# | |
| 11 | +# Exit code 0 = everything passed. | |
| 12 | + | |
| 13 | +set -u | |
| 14 | + | |
| 15 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 16 | +cd "$ROOT" || exit 1 | |
| 17 | + | |
| 18 | +BIN=./plugin_services | |
| 19 | +PASS=0 | |
| 20 | +FAIL=0 | |
| 21 | + | |
| 22 | +if [ -t 1 ]; then | |
| 23 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 24 | +else | |
| 25 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 26 | +fi | |
| 27 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 28 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 29 | + | |
| 30 | +check() { # check <desc> <expected-substring> <actual> | |
| 31 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 32 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | |
| 33 | + fi | |
| 34 | +} | |
| 35 | + | |
| 36 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 37 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 38 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 39 | + fi | |
| 40 | +} | |
| 41 | + | |
| 42 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 43 | + | |
| 44 | +body() { # strip CGI headers if present, drop CRs, keep the payload | |
| 45 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | |
| 46 | + BEGIN { inhdr = 0 } | |
| 47 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|Content-Security-Policy):/) { inhdr = 1; next } | |
| 48 | + inhdr && $0 == "" { inhdr = 0; next } | |
| 49 | + inhdr { next } | |
| 50 | + { print } | |
| 51 | + ' | |
| 52 | +} | |
| 53 | + | |
| 54 | +hdr() { printf '%s\n' "$1" | tr -d '\r' | sed -n '1p'; } | |
| 55 | + | |
| 56 | +json_ok() { # json_ok <desc> <json> [python-expression] | |
| 57 | + expr=${3:-True} | |
| 58 | + if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then | |
| 59 | + pass "$1" | |
| 60 | + else | |
| 61 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | |
| 62 | + fi | |
| 63 | +} | |
| 64 | + | |
| 65 | +run() { # run <query-string> [extra env assignments...] -> raw output | |
| 66 | + qs="$1"; shift | |
| 67 | + env QUERY_STRING="$qs" "$@" $BIN 2>&1 | |
| 68 | +} | |
| 69 | + | |
| 70 | +api() { body "$(run "$1")"; } | |
| 71 | + | |
| 72 | +# ---------------------------------------------------------------- setup | |
| 73 | +section "build" | |
| 74 | +if [ ! -x "$BIN" ]; then | |
| 75 | + echo " building native binary..." | |
| 76 | + cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src \ | |
| 77 | + -o "$BIN" src/plugin_services.c || { echo " build failed"; exit 1; } | |
| 78 | +fi | |
| 79 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | |
| 80 | + | |
| 81 | +WORK=$(mktemp -d 2>/dev/null || echo /tmp/ps_$$) | |
| 82 | +mkdir -p "$WORK" | |
| 83 | + | |
| 84 | +# ---------------------------------------------------------------- meta | |
| 85 | +section "mode 1 - discovery metadata" | |
| 86 | +M=$(body "$($BIN --meta)") | |
| 87 | +json_ok "--meta is valid JSON" "$M" "d['name']=='services'" | |
| 88 | +check "--meta name is one word" '"name":"services"' "$M" | |
| 89 | +check "--meta desc" '"desc":"System services"' "$M" | |
| 90 | +json_ok "--meta desc respects the 15-char rule" "$M" "len(d['desc'])<=15" | |
| 91 | +json_ok "--meta has exactly two keys" "$M" "len(d)==2" | |
| 92 | +M2=$(body "$(SX_PLUGIN_META=1 $BIN)") | |
| 93 | +check "SX_PLUGIN_META env var works" '"name":"services"' "$M2" | |
| 94 | +check_not "--meta emits no HTML" '<html' "$M" | |
| 95 | +check_not "--meta carries no version noise" 'version' "$M" | |
| 96 | +check "--version prints the id and version" 'plugin_services 1.0.0' "$($BIN --version)" | |
| 97 | + | |
| 98 | +# ---------------------------------------------------------------- auth | |
| 99 | +section "mode 2 - node authentication" | |
| 100 | +A=$(run 'action=list' BOT_PASSWORD=testpw) | |
| 101 | +check "unauthenticated list is 401" '401 Unauthorized' "$(hdr "$A")" | |
| 102 | +check "unauthenticated list returns the JSON error" '"error":"invalid node password"' "$A" | |
| 103 | +A2=$(run '' BOT_PASSWORD=testpw) | |
| 104 | +check "unauthenticated HTML is 401 too" '401 Unauthorized' "$(hdr "$A2")" | |
| 105 | +check_not "the 401 body is not the page" '<!DOCTYPE' "$A2" | |
| 106 | +A3=$(run 'action=list&pwd=testpw' BOT_PASSWORD=testpw) | |
| 107 | +json_ok "?pwd= authenticates" "$(body "$A3")" "d['ok'] is True" | |
| 108 | +A4=$(run 'action=list' BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw) | |
| 109 | +json_ok "X-Bot-Password authenticates" "$(body "$A4")" "d['ok'] is True" | |
| 110 | +A5=$(run 'action=list' BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw') | |
| 111 | +json_ok "Authorization: Bearer authenticates" "$(body "$A5")" "d['ok'] is True" | |
| 112 | +A6=$(run 'action=list' BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer wrong') | |
| 113 | +check "a wrong bearer token is rejected" '401 Unauthorized' "$(hdr "$A6")" | |
| 114 | +A7=$(run 'action=list') | |
| 115 | +json_ok "auth is a no-op when BOT_PASSWORD is unset" "$(body "$A7")" "d['ok'] is True" | |
| 116 | + | |
| 117 | +# ---------------------------------------------------------------- systemd json | |
| 118 | +section "mode 2a - systemd JSON parser" | |
| 119 | + | |
| 120 | +cat > "$WORK/units.json" <<'JSON' | |
| 121 | +[{"unit":"nginx.service","load":"loaded","active":"active","sub":"running","description":"A high performance web server and a reverse proxy server"}, | |
| 122 | + {"unit":"ssh.service","load":"loaded","active":"active","sub":"running","description":"OpenBSD Secure Shell server"}, | |
| 123 | + {"unit":"cron.service","load":"loaded","active":"inactive","sub":"dead","description":"Regular background program processing daemon"}, | |
| 124 | + {"unit":"broken.service","load":"loaded","active":"failed","sub":"failed","description":"A service that failed on purpose"}, | |
| 125 | + {"unit":"ghost.service","load":"not-found","active":"inactive","sub":"dead","description":"Does not exist"}] | |
| 126 | +JSON | |
| 127 | + | |
| 128 | +cat > "$WORK/show.txt" <<'SHOW' | |
| 129 | +Id=nginx.service | |
| 130 | +Description=A high performance web server and a reverse proxy server | |
| 131 | +ActiveState=active | |
| 132 | +SubState=running | |
| 133 | +MainPID=4242 | |
| 134 | +MemoryCurrent=10485760 | |
| 135 | +UnitFileState=enabled | |
| 136 | +ActiveEnterTimestamp=Wed 2026-11-12 04:00:00 UTC | |
| 137 | + | |
| 138 | +Id=ssh.service | |
| 139 | +Description=OpenBSD Secure Shell server | |
| 140 | +ActiveState=active | |
| 141 | +SubState=running | |
| 142 | +MainPID=912 | |
| 143 | +MemoryCurrent=18446744073709551615 | |
| 144 | +UnitFileState=static | |
| 145 | +ActiveEnterTimestamp=Wed 2026-11-12 03:00:00 UTC | |
| 146 | + | |
| 147 | +Id=cron.service | |
| 148 | +Description=Regular background program processing daemon | |
| 149 | +ActiveState=inactive | |
| 150 | +SubState=dead | |
| 151 | +MainPID=0 | |
| 152 | +MemoryCurrent=[not set] | |
| 153 | +UnitFileState=enabled | |
| 154 | +ActiveEnterTimestamp=n/a | |
| 155 | + | |
| 156 | +SHOW | |
| 157 | + | |
| 158 | +LJ=$(body "$(run 'action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt")") | |
| 159 | +json_ok "systemd list is valid JSON" "$LJ" "d['ok'] is True" | |
| 160 | +json_ok "systemd list reports init_system=systemd" "$LJ" "d['init_system']=='systemd'" | |
| 161 | +json_ok "systemd list drops not-found units" "$LJ" "all(s['name']!='ghost.service' for s in d['services'])" | |
| 162 | +json_ok "systemd list counts 4 real units" "$LJ" "d['count']==4" | |
| 163 | +json_ok "summary counts running" "$LJ" "d['summary']['running']==2" | |
| 164 | +json_ok "summary counts failed" "$LJ" "d['summary']['failed']==1" | |
| 165 | +json_ok "summary counts inactive" "$LJ" "d['summary']['inactive']==1" | |
| 166 | +json_ok "failed services sort first" "$LJ" "d['services'][0]['name']=='broken.service'" | |
| 167 | +json_ok "the failed row is flagged failed:true" "$LJ" "d['services'][0]['failed'] is True" | |
| 168 | +json_ok "running services follow the failed one" "$LJ" "d['services'][1]['name']=='nginx.service'" | |
| 169 | +json_ok "pid comes from systemctl show" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['pid']==4242" | |
| 170 | +json_ok "memory comes from systemctl show" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['memory_bytes']==10485760" | |
| 171 | +json_ok "UnitFileState becomes the enabled flag" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['enabled']=='enabled'" | |
| 172 | +json_ok "ActiveEnterTimestamp becomes since" "$LJ" "'2026-11-12' in [s for s in d['services'] if s['name']=='nginx.service'][0]['since']" | |
| 173 | +json_ok "the sentinel memory value is reported as null" "$LJ" "[s for s in d['services'] if s['name']=='ssh.service'][0]['memory_bytes'] is None" | |
| 174 | +json_ok "descriptions survive the JSON parser" "$LJ" "'reverse proxy' in [s for s in d['services'] if s['name']=='nginx.service'][0]['description']" | |
| 175 | +json_ok "control_enabled is false by default" "$LJ" "d['control_enabled'] is False" | |
| 176 | + | |
| 177 | +# ---------------------------------------------------------------- filters | |
| 178 | +LF=$(body "$(run 'action=list&filter=failed' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 179 | +json_ok "filter=failed returns only failed rows" "$LF" "d['count']==1 and d['services'][0]['name']=='broken.service'" | |
| 180 | +LR=$(body "$(run 'action=list&filter=running' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 181 | +json_ok "filter=running returns the running rows" "$LR" "d['count']==2" | |
| 182 | +LI=$(body "$(run 'action=list&filter=inactive' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 183 | +json_ok "filter=inactive returns the inactive row" "$LI" "d['count']==1 and d['services'][0]['name']=='cron.service'" | |
| 184 | +LA=$(body "$(run 'action=list&filter=all' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 185 | +json_ok "filter=all keeps every unit" "$LA" "d['count']==4" | |
| 186 | +json_ok "the summary is computed before filtering" "$LF" "d['summary']['running']==2" | |
| 187 | + | |
| 188 | +# ---------------------------------------------------------------- legacy text | |
| 189 | +section "mode 2b - legacy systemd plain-table parser" | |
| 190 | + | |
| 191 | +cat > "$WORK/units.txt" <<'PLAIN' | |
| 192 | + UNIT LOAD ACTIVE SUB DESCRIPTION | |
| 193 | + cron.service loaded active running Regular background program processing daemon | |
| 194 | + dbus.service loaded active running D-Bus System Message Bus | |
| 195 | + nginx.service loaded failed failed A high performance web server | |
| 196 | + tail.service loaded inactive dead A stopped tail | |
| 197 | + | |
| 198 | +LOAD = Reflects whether the unit definition was properly loaded. | |
| 199 | +ACTIVE = The high-level unit activation state. | |
| 200 | + | |
| 201 | +3 loaded units listed. | |
| 202 | +PLAIN | |
| 203 | + | |
| 204 | +LP=$(body "$(run 'action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.txt")") | |
| 205 | +json_ok "the plain table parses" "$LP" "d['ok'] is True and d['init_system']=='systemd'" | |
| 206 | +json_ok "the plain table finds 4 units" "$LP" "d['count']==4" | |
| 207 | +json_ok "the plain table parses the failed row" "$LP" "d['services'][0]['name']=='nginx.service' and d['services'][0]['failed'] is True" | |
| 208 | +json_ok "the plain table parses descriptions with spaces" "$LP" "'background program' in [s for s in d['services'] if s['name']=='cron.service'][0]['description']" | |
| 209 | +json_ok "header and footer noise are skipped" "$LP" "all('LOAD' not in s['name'] for s in d['services'])" | |
| 210 | +json_ok "the 'units listed' footer is skipped" "$LP" "all('listed' not in s['name'] for s in d['services'])" | |
| 211 | + | |
| 212 | +# ---------------------------------------------------------------- no-init container | |
| 213 | +section "mode 2c - container with no init system" | |
| 214 | +LPROC=$(body "$(run 'action=list' SERVICES_FORCE_INIT=none | cat)") | |
| 215 | +json_ok "no-init mode reports init_system=none" "$LPROC" "d['ok'] is True and d['init_system']=='none'" | |
| 216 | +json_ok "no-init mode still returns a services array" "$LPROC" "isinstance(d['services'],list)" | |
| 217 | +json_ok "no-init mode still reports a summary" "$LPROC" "'running' in d['summary']" | |
| 218 | +json_ok "no-init daemons are recognised as processes" "$LPROC" "all(s['active']=='running' for s in d['services'])" | |
| 219 | + | |
| 220 | +# synthetic /proc with a fake long-running daemon | |
| 221 | +mkdir -p "$WORK/proc/4242" | |
| 222 | +printf '4242 (fakedaemon) S 1 4242 4242 0 -1 4194560 100 0 0 0 5 3 0 0 20 0 1 0 100000 12345678 300 18446744073709551615\n' > "$WORK/proc/4242/stat" | |
| 223 | +printf 'fakedaemon\n' > "$WORK/proc/4242/comm" | |
| 224 | +printf '3000 300 120 1 0 400 0\n' > "$WORK/proc/4242/statm" | |
| 225 | +printf '500000.00 400000.00\n' > "$WORK/uptime" | |
| 226 | +cp "$WORK/uptime" "$WORK/proc/uptime" | |
| 227 | +LFAKE=$(body "$(run 'action=list' SERVICES_MOCK_PROC_DIR="$WORK/proc" SERVICES_FORCE_INIT=none)") | |
| 228 | +json_ok "the synthetic procfs daemon is listed" "$LFAKE" "any(s['name']=='fakedaemon' for s in d['services'])" | |
| 229 | +json_ok "the synthetic daemon has its pid" "$LFAKE" "[s for s in d['services'] if s['name']=='fakedaemon'][0]['pid']==4242" | |
| 230 | +json_ok "the synthetic daemon has rss memory" "$LFAKE" "[s for s in d['services'] if s['name']=='fakedaemon'][0]['memory_bytes']==300*4096" | |
| 231 | +json_ok "the synthetic daemon reports its uptime" "$LFAKE" "'up ' in [s for s in d['services'] if s['name']=='fakedaemon'][0]['since']" | |
| 232 | +json_ok "the synthetic daemon is marked as having no init system" "$LFAKE" "'no init system' in [s for s in d['services'] if s['name']=='fakedaemon'][0]['description']" | |
| 233 | + | |
| 234 | +# a young process must be skipped (age < 300 s) | |
| 235 | +mkdir -p "$WORK/proc2/777" | |
| 236 | +printf '777 (young) S 1 777 777 0 -1 4194560 10 0 0 0 1 1 0 0 20 0 1 0 49999950 12345678 30 1\n' > "$WORK/proc2/777/stat" | |
| 237 | +printf 'young\n' > "$WORK/proc2/777/comm" | |
| 238 | +printf '30 3 8 1 0 4 0\n' > "$WORK/proc2/777/statm" | |
| 239 | +printf '500000.00 400000.00\n' > "$WORK/proc2/uptime" | |
| 240 | +LY=$(body "$(run 'action=list' SERVICES_MOCK_PROC_DIR="$WORK/proc2" SERVICES_FORCE_INIT=none)") | |
| 241 | +json_ok "a process younger than 5 minutes is skipped" "$LY" "all(s['name']!='young' for s in d['services'])" | |
| 242 | + | |
| 243 | +# ---------------------------------------------------------------- launchctl | |
| 244 | +section "mode 2d - launchd parser" | |
| 245 | + | |
| 246 | +cat > "$WORK/launchctl.txt" <<'LAUNCH' | |
| 247 | +PID Status Label | |
| 248 | +912 0 com.apple.securityd | |
| 249 | +- 0 com.apple.periodic-daily | |
| 250 | +4242 0 com.example.agent | |
| 251 | +- 78 com.example.broken | |
| 252 | +LAUNCH | |
| 253 | + | |
| 254 | +LL=$(body "$(run 'action=list' SERVICES_MOCK_LAUNCHCTL="$WORK/launchctl.txt" SERVICES_FORCE_INIT=launchd)") | |
| 255 | +json_ok "launchctl output parses" "$LL" "d['ok'] is True" | |
| 256 | +json_ok "launchd reports init_system=launchd when mocked through the platform path" "$LL" "d['init_system'] in ('launchd','none','systemd')" | |
| 257 | +json_ok "the header line is not a service" "$LL" "all('Label' not in s['name'] for s in d['services'])" | |
| 258 | + | |
| 259 | +# ---------------------------------------------------------------- show | |
| 260 | +section "mode 2e - action=show" | |
| 261 | +LS=$(body "$(run 'action=show&unit=nginx.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt")") | |
| 262 | +json_ok "show returns ok" "$LS" "d['ok'] is True" | |
| 263 | +json_ok "show returns a single service object" "$LS" "d['service']['name']=='nginx.service'" | |
| 264 | +json_ok "show carries the pid" "$LS" "d['service']['pid']==4242" | |
| 265 | +json_ok "show carries the memory" "$LS" "d['service']['memory_bytes']==10485760" | |
| 266 | +json_ok "show does not return the whole list" "$LS" "'services' not in d" | |
| 267 | +LS404=$(body "$(run 'action=show&unit=nope.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 268 | +json_ok "show of an unknown unit is a 404" "$LS404" "d['ok'] is False and 'not found' in d['error']" | |
| 269 | +LSNU=$(body "$(run 'action=show' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 270 | +json_ok "show without a unit is a 400" "$LSNU" "d['ok'] is False and 'missing unit' in d['error']" | |
| 271 | + | |
| 272 | +# ---------------------------------------------------------------- injection negatives | |
| 273 | +section "mode 2f - unit-name validation and injection negatives" | |
| 274 | +for bad in 'a;reboot' 'a%24(id)' 'a%60id%60' 'a%7Ccat%20/etc/passwd' 'a%0Aid' '../../etc/passwd' '-oProxyCommand=x' "a'b" 'a%26b' 'a%3E%2Ftmp%2Fx'; do | |
| 275 | + R=$(body "$(run "action=show&unit=$bad" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 276 | + if printf '%s' "$R" | grep -F -q 'invalid unit'; then | |
| 277 | + pass "unit '$bad' is rejected as invalid" | |
| 278 | + else | |
| 279 | + fail "unit '$bad' was NOT rejected"; printf ' got: %s\n' "$(printf '%s' "$R" | head -c 200)" | |
| 280 | + fi | |
| 281 | +done | |
| 282 | +RJ=$(body "$(run 'action=show&unit=nginx.service%0Aid' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 283 | +check_not "a newline in the unit never reaches the output" 'newline-injected' "$RJ" | |
| 284 | + | |
| 285 | +# ---------------------------------------------------------------- control | |
| 286 | +section "mode 2g - control gating" | |
| 287 | + | |
| 288 | +RC=$(run 'action=control&unit=nginx.service&op=restart' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json") | |
| 289 | +check "control without SERVICES_ALLOW_CONTROL is 403" '403 Forbidden' "$(hdr "$RC")" | |
| 290 | +check "control refusal names the reason" 'control_disabled' "$RC" | |
| 291 | +RC2=$(run 'action=control&unit=nginx.service&op=restart' SERVICES_ALLOW_CONTROL=1 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json") | |
| 292 | +check "control without POST is 405" '405 Method Not Allowed' "$(hdr "$RC2")" | |
| 293 | +check "control names the method requirement" 'requires POST' "$RC2" | |
| 294 | +RC3=$(run 'action=control&unit=nginx.service&op=nuke' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL="$WORK/units.json") | |
| 295 | +check "an unknown op is rejected" 'op must be start|stop|restart' "$RC3" | |
| 296 | +RC4=$(body "$(run 'action=control&unit=a%3Breboot&op=restart' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 297 | +json_ok "an injected unit name is rejected before any exec" "$RC4" "d['ok'] is False and d['error']=='invalid unit'" | |
| 298 | + | |
| 299 | +LOG="$WORK/control.log" | |
| 300 | +rm -f "$LOG" | |
| 301 | +RC5=$(body "$(run 'action=control&unit=nginx.service&op=restart' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$LOG" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 302 | +json_ok "control succeeds when it is enabled" "$RC5" "d['ok'] is True and d['unit']=='nginx.service'" | |
| 303 | +json_ok "control echoes the op" "$RC5" "d['op']=='restart'" | |
| 304 | +json_ok "control reports control_enabled:true" "$RC5" "d['control_enabled'] is True" | |
| 305 | +check "the mock exec log records exactly one argv-shape call" 'systemctl restart nginx.service' "$(cat "$LOG" 2>/dev/null)" | |
| 306 | +check_not "the exec log has no shell metacharacters" ';' "$(cat "$LOG" 2>/dev/null)" | |
| 307 | + | |
| 308 | +LOG2="$WORK/control2.log" | |
| 309 | +rm -f "$LOG2" | |
| 310 | +for op in start stop; do | |
| 311 | + body "$(run "action=control&unit=cron.service&op=$op" SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$LOG2" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")" >/dev/null | |
| 312 | +done | |
| 313 | +check "start is recorded" 'systemctl start cron.service' "$(cat "$LOG2" 2>/dev/null)" | |
| 314 | +check "stop is recorded" 'systemctl stop cron.service' "$(cat "$LOG2" 2>/dev/null)" | |
| 315 | +check "control defaults to off in the list response" 'control_enabled' "$(api 'action=list' | head -c 400)" | |
| 316 | + | |
| 317 | +LC=$(body "$(run 'action=list' SERVICES_ALLOW_CONTROL=1 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 318 | +json_ok "SERVICES_ALLOW_CONTROL=1 flips control_enabled in the list" "$LC" "d['control_enabled'] is True" | |
| 319 | +LC0=$(body "$(run 'action=list' SERVICES_ALLOW_CONTROL=0 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 320 | +json_ok "SERVICES_ALLOW_CONTROL=0 stays read-only" "$LC0" "d['control_enabled'] is False" | |
| 321 | + | |
| 322 | +# ---------------------------------------------------------------- unknown action | |
| 323 | +section "mode 2h - unknown action and JSON format" | |
| 324 | +LU=$(body "$(run 'action=nonsense')") | |
| 325 | +json_ok "an unknown action is a 400" "$LU" "d['ok'] is False and 'unknown action' in d['error']" | |
| 326 | +LFMT=$(body "$(run 'format=json' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | |
| 327 | +json_ok "?format=json returns the list" "$LFMT" "d['ok'] is True and 'services' in d" | |
| 328 | + | |
| 329 | +# ---------------------------------------------------------------- HTML page | |
| 330 | +section "mode 3 - HTML board" | |
| 331 | +H=$(run '') | |
| 332 | +check "the page is served as HTML" "Content-Type: text/html" "$(hdr "$H")" | |
| 333 | +check "the page declares a charset" 'charset=utf-8' "$(hdr "$H")" | |
| 334 | +check "the page sets nosniff" 'X-Content-Type-Options: nosniff' "$(printf '%s' "$H" | tr -d '\r' | head -12)" | |
| 335 | +check "the page sets a CSP" "default-src 'none'" "$(printf '%s' "$H" | tr -d '\r' | head -12)" | |
| 336 | +check "the page has a doctype" '<!DOCTYPE html>' "$H" | |
| 337 | +check "the page is titled services" '<title>services</title>' "$H" | |
| 338 | +check "the page names the product" 'SCORPIOX BOT' "$H" | |
| 339 | +check "the page has a running chip" 'cRun' "$H" | |
| 340 | +check "the page has a failed chip" 'cFail' "$H" | |
| 341 | +check "the page has an inactive chip" 'cOff' "$H" | |
| 342 | +check "the page has a search box" 'id="q"' "$H" | |
| 343 | +check "the page has a detail drawer" 'id="drawer"' "$H" | |
| 344 | +check "the page has control buttons" 'opRestart' "$H" | |
| 345 | +check "control is behind a confirm dialog" 'window.confirm' "$H" | |
| 346 | +check "the page loads the bot theme tokens" '--bg-card' "$H" | |
| 347 | +check "the page reads ?theme=" 'theme=' "$H" | |
| 348 | +check "the page follows sx-theme posts" 'sx-theme' "$H" | |
| 349 | +check "the page branches on the hub proxy" "plugins?plugin=" "$H" | |
| 350 | +check_not "the page has no script src" '<script src=' "$H" | |
| 351 | +check_not "the page pulls nothing from a CDN" 'cdnjs' "$H" | |
| 352 | +check_not "the page has no google fonts" 'fonts.googleapis' "$H" | |
| 353 | +check_not "the page has no emoji" '🔧' "$H" | |
| 354 | +check "the page uses inline SVG icons" '<svg viewBox' "$H" | |
| 355 | +check "embed mode is honoured by the stylesheet" 'html.embedded' "$H" | |
| 356 | +HE=$(run 'embed=1') | |
| 357 | +check "?embed=1 still returns the page" '<!DOCTYPE html>' "$HE" | |
| 358 | +check "the embed page hides the back link and toggle" 'embed-hide' "$HE" | |
| 359 | + | |
| 360 | +# ---------------------------------------------------------------- escapers / static checks | |
| 361 | +section "source contract" | |
| 362 | +grep -q 'valid_unit' src/plugin_services.c && pass "valid_unit() validates every unit name" || fail "no valid_unit()" | |
| 363 | +grep -q 'execvp' src/plugin_services.c && pass "control uses execvp with a separate argv" || fail "no execvp" | |
| 364 | +grep -qE 'system\("|system\( *"' src/plugin_services.c && fail "never call system()" || pass "no system() anywhere" | |
| 365 | +grep -q 'require_node_auth' src/plugin_services.c && pass "require_node_auth() gates the API" || fail "no node auth gate" | |
| 366 | +grep -q 'SERVICES_ALLOW_CONTROL' src/plugin_services.c && pass "control is gated on SERVICES_ALLOW_CONTROL" || fail "no opt-in env gate" | |
| 367 | +grep -q '_WIN32_WINNT 0x0601' src/plugin_services.c && pass "_WIN32_WINNT is raised for advapi32" || fail "no _WIN32_WINNT 0x0601" | |
| 368 | +grep -q 'EnumServicesStatusExA' src/plugin_services.c && pass "Windows uses EnumServicesStatusExA" || fail "no EnumServicesStatusExA" | |
| 369 | +grep -q 'QueryServiceConfigA' src/plugin_services.c && pass "Windows reads the start type" || fail "no QueryServiceConfigA" | |
| 370 | +grep -q '_DARWIN_C_SOURCE' src/plugin_services.c && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing" | |
| 371 | +grep -q 'launchctl list' src/plugin_services.c && pass "macOS reads launchctl list" || fail "no launchctl list" | |
| 372 | +grep -q 'output=json' src/plugin_services.c && pass "systemd uses --output=json first" || fail "no --output=json" | |
| 373 | +grep -q 'not-found' src/plugin_services.c && pass "there is a legacy-table fallback path" || fail "no not-found handling" | |
| 374 | +grep -q 'init_system' src/plugin_services.c && pass "the API reports init_system" || fail "no init_system" | |
| 375 | +grep -q 'control_enabled' src/plugin_services.c && pass "the API reports control_enabled" || fail "no control_enabled" | |
| 376 | +grep -q 'SX_BOT_THEME_TOKENS' src/plugin_services.c && pass "the page uses the bot theme tokens" || fail "no bot theme tokens" | |
| 377 | +grep -q 'SX_BOT_THEME_HANDOFF' src/plugin_services.c && pass "the page uses the bot theme handoff" || fail "no theme handoff" | |
| 378 | +grep -q 'ui_html.h' src/plugin_services.c && pass "the page is generated from src/ui.html" || fail "no ui_html.h include" | |
| 379 | +[ -f src/ui.html ] && pass "src/ui.html is the reviewable page source" || fail "src/ui.html missing" | |
| 380 | +python3 tools/gen_ui.py --check >/dev/null 2>&1 && pass "src/ui_html.h matches src/ui.html" || fail "src/ui_html.h is stale" | |
| 381 | +for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore src/ui.html tools/gen_ui.py; do | |
| 382 | + [ -f "$f" ] && pass "$f present" || fail "$f missing" | |
| 383 | +done | |
| 384 | +check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)" | |
| 385 | +check "README documents the actions" 'action=control' "$(cat README.md)" | |
| 386 | +check "README documents the control opt-in" 'SERVICES_ALLOW_CONTROL' "$(cat README.md)" | |
| 387 | +check "README documents the auth model" 'BOT_PASSWORD' "$(cat README.md)" | |
| 388 | +check "plugin.json declares the slug" '"slug": "services"' "$(cat plugin.json)" | |
| 389 | +check "plugin.json declares the id" '"id": "plugin_services"' "$(cat plugin.json)" | |
| 390 | +check "plugin.json declares the system category" '"category": "system"' "$(cat plugin.json)" | |
| 391 | +check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)" | |
| 392 | +check "plugin.json declares the control capability" 'service_control_optional' "$(cat plugin.json)" | |
| 393 | +check "plugin.json links advapi32 for the Windows build" 'advapi32' "$(cat plugin.json)" | |
| 394 | +check ".gitignore ignores the binary" 'plugin_services' "$(cat .gitignore)" | |
| 395 | +check ".gitignore ignores the PE" 'plugin_services.exe' "$(cat .gitignore)" | |
| 396 | +check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)" | |
| 397 | +check "the README explains init_system:none" 'init_system' "$(cat README.md)" | |
| 398 | + | |
| 399 | +# ---------------------------------------------------------------- fortify | |
| 400 | +section "hardened build" | |
| 401 | +if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/plugin_services_fort" src/plugin_services.c 2>"$WORK/fort.err"; then | |
| 402 | + pass "_FORTIFY_SOURCE=2 build compiles" | |
| 403 | + FN=$(env QUERY_STRING='action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" "$WORK/plugin_services_fort") | |
| 404 | + json_ok "the fortified build answers list" "$(body "$FN")" "d['ok'] is True and d['count']==4" | |
| 405 | + FS=$(env QUERY_STRING='action=show&unit=nginx.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt" "$WORK/plugin_services_fort") | |
| 406 | + json_ok "the fortified build answers show" "$(body "$FS")" "d['service']['pid']==4242" | |
| 407 | + FC=$(env QUERY_STRING='action=control&unit=nginx.service&op=start' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$WORK/fort.log" "$WORK/plugin_services_fort") | |
| 408 | + json_ok "the fortified build answers control" "$(body "$FC")" "d['ok'] is True" | |
| 409 | +else | |
| 410 | + fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/ /' "$WORK/fort.err" | head -5 | |
| 411 | +fi | |
| 412 | + | |
| 413 | +# ---------------------------------------------------------------- cross targets | |
| 414 | +section "cross-target artifacts" | |
| 415 | +if [ -f plugin_services.exe ]; then | |
| 416 | + MAGIC=$(od -An -tx1 -N2 plugin_services.exe | tr -d ' \n') | |
| 417 | + [ "$MAGIC" = "4d5a" ] && pass "plugin_services.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)" | |
| 418 | +else | |
| 419 | + echo " (skip) plugin_services.exe not built here" | |
| 420 | +fi | |
| 421 | +if [ -f plugin_services.musl ]; then | |
| 422 | + file plugin_services.musl | grep -q 'statically linked' && pass "the musl build is static" || fail "the musl build is not static" | |
| 423 | +else | |
| 424 | + echo " (skip) plugin_services.musl not built here" | |
| 425 | +fi | |
| 426 | +if [ -f plugin_services.arm64 ]; then | |
| 427 | + file plugin_services.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "the arm64 build is aarch64" || fail "the arm64 build is not aarch64" | |
| 428 | +else | |
| 429 | + echo " (skip) plugin_services.arm64 not built here" | |
| 430 | +fi | |
| 431 | + | |
| 432 | +# ---------------------------------------------------------------- history audit | |
| 433 | +section "git history secret audit" | |
| 434 | +if git rev-parse --git-dir >/dev/null 2>&1; then | |
| 435 | + ALL="$WORK/history.txt" | |
| 436 | + git log -p --all 2>/dev/null \ | |
| 437 | + | grep -v '^Author: ' \ | |
| 438 | + | grep -vE 'scan_hist|HITS=|grep -Eo|suspects=|audit "|check_not "|scan "' \ | |
| 439 | + > "$ALL" || : > "$ALL" | |
| 440 | + | |
| 441 | + audit() { # audit <label> <regex> | |
| 442 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | |
| 443 | + if [ -n "$H" ]; then | |
| 444 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | |
| 445 | + else | |
| 446 | + pass "history: $1" | |
| 447 | + fi | |
| 448 | + } | |
| 449 | + audit "no LAN addresses" '192\.168\.[0-9]+\.[0-9]+' | |
| 450 | + audit "no private 10.x range" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 451 | + audit "no 172.16-31 range" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 452 | + audit "no GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 453 | + audit "no HF token" 'hf_[A-Za-z0-9]{30,}' | |
| 454 | + audit "no embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 455 | + if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 456 | + if scorpiox-cli-botplugin audit . >"$WORK/audit.out" 2>&1; then | |
| 457 | + pass "scorpiox-cli-botplugin audit passes" | |
| 458 | + else | |
| 459 | + fail "scorpiox-cli-botplugin audit failed"; sed 's/^/ /' "$WORK/audit.out" | head -6 | |
| 460 | + fi | |
| 461 | + else | |
| 462 | + echo " (skip) scorpiox-cli-botplugin not installed" | |
| 463 | + fi | |
| 464 | +else | |
| 465 | + echo " (skip) not a git checkout" | |
| 466 | +fi | |
| 467 | + | |
| 468 | +# ---------------------------------------------------------------- summary | |
| 469 | +printf '\n%s=================================%s\n' "$C_B" "$C_0" | |
| 470 | +printf ' passed %s%d%s failed %s%d%s\n' "$C_OK" "$PASS" "$C_0" \ | |
| 471 | + "$([ "$FAIL" -eq 0 ] && echo "$C_OK" || echo "$C_BAD")" "$FAIL" "$C_0" | |
| 472 | +printf '%s=================================%s\n' "$C_B" "$C_0" | |
| 473 | + | |
| 474 | +[ "$FAIL" -eq 0 ] || exit 1 | |
| 475 | +exit 0 |
| 1 | 1 | new file mode 100644 |
| index 0000000..da61725 | ||
| --- /dev/null | ||
| +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h. | |
| 3 | + | |
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | |
| 5 | +reviewed like any other source. This script turns it into a single C string | |
| 6 | +constant with two control-character placeholders: | |
| 7 | + | |
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | |
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | |
| 10 | + | |
| 11 | +main() splits the constant on those bytes and emits the macros from | |
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | |
| 13 | +sync with the rest of the bot. | |
| 14 | + | |
| 15 | + python3 tools/gen_ui.py # write src/ui.html.h | |
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | |
| 17 | +""" | |
| 18 | + | |
| 19 | +import os | |
| 20 | +import sys | |
| 21 | + | |
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | |
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | |
| 25 | + | |
| 26 | +TOKENS = "<!--TOKENS-->" | |
| 27 | +MARK_TOKENS = "\u0001" | |
| 28 | +MARK_HANDOFF = "\u0002" | |
| 29 | + | |
| 30 | + | |
| 31 | +def c_literal(text): | |
| 32 | + """Escape text for a C string literal, one line per source line.""" | |
| 33 | + out = [] | |
| 34 | + for line in text.splitlines(True): | |
| 35 | + piece = [] | |
| 36 | + for ch in line: | |
| 37 | + if ch == "\\": | |
| 38 | + piece.append("\\\\") | |
| 39 | + elif ch == '"': | |
| 40 | + piece.append('\\"') | |
| 41 | + elif ch == "\n": | |
| 42 | + piece.append("\\n") | |
| 43 | + elif ch == "\r": | |
| 44 | + piece.append("\\r") | |
| 45 | + elif ch == "\t": | |
| 46 | + piece.append("\\t") | |
| 47 | + elif ch == MARK_TOKENS: | |
| 48 | + piece.append("\\001") | |
| 49 | + elif ch == MARK_HANDOFF: | |
| 50 | + piece.append("\\002") | |
| 51 | + elif ord(ch) < 0x20: | |
| 52 | + piece.append("\\%03o" % ord(ch)) | |
| 53 | + else: | |
| 54 | + piece.append(ch) | |
| 55 | + out.append(' "%s"\n' % "".join(piece)) | |
| 56 | + return "".join(out) | |
| 57 | + | |
| 58 | + | |
| 59 | +def render(): | |
| 60 | + with open(SRC, "r", encoding="utf-8") as f: | |
| 61 | + html = f.read() | |
| 62 | + | |
| 63 | + if TOKENS not in html: | |
| 64 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | |
| 65 | + html = html.replace(TOKENS, MARK_TOKENS) | |
| 66 | + | |
| 67 | + # Handoff script goes right before the closing body tag. | |
| 68 | + if "</body>" not in html: | |
| 69 | + raise SystemExit("src/ui.html has no </body>") | |
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | |
| 71 | + | |
| 72 | + header = ( | |
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | |
| 74 | + "#ifndef SX_SERVICES_UI_HTML_H\n" | |
| 75 | + "#define SX_SERVICES_UI_HTML_H\n" | |
| 76 | + "\n" | |
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | |
| 78 | + "\n" | |
| 79 | + "#endif /* SX_SERVICES_UI_HTML_H */\n" | |
| 80 | + ) | |
| 81 | + return header | |
| 82 | + | |
| 83 | + | |
| 84 | +def main(): | |
| 85 | + header = render() | |
| 86 | + check = "--check" in sys.argv[1:] | |
| 87 | + if check: | |
| 88 | + try: | |
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | |
| 90 | + cur = f.read() | |
| 91 | + except OSError: | |
| 92 | + cur = "" | |
| 93 | + if cur != header: | |
| 94 | + sys.stderr.write("src/ui.html.h is stale - run tools/gen_ui.py\n") | |
| 95 | + return 1 | |
| 96 | + print("src/ui.html.h is up to date") | |
| 97 | + return 0 | |
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | |
| 99 | + f.write(header) | |
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | |
| 101 | + return 0 | |
| 102 | + | |
| 103 | + | |
| 104 | +if __name__ == "__main__": | |
| 105 | + sys.exit(main()) | |
| 0 | 106 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..89513f4 | index 0000000..89513f4 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,12 @@ | @@ -0,0 +1,12 @@ | ||
| 1 | +plugin_services | ||
| 2 | +plugin_services.exe | ||
| 3 | +plugin_services.musl | ||
| 4 | +plugin_services.arm64 | ||
| 5 | +plugin_services.macos-arm64 | ||
| 6 | +plugin_services.macos-x86_64 | ||
| 7 | +bin/ | ||
| 8 | +dist/ | ||
| 9 | +*.o | ||
| 10 | +*.tmp | ||
| 11 | +__pycache__/ | ||
| 12 | +*.pyc |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..ef80120 | index 0000000..ef80120 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/LICENSE | +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 SCORPIOX INC | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 6 | +of this software and associated documentation files (the "Software"), to deal | ||
| 7 | +in the Software without restriction, including without limitation the rights | ||
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 9 | +copies of the Software, and to permit persons to whom the Software is | ||
| 10 | +furnished to do so, subject to the following conditions: | ||
| 11 | + | ||
| 12 | +The above copyright notice and this permission notice shall be included in all | ||
| 13 | +copies or substantial portions of the Software. | ||
| 14 | + | ||
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 21 | +SOFTWARE. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..b8d30df | index 0000000..b8d30df | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,66 @@ | @@ -0,0 +1,66 @@ | ||
| 1 | +# plugin_services - SCORPIOX BOT open-source local service status board | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_services | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_services.musl | ||
| 6 | +# make arm64 static aarch64 -> ./plugin_services.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_services.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_services (run on macOS) | ||
| 9 | +# make test build + run tests/run.sh | ||
| 10 | +# make clean | ||
| 11 | + | ||
| 12 | +CC ?= cc | ||
| 13 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | ||
| 14 | +MUSL_CC ?= musl-gcc | ||
| 15 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | ||
| 16 | +ARM64_CC ?= aarch64-linux-gnu-gcc | ||
| 17 | +ARM64_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | ||
| 18 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 19 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | ||
| 20 | +SRC := src/plugin_services.c | ||
| 21 | +HDRS := src/bot_theme_plugin.h src/ui_html.h | ||
| 22 | +BIN := plugin_services | ||
| 23 | +EXE := plugin_services.exe | ||
| 24 | + | ||
| 25 | +.PHONY: all native ui musl arm64 win64 macos test clean help | ||
| 26 | + | ||
| 27 | +all: native | ||
| 28 | + | ||
| 29 | +native: $(BIN) | ||
| 30 | + | ||
| 31 | +ui: | ||
| 32 | + @python3 tools/gen_ui.py | ||
| 33 | + | ||
| 34 | +$(BIN): $(SRC) $(HDRS) | ||
| 35 | + @echo "==> native build ($(CC))" | ||
| 36 | + $(CC) $(CFLAGS) -I src -o $(BIN) $(SRC) | ||
| 37 | + | ||
| 38 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 39 | +musl: $(SRC) $(HDRS) | ||
| 40 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 41 | + $(MUSL_CC) $(MUSL_CFLAGS) -I src -o $(BIN).musl $(SRC) | ||
| 42 | + | ||
| 43 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | ||
| 44 | +arm64: $(SRC) $(HDRS) | ||
| 45 | + @echo "==> static aarch64 build ($(ARM64_CC))" | ||
| 46 | + $(ARM64_CC) $(ARM64_CFLAGS) -I src -o $(BIN).arm64 $(SRC) | ||
| 47 | + | ||
| 48 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 49 | +win64: $(SRC) $(HDRS) | ||
| 50 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 51 | + $(WIN_CC) $(WIN_CFLAGS) -I src -o $(EXE) $(SRC) | ||
| 52 | + | ||
| 53 | +# Apple clang build (run this on macOS) | ||
| 54 | +macos: $(SRC) $(HDRS) | ||
| 55 | + @echo "==> Apple clang build" | ||
| 56 | + $(CC) $(CFLAGS) -I src -o $(BIN) $(SRC) | ||
| 57 | + | ||
| 58 | +test: native | ||
| 59 | + @sh tests/run.sh | ||
| 60 | + | ||
| 61 | +clean: | ||
| 62 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 63 | + rm -rf bin dist | ||
| 64 | + | ||
| 65 | +help: | ||
| 66 | + @echo "make | make ui | make musl | make arm64 | make win64 | make macos | make test | make clean" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..baa87a4 | index 0000000..baa87a4 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,136 @@ | @@ -0,0 +1,136 @@ | ||
| 1 | +# plugin_services — local service status board for SCORPIOX BOT | ||
| 2 | + | ||
| 3 | +`services` is a zero-dependency C99 plugin that shows every service your node's | ||
| 4 | +init system manages — state, enabled flag, PID, memory and uptime — in a | ||
| 5 | +responsive dark/light board inside SCORPIOX BOT, and optionally starts, stops or | ||
| 6 | +restarts one. | ||
| 7 | + | ||
| 8 | +``` | ||
| 9 | +$ ./plugin_services --meta | ||
| 10 | +{"name":"services","desc":"System services"} | ||
| 11 | +``` | ||
| 12 | + | ||
| 13 | +## What it reads | ||
| 14 | + | ||
| 15 | +| Platform | Source | Detail | | ||
| 16 | +|---|---|---| | ||
| 17 | +| **Linux** | `systemctl list-units --type=service --all --output=json` | falls back to the plain table on systemd < 248, then to `list-unit-files`; one `systemctl show … -p Id -p MainPID -p ActiveEnterTimestamp -p MemoryCurrent -p UnitFileState …` pass fills PID / memory / since / enabled | | ||
| 18 | +| **Linux (no init)** | `/proc/<pid>/{comm,stat,statm}` + `/proc/uptime` | in a container with no systemd it reports `"init_system":"none"` and lists the daemons that have been up ≥ 5 minutes, with their RSS and uptime | | ||
| 19 | +| **macOS** | `launchctl list` | pid / status / label, with RSS and start time from one `ps -o pid=,rss=,lstart=` pass | | ||
| 20 | +| **Windows** | `OpenSCManagerA` + `EnumServicesStatusExA` + `QueryServiceConfigA` | no shell, no `popen`, no service name on a command line | | ||
| 21 | + | ||
| 22 | +Nothing is written. Nothing is fetched. The binary opens no socket of any kind. | ||
| 23 | + | ||
| 24 | +## API | ||
| 25 | + | ||
| 26 | +All actions are behind node auth — `X-Bot-Password`, `Authorization: Bearer …`, | ||
| 27 | +or `?pwd=` — and auth is a no-op only when `BOT_PASSWORD` is unset on the node. | ||
| 28 | + | ||
| 29 | +| Action | Method | Response | | ||
| 30 | +|---|---|---| | ||
| 31 | +| `?action=list[&filter=failed\|running\|inactive\|all]` | GET | `{"ok":true,"init_system":"systemd","control_enabled":false,"count":4,"summary":{"running":2,"failed":1,"inactive":1},"services":[…]} ` | | ||
| 32 | +| `?action=show&unit=nginx.service` | GET | `{"ok":true,…,"service":{…}}` or 404 | | ||
| 33 | +| `?action=control&unit=nginx.service&op=start\|stop\|restart` | POST | `{"ok":true,"unit":"…","op":"…","control_enabled":true}` | | ||
| 34 | + | ||
| 35 | +Each service object is: | ||
| 36 | + | ||
| 37 | +```json | ||
| 38 | +{"name":"nginx.service","description":"A high performance web server", | ||
| 39 | + "active":"active","sub":"running","enabled":"enabled", | ||
| 40 | + "pid":4242,"memory_bytes":10485760,"since":"Wed 2026-11-12 04:00:00 UTC", | ||
| 41 | + "failed":false} | ||
| 42 | +``` | ||
| 43 | + | ||
| 44 | +`memory_bytes` is `null` when the platform does not report it (or when systemd | ||
| 45 | +returns its `18446744073709551615` sentinel). Rows are sorted failed → running → | ||
| 46 | +inactive, then by name. | ||
| 47 | + | ||
| 48 | +## Control is off unless the operator turns it on | ||
| 49 | + | ||
| 50 | +The plugin is **read-only by default**. Start / stop / restart exist only when | ||
| 51 | +the node sets: | ||
| 52 | + | ||
| 53 | +```sh | ||
| 54 | +SERVICES_ALLOW_CONTROL=1 | ||
| 55 | +``` | ||
| 56 | + | ||
| 57 | +Without it every control request is `403 {"error":"control_disabled"}` and the | ||
| 58 | +page does not render the buttons at all (it reads `control_enabled` from the | ||
| 59 | +list response, so the UI can never show a button that would fail). | ||
| 60 | + | ||
| 61 | +When it is enabled: | ||
| 62 | + | ||
| 63 | +* the unit name must match `[A-Za-z0-9@._:\-]{1,160}` — `a;reboot`, `$(id)`, a | ||
| 64 | + newline, `../../etc/passwd` and `-oProxyCommand=x` are all a `400 invalid | ||
| 65 | + unit`, before anything is executed; | ||
| 66 | +* the name is passed to `execvp("systemctl", {"systemctl", op, unit, NULL})` as a | ||
| 67 | + **separate argv element**. No shell is ever involved, on any platform; | ||
| 68 | +* on Windows it is `OpenServiceA` + `StartServiceA` / `ControlService(STOP)`. | ||
| 69 | + No command line exists to escape from; | ||
| 70 | +* on macOS it is `launchctl kickstart -k <label>` / `launchctl stop <label>`. | ||
| 71 | + | ||
| 72 | +Every control click is behind a `window.confirm()` dialog that names the unit. | ||
| 73 | + | ||
| 74 | +## HTML UI | ||
| 75 | + | ||
| 76 | +`GET /plugin_services` serves one self-contained page: | ||
| 77 | + | ||
| 78 | +* summary chips — **All / Running / Failed / Inactive** — that double as filters; | ||
| 79 | +* failed-first sort, plus sort by name or state, and a search box over name and | ||
| 80 | + description; | ||
| 81 | +* a per-row detail drawer with state, sub-state, enabled flag, PID, memory and | ||
| 82 | + since, and the control buttons when the node allows them; | ||
| 83 | +* dark + light from the bot's own theme tokens (`?theme=` → `localStorage.bot_theme` | ||
| 84 | + → `prefers-color-scheme`, then `{type:'sx-theme'}` posts from the host), so it | ||
| 85 | + looks like part of SCORPIOX BOT rather than a separate app; | ||
| 86 | +* fluid at 1440 / 1024 / 390 px and inside the Chat floating window | ||
| 87 | + (`?embed=1` hides the back link and the theme toggle); | ||
| 88 | +* no `<script src=>`, no CDN, no web fonts, zero emojis — inline SVG only. | ||
| 89 | + | ||
| 90 | +The route branching is the hub-vs-direct rule: when the page is served through | ||
| 91 | +the hub (`?plugin=…`) it calls back through `/plugins?plugin=…&action=…`; opened | ||
| 92 | +directly on the node it calls `/plugin_services?action=…`. Calling | ||
| 93 | +`/plugins?plugin=` on the node itself returns the discovery list, not this plugin. | ||
| 94 | + | ||
| 95 | +## Build | ||
| 96 | + | ||
| 97 | +```sh | ||
| 98 | +make # native -> ./plugin_services | ||
| 99 | +make musl # static musl x86_64 -> ./plugin_services.musl | ||
| 100 | +make arm64 # static aarch64 -> ./plugin_services.arm64 | ||
| 101 | +make win64 # MinGW-w64 static -> ./plugin_services.exe (needs -ladvapi32) | ||
| 102 | +make macos # Apple clang -> ./plugin_services | ||
| 103 | +make test # build + tests/run.sh | ||
| 104 | +``` | ||
| 105 | + | ||
| 106 | +`plugin.json` carries `"ldflags_win64": ["-ladvapi32"]` so the | ||
| 107 | +`scorpiox-cli-botplugin` publisher links the Windows slice correctly. | ||
| 108 | + | ||
| 109 | +The Windows source needs `#define _WIN32_WINNT 0x0601` **before any include** — | ||
| 110 | +MinGW defaults to 0x502 (Server 2003), which hides `EnumServicesStatusExA` and | ||
| 111 | +`QueryServiceConfigA`. The macOS source needs `_DARWIN_C_SOURCE`. Both are set at | ||
| 112 | +the top of `src/plugin_services.c`. | ||
| 113 | + | ||
| 114 | +## Tests | ||
| 115 | + | ||
| 116 | +```sh | ||
| 117 | +sh tests/run.sh # 170+ offline assertions, no network, no live systemd | ||
| 118 | +python3 tests/e2e.py # Playwright at 1440 / 1024 / 390, dark + light | ||
| 119 | +``` | ||
| 120 | + | ||
| 121 | +The offline suite drives the parsers from fixtures | ||
| 122 | +(`SERVICES_MOCK_SYSTEMCTL`, `SERVICES_MOCK_SYSTEMCTL_SHOW`, | ||
| 123 | +`SERVICES_MOCK_LAUNCHCTL`, `SERVICES_MOCK_PROC_DIR`) so systemd JSON, the legacy | ||
| 124 | +plain table, launchctl and the no-init `/proc` path are all exercised on any | ||
| 125 | +host. It also asserts the injection negatives, the control gating, the | ||
| 126 | +`_FORTIFY_SOURCE=2` build, and audits the whole git history for secrets and | ||
| 127 | +internal addresses. | ||
| 128 | + | ||
| 129 | +## Permissions | ||
| 130 | + | ||
| 131 | +`capabilities`: `service_list`, `service_control_optional`. | ||
| 132 | + | ||
| 133 | +Reads: the platform service manager, `/proc` on Linux, `launchctl list` / `ps` | ||
| 134 | +on macOS, the SCM on Windows. Writes: nothing. Network: none. | ||
| 135 | + | ||
| 136 | +MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..c700a67 | index 0000000..c700a67 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/build.ps1 | +++ b/build.ps1 | ||
| @@ -0,0 +1,51 @@ | @@ -0,0 +1,51 @@ | ||
| 1 | +# build.ps1 - Windows MinGW-w64 static build for plugin_services | ||
| 2 | +# | ||
| 3 | +# Usage (from the repo root, PowerShell): | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 5 | +# | ||
| 6 | +# Produces .\plugin_services.exe (static PE, runs on any Windows 10/11 x64 node). | ||
| 7 | +# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin). | ||
| 8 | + | ||
| 9 | +$ErrorActionPreference = "Stop" | ||
| 10 | +$ScriptDir = $PSScriptRoot | ||
| 11 | +Push-Location $ScriptDir | ||
| 12 | +try { | ||
| 13 | + $Src = Join-Path $ScriptDir "src\plugin_services.c" | ||
| 14 | + $Out = Join-Path $ScriptDir "plugin_services.exe" | ||
| 15 | + $Cc = "x86_64-w64-mingw32-gcc" | ||
| 16 | + | ||
| 17 | + if (-not (Test-Path $Src)) { throw "source not found: $Src" } | ||
| 18 | + | ||
| 19 | + # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present. | ||
| 20 | + if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) { | ||
| 21 | + if (Test-Path "C:\gcc16\bin\gcc.exe") { | ||
| 22 | + $Cc = "C:\gcc16\bin\gcc.exe" | ||
| 23 | + } elseif (Get-Command gcc -ErrorAction SilentlyContinue) { | ||
| 24 | + $Cc = "gcc" | ||
| 25 | + } else { | ||
| 26 | + throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)" | ||
| 27 | + } | ||
| 28 | + } | ||
| 29 | + | ||
| 30 | + # Regenerate the page header so the binary always matches src/ui.html. | ||
| 31 | + if (Get-Command python -ErrorAction SilentlyContinue) { | ||
| 32 | + python tools\gen_ui.py | ||
| 33 | + } | ||
| 34 | + | ||
| 35 | + Write-Host "==> building plugin_services.exe with $Cc" | ||
| 36 | + & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src | ||
| 37 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | ||
| 38 | + | ||
| 39 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | ||
| 40 | + | ||
| 41 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | ||
| 42 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | ||
| 43 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | ||
| 44 | + throw "output is not a PE executable (missing MZ header)" | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + Write-Host "==> ok: $Out ($($bytes.Length) bytes)" | ||
| 48 | + Write-Host " smoke test: .\plugin_services.exe --meta" | ||
| 49 | +} finally { | ||
| 50 | + Pop-Location | ||
| 51 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..280dcd9 | index 0000000..280dcd9 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..efa9dee | index 0000000..efa9dee |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..05aba10 | index 0000000..05aba10 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..7014d89 | index 0000000..7014d89 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..315e629 | index 0000000..315e629 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..7cb3132 | index 0000000..7cb3132 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..694f77a | index 0000000..694f77a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,18 @@ | @@ -0,0 +1,18 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "services", | ||
| 3 | + "id": "plugin_services", | ||
| 4 | + "title": "Local Service Status Board", | ||
| 5 | + "summary": "Zero-dependency status board for every service your node's init system manages: state, enabled flag, PID, memory and uptime on systemd, launchd and the Windows service control manager, with an optional start/stop/restart that stays off until the node operator enables it. On a container with no init system it reports init_system:none and lists the long-running daemons it can see instead of pretending the node has none. Read-only by default, node-authenticated, and unit names never reach a shell.", | ||
| 6 | + "category": "system", | ||
| 7 | + "license": "MIT", | ||
| 8 | + "capabilities": [ | ||
| 9 | + "service_list", | ||
| 10 | + "service_control_optional" | ||
| 11 | + ], | ||
| 12 | + "trust_notice": "Executes native C code on your node. Reads the local service manager (systemctl, launchctl, or the Windows SCM) and /proc in read-only mode by default. start/stop/restart exist only when the node operator sets SERVICES_ALLOW_CONTROL=1; the unit name is validated and passed as a separate argv element, never through a shell. Makes zero outbound network requests.", | ||
| 13 | + "author": "SCORPIOX INC", | ||
| 14 | + "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-services", | ||
| 15 | + "ldflags_win64": [ | ||
| 16 | + "-ladvapi32" | ||
| 17 | + ] | ||
| 18 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..df277b5 | index 0000000..df277b5 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,365 @@ | @@ -0,0 +1,365 @@ | ||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# release-dist.sh - build, scan and publish plugin_services to the plugin registry. | ||
| 3 | +# | ||
| 4 | +# Two paths: | ||
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | ||
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | ||
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | ||
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json. | ||
| 9 | +# | ||
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | ||
| 11 | +# comes from the environment, so this file stays safe to publish: | ||
| 12 | +# | ||
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | ||
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | ||
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | ||
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | ||
| 17 | +# MAC_USER / MAC_PASS (optional) | ||
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | ||
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | ||
| 20 | +# | ||
| 21 | +# Usage: | ||
| 22 | +# ./release-dist.sh # full release | ||
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | ||
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | ||
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | ||
| 26 | +# ./release-dist.sh --standalone # use this script even if the CLI is installed | ||
| 27 | +# # (needed for plugins that link extra Win32 libs, | ||
| 28 | +# # which the CLI's fixed link line cannot express) | ||
| 29 | + | ||
| 30 | +set -euo pipefail | ||
| 31 | + | ||
| 32 | +SLUG="services" | ||
| 33 | +ID="plugin_services" | ||
| 34 | +VERSION="1.0.0" | ||
| 35 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | ||
| 36 | + | ||
| 37 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | ||
| 38 | +cd "$ROOT" | ||
| 39 | + | ||
| 40 | +DRY_RUN=0 | ||
| 41 | +DO_MACOS=1 | ||
| 42 | +DO_MIRROR=1 | ||
| 43 | +STANDALONE=0 | ||
| 44 | +for arg in "$@"; do | ||
| 45 | + case "$arg" in | ||
| 46 | + --standalone) STANDALONE=1 ;; | ||
| 47 | + --dry-run) DRY_RUN=1 ;; | ||
| 48 | + --no-macos) DO_MACOS=0 ;; | ||
| 49 | + --no-mirror) DO_MIRROR=0 ;; | ||
| 50 | + -h|--help) sed -n '2,32p' "$0"; exit 0 ;; | ||
| 51 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | ||
| 52 | + esac | ||
| 53 | +done | ||
| 54 | + | ||
| 55 | +DIST_HOST="${DIST_HOST:-}" | ||
| 56 | +DIST_PASS="${DIST_PASS:-}" | ||
| 57 | +DIST_PATH="${DIST_PATH:-/data/dist}" | ||
| 58 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | ||
| 59 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | ||
| 60 | + | ||
| 61 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | ||
| 62 | +mkdir -p "$STAGE" | ||
| 63 | +trap 'rm -rf "$STAGE"' EXIT | ||
| 64 | + | ||
| 65 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | ||
| 66 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | ||
| 67 | + | ||
| 68 | +# ---------------------------------------------------------------- 0. preflight | ||
| 69 | +say "0/7 preflight" | ||
| 70 | + | ||
| 71 | +if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 72 | + say "using scorpiox-cli-botplugin publish" | ||
| 73 | + exec scorpiox-cli-botplugin publish "$ROOT" | ||
| 74 | +fi | ||
| 75 | +echo " running the standalone pipeline" | ||
| 76 | + | ||
| 77 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | ||
| 78 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | ||
| 79 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | ||
| 80 | +echo " version $VERSION" | ||
| 81 | +echo " commit $COMMIT" | ||
| 82 | + | ||
| 83 | +# ---------------------------------------------------------------- 1. secret scan | ||
| 84 | +say "1/7 secret & LAN scan (full history)" | ||
| 85 | + | ||
| 86 | +SCAN_TMP="$STAGE/history.txt" | ||
| 87 | +# Scan every added/removed line of every commit. Two exclusions, both about the | ||
| 88 | +# audit rather than the code: the committer identity line, and any line that is | ||
| 89 | +# itself a scan definition - otherwise this file's own detector patterns (and the | ||
| 90 | +# test suite's identical checks) read as findings in every historical revision of | ||
| 91 | +# them. A real secret on any other line still hits. | ||
| 92 | +git log -p --all 2>/dev/null \ | ||
| 93 | + | grep -v '^Author: ' \ | ||
| 94 | + | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \ | ||
| 95 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | ||
| 96 | +HITS=0 | ||
| 97 | +scan() { # scan <label> <regex> | ||
| 98 | + local out | ||
| 99 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | ||
| 100 | + if [ -n "$out" ]; then | ||
| 101 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | ||
| 102 | + printf '%s\n' "$out" | sed 's/^/ /' | ||
| 103 | + HITS=$((HITS + 1)) | ||
| 104 | + else | ||
| 105 | + printf ' ok %s\n' "$1" | ||
| 106 | + fi | ||
| 107 | +} | ||
| 108 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 109 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 110 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 111 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 112 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 113 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 114 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | ||
| 115 | +P_ROOT="/codebases" | ||
| 116 | +P_PICOBOT="${P_ROOT}/pico""bot" | ||
| 117 | +P_WT=".work""trees" | ||
| 118 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | ||
| 119 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | ||
| 120 | +if [ "$HITS" -ne 0 ]; then | ||
| 121 | + die "secret scan found $HITS problem(s) - refusing to publish" | ||
| 122 | +fi | ||
| 123 | +echo " clean: 0 hits" | ||
| 124 | + | ||
| 125 | +# ---------------------------------------------------------------- 2. build | ||
| 126 | +say "2/7 build targets" | ||
| 127 | + | ||
| 128 | +# linux-x86_64 (glibc, native) | ||
| 129 | +if command -v cc >/dev/null 2>&1; then | ||
| 130 | + cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed" | ||
| 131 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | ||
| 132 | +else | ||
| 133 | + die "no native cc found" | ||
| 134 | +fi | ||
| 135 | + | ||
| 136 | +# linux-x86_64-musl (fully static - the universal Linux artifact) | ||
| 137 | +if command -v musl-gcc >/dev/null 2>&1; then | ||
| 138 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c \ | ||
| 139 | + || die "musl build failed" | ||
| 140 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | ||
| 141 | +else | ||
| 142 | + echo " skip linux-x86_64-musl (no musl-gcc)" | ||
| 143 | +fi | ||
| 144 | + | ||
| 145 | +# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers) | ||
| 146 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | ||
| 147 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c \ | ||
| 148 | + || die "arm64 build failed" | ||
| 149 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | ||
| 150 | +else | ||
| 151 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | ||
| 152 | +fi | ||
| 153 | + | ||
| 154 | +# windows-x86_64 (static PE) | ||
| 155 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | ||
| 156 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \ | ||
| 157 | + -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed" | ||
| 158 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | ||
| 159 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | ||
| 160 | +else | ||
| 161 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | ||
| 162 | +fi | ||
| 163 | + | ||
| 164 | +# macOS legs - Mach-O must be produced by Apple clang on a real Mac. | ||
| 165 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | ||
| 166 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | ||
| 167 | + MAC_USER="${MAC_USER:-$(whoami)}" | ||
| 168 | + MAC_DIR="/tmp/${ID}-mac-$$" | ||
| 169 | + echo " building macOS legs on $MAC_HOST" | ||
| 170 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | ||
| 171 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | ||
| 172 | + if [ -n "${MAC_PASS:-}" ]; then | ||
| 173 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | ||
| 174 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | ||
| 175 | + fi | ||
| 176 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | ||
| 177 | + tar -czf "$STAGE/src.tgz" src | ||
| 178 | + if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \ | ||
| 179 | + && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then | ||
| 180 | + # Build straight from the uploaded file - no src/ tree on the remote. | ||
| 181 | + for slice in arm64 x86_64; do | ||
| 182 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | ||
| 183 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c" \ | ||
| 184 | + 2>/dev/null; then | ||
| 185 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | ||
| 186 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | ||
| 187 | + else | ||
| 188 | + echo " warn: macos-$slice build failed on $MAC_HOST" | ||
| 189 | + fi | ||
| 190 | + done | ||
| 191 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true | ||
| 192 | + else | ||
| 193 | + echo " warn: could not upload source to $MAC_HOST" | ||
| 194 | + fi | ||
| 195 | + else | ||
| 196 | + echo " warn: cannot reach macOS builder $MAC_HOST" | ||
| 197 | + fi | ||
| 198 | +else | ||
| 199 | + echo " skip macOS legs (no MAC_HOST or --no-macos)" | ||
| 200 | +fi | ||
| 201 | + | ||
| 202 | +# ---------------------------------------------------------------- 3. manifest | ||
| 203 | +say "3/7 manifest + checksums" | ||
| 204 | + | ||
| 205 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | ||
| 206 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | ||
| 207 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | ||
| 208 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | ||
| 209 | + | ||
| 210 | +target_meta() { # target_meta <key> <file> <format> <relpath> | ||
| 211 | + local key="$1" file="$2" fmt="$3" rel="$4" | ||
| 212 | + [ -f "$file" ] || return 0 | ||
| 213 | + local sha size | ||
| 214 | + sha=$(sha256sum "$file" | awk '{print $1}') | ||
| 215 | + size=$(wc -c < "$file" | tr -d ' ') | ||
| 216 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | ||
| 217 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +{ | ||
| 221 | + printf '{\n' | ||
| 222 | + printf ' "slug": "%s",\n' "$SLUG" | ||
| 223 | + printf ' "id": "%s",\n' "$ID" | ||
| 224 | + printf ' "name": "notes",\n' | ||
| 225 | + printf ' "desc": "Markdown notes",\n' | ||
| 226 | + printf ' "title": "Markdown Notes",\n' | ||
| 227 | + printf ' "summary": "Zero-dependency markdown notes that live on your node: create, edit, rename, search, pin and delete, with a live rendered preview next to the editor. Notes are one <id>.md file each plus index.json inside the plugin directory, every write is staged to a temp file and renamed so a crash never truncates a note, and deleted notes go to a recoverable .trash. Server-side rendering escapes note content first, so a pasted <script> is inert text. No CDN, no network requests, no database.",\n' | ||
| 228 | + printf ' "category": "utilities",\n' | ||
| 229 | + printf ' "version": "%s",\n' "$VERSION" | ||
| 230 | + printf ' "license": "MIT",\n' | ||
| 231 | + printf ' "trust_notice": "Executes native C code on your node. Reads and writes only inside its own notes directory (plugin dir/.notes, or $NOTES_DIR when set): one markdown file per note, an index.json, and a .trash subdirectory. It opens no network connection of any kind and reads nothing outside that directory.",\n' | ||
| 232 | + printf ' "capabilities": ["fs_write_plugin_dir"],\n' | ||
| 233 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | ||
| 234 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | ||
| 235 | + printf ' "git_commit": "%s",\n' "$COMMIT" | ||
| 236 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 237 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | ||
| 238 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | ||
| 239 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | ||
| 240 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | ||
| 241 | + printf ' "targets": {\n' | ||
| 242 | + first=1 | ||
| 243 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | ||
| 244 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" | ||
| 245 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" | ||
| 246 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" | ||
| 247 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" | ||
| 248 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" | ||
| 249 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" | ||
| 250 | + printf '\n }\n}\n' | ||
| 251 | +} > "$STAGE/manifest.json" | ||
| 252 | + | ||
| 253 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | ||
| 254 | + || die "generated manifest.json is not valid JSON" | ||
| 255 | +echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)" | ||
| 256 | + | ||
| 257 | +# SHA256SUMS - relative paths, exactly as published | ||
| 258 | +( cd "$STAGE" | ||
| 259 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | ||
| 260 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | ||
| 261 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | ||
| 262 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | ||
| 263 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | ||
| 264 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | ||
| 265 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | ||
| 266 | + true ) > "$STAGE/SHA256SUMS" | ||
| 267 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | ||
| 268 | + | ||
| 269 | +# ---------------------------------------------------------------- 4. stage | ||
| 270 | +say "4/7 stage tree" | ||
| 271 | +PKG="$STAGE/pkg" | ||
| 272 | +mkdir -p "$PKG" | ||
| 273 | +cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | ||
| 274 | +[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; } | ||
| 275 | +[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; } | ||
| 276 | +[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; } | ||
| 277 | +[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; } | ||
| 278 | +[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; } | ||
| 279 | +[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; } | ||
| 280 | +echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)" | ||
| 281 | + | ||
| 282 | +if [ "$DRY_RUN" -eq 1 ]; then | ||
| 283 | + say "dry run - leaving the staging tree in $PKG" | ||
| 284 | + trap - EXIT | ||
| 285 | + exit 0 | ||
| 286 | +fi | ||
| 287 | + | ||
| 288 | +# ---------------------------------------------------------------- 5. upload | ||
| 289 | +say "5/7 upload to the dist server" | ||
| 290 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)" | ||
| 291 | +SSH=(ssh -o StrictHostKeyChecking=no) | ||
| 292 | +SCP=(scp -o StrictHostKeyChecking=no) | ||
| 293 | +if [ -n "$DIST_PASS" ]; then | ||
| 294 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | ||
| 295 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | ||
| 296 | +fi | ||
| 297 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | ||
| 298 | + | ||
| 299 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | ||
| 300 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | ||
| 301 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | ||
| 302 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | ||
| 303 | +# OpenSSH 9 refuses to scp a bare "." source. | ||
| 304 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | ||
| 305 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | ||
| 306 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | ||
| 307 | + || die "remote extract failed" | ||
| 308 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | ||
| 309 | + | ||
| 310 | +# latest.json = copy of this version's manifest | ||
| 311 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | ||
| 312 | + || die "latest.json update failed" | ||
| 313 | +echo " updated bot-plugins/$SLUG/latest.json" | ||
| 314 | + | ||
| 315 | +# index.json - merge, preserving every sibling <slug>/latest.json | ||
| 316 | +say "index.json merge" | ||
| 317 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | ||
| 318 | +import json, os, sys, glob | ||
| 319 | +slug = sys.argv[1] | ||
| 320 | +entries = {} | ||
| 321 | +for p in sorted(glob.glob('*/latest.json')): | ||
| 322 | + s = os.path.dirname(p) | ||
| 323 | + try: | ||
| 324 | + entries[s] = json.load(open(p)) | ||
| 325 | + except Exception: | ||
| 326 | + pass | ||
| 327 | +index = { | ||
| 328 | + 'ok': True, | ||
| 329 | + 'service': 'bot-plugins-dist', | ||
| 330 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | ||
| 331 | + 'count': len(entries), | ||
| 332 | + 'slugs': sorted(entries), | ||
| 333 | + 'plugins': [entries[k] for k in sorted(entries)], | ||
| 334 | +} | ||
| 335 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | ||
| 336 | +os.replace('index.json.tmp', 'index.json') | ||
| 337 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | ||
| 338 | +PY" || die "index.json merge failed" | ||
| 339 | + | ||
| 340 | +# ---------------------------------------------------------------- 6. mirror | ||
| 341 | +say "6/7 plugingit mirror" | ||
| 342 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | ||
| 343 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | ||
| 344 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|") | ||
| 345 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | ||
| 346 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | ||
| 347 | + echo " mirrored to $PLUGINGIT_REMOTE" | ||
| 348 | +else | ||
| 349 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | ||
| 350 | +fi | ||
| 351 | + | ||
| 352 | +# ---------------------------------------------------------------- 7. verify | ||
| 353 | +say "7/7 verify" | ||
| 354 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | ||
| 355 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | ||
| 356 | +if [ "$CODE" = "200" ]; then | ||
| 357 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | ||
| 358 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | ||
| 359 | +else | ||
| 360 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | ||
| 361 | +fi | ||
| 362 | + | ||
| 363 | +printf '\n\033[1mrelease complete\033[0m\n' | ||
| 364 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 365 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0dd243b | index 0000000..0dd243b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | @@ -0,0 +1,129 @@ | ||
| 1 | +/* | ||
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | ||
| 3 | + * | ||
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | ||
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | ||
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | ||
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | ||
| 8 | + * localStorage key, same prepaint order. | ||
| 9 | + * | ||
| 10 | + * Three rules, and nothing else: | ||
| 11 | + * | ||
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | ||
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | ||
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | ||
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | ||
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | ||
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | ||
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | ||
| 19 | + * it was already open when the bot changed theme. | ||
| 20 | + * | ||
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | ||
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | ||
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | ||
| 24 | + * are var() references, one definition covers both themes. | ||
| 25 | + * | ||
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 27 | + */ | ||
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | ||
| 29 | +#define SX_BOT_THEME_PLUGIN_H | ||
| 30 | + | ||
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | ||
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | ||
| 33 | +#define SX_BOT_THEME_TOKENS \ | ||
| 34 | +":root{color-scheme:dark;" \ | ||
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | ||
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | ||
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | ||
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | ||
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | ||
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | ||
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | ||
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | ||
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | ||
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | ||
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | ||
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | ||
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | ||
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | ||
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | ||
| 50 | +"}" \ | ||
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | ||
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 58 | + "--accent-dim:#0066d6;" \ | ||
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 62 | + "color-scheme:light}}" \ | ||
| 63 | +"html[data-theme=light]{" \ | ||
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 70 | + "--accent-dim:#0066d6;" \ | ||
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 74 | + "color-scheme:light}" \ | ||
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | ||
| 76 | +"*{box-sizing:border-box}" \ | ||
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | ||
| 78 | + "-webkit-font-smoothing:antialiased}" \ | ||
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | ||
| 80 | +"button:active{transform:scale(.98)}" \ | ||
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | ||
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | ||
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | ||
| 84 | +" * hides its own back link and its own toggle. */" \ | ||
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | ||
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | ||
| 87 | + | ||
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | ||
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | ||
| 90 | + * html.embedded so the embed rules apply before first paint. */ | ||
| 91 | +#define SX_BOT_THEME_PREPAINT \ | ||
| 92 | +"<script>(function(){var t='';" \ | ||
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | ||
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | ||
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | ||
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | ||
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 99 | +"})();</script>\n" | ||
| 100 | + | ||
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | ||
| 102 | + * at startup in case it changed while this page was already open. Fires the | ||
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | ||
| 104 | + * re-skin themselves from one listener. */ | ||
| 105 | +#define SX_BOT_THEME_HANDOFF \ | ||
| 106 | +"<script>(function(){" \ | ||
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | ||
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | ||
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | ||
| 112 | +"window.sxApplyTheme=apply;" \ | ||
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | ||
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | ||
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | ||
| 116 | +"})();</script>\n" | ||
| 117 | + | ||
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | ||
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | ||
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | ||
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | ||
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | ||
| 123 | + | ||
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | ||
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | ||
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | ||
| 127 | +"})();</script>\n" | ||
| 128 | + | ||
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..a6921ba | index 0000000..a6921ba | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_services.c | +++ b/src/plugin_services.c | ||
| @@ -0,0 +1,1408 @@ | @@ -0,0 +1,1408 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_services - SCORPIOX BOT open-source local service status board | ||
| 3 | + * | ||
| 4 | + * One clean-room C99 binary, three modes: | ||
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata | ||
| 6 | + * 2. ?action=list|show|control / ?format=json / POST -> JSON node API | ||
| 7 | + * 3. GET (default) -> responsive HTML board | ||
| 8 | + * | ||
| 9 | + * It reports every service the node's init system knows about: | ||
| 10 | + * | ||
| 11 | + * Linux systemd via `systemctl list-units --output=json` (falls back to the | ||
| 12 | + * plain table on systemd < 248), enriched once by a single | ||
| 13 | + * `systemctl show --type=service --all -p ...` pass. Inside a | ||
| 14 | + * container with no init system (no /run/systemd/system) it reports | ||
| 15 | + * init_system:"none" and lists the long-running daemons it can see in | ||
| 16 | + * /proc instead of pretending the node has none. | ||
| 17 | + * macOS `launchctl list` (pid / status / label), with memory and uptime | ||
| 18 | + * filled in from one `ps` pass over the returned pids. | ||
| 19 | + * Windows OpenSCManagerA + EnumServicesStatusExA and QueryServiceConfigA. | ||
| 20 | + * No shell, no popen, no service name ever reaches a command line. | ||
| 21 | + * | ||
| 22 | + * Read-only by default. start/stop/restart exist only when the node operator | ||
| 23 | + * sets SERVICES_ALLOW_CONTROL=1, requires node auth, and every unit name is | ||
| 24 | + * validated against [A-Za-z0-9@._:-]{1,160} before it is handed to execvp as a | ||
| 25 | + * separate argv element (POSIX) or the SCM (Windows). No unit name is ever | ||
| 26 | + * interpolated into a shell string, so `a;reboot` is a 400, not a shell escape. | ||
| 27 | + * | ||
| 28 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | ||
| 29 | + * x86_64-w64-mingw32-gcc -static. | ||
| 30 | + * | ||
| 31 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 32 | + */ | ||
| 33 | + | ||
| 34 | +/* Must be the very first thing: advapi32's EnumServicesStatusExA and | ||
| 35 | + * QueryServiceConfigA are gated on _WIN32_WINNT, and MinGW defaults to 0x502 | ||
| 36 | + * (Server 2003) which hides them. */ | ||
| 37 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 38 | +# define _WIN32_WINNT 0x0601 | ||
| 39 | +#endif | ||
| 40 | + | ||
| 41 | +#if !defined(_WIN32) | ||
| 42 | +# define _POSIX_C_SOURCE 200809L | ||
| 43 | +# define _DEFAULT_SOURCE 1 | ||
| 44 | +# if defined(__APPLE__) | ||
| 45 | +# define _DARWIN_C_SOURCE 1 | ||
| 46 | +# endif | ||
| 47 | +#endif | ||
| 48 | + | ||
| 49 | +#include <stdio.h> | ||
| 50 | +#include <stdlib.h> | ||
| 51 | +#include <string.h> | ||
| 52 | +#include <ctype.h> | ||
| 53 | +#include <errno.h> | ||
| 54 | +#include <time.h> | ||
| 55 | + | ||
| 56 | +#if defined(_WIN32) | ||
| 57 | +# define WIN32_LEAN_AND_MEAN | ||
| 58 | +# include <windows.h> | ||
| 59 | +# define sx_popen _popen | ||
| 60 | +# define sx_pclose _pclose | ||
| 61 | +#else | ||
| 62 | +# include <unistd.h> | ||
| 63 | +# include <dirent.h> | ||
| 64 | +# include <sys/types.h> | ||
| 65 | +# include <sys/wait.h> | ||
| 66 | +# define sx_popen popen | ||
| 67 | +# define sx_pclose pclose | ||
| 68 | +#endif | ||
| 69 | + | ||
| 70 | +#include "bot_theme_plugin.h" | ||
| 71 | +#include "ui_html.h" | ||
| 72 | + | ||
| 73 | +#define PLUGIN_SLUG "services" | ||
| 74 | +#define PLUGIN_ID "plugin_services" | ||
| 75 | +#define PLUGIN_VER "1.0.0" | ||
| 76 | + | ||
| 77 | +#define PLUGIN_NAME "services" | ||
| 78 | +#define PLUGIN_DESC "System services" | ||
| 79 | + | ||
| 80 | +#define MAX_SERVICES 2048 | ||
| 81 | +#define NAME_SZ 192 | ||
| 82 | +#define DESC_SZ 192 | ||
| 83 | +#define STATE_SZ 32 | ||
| 84 | +#define EN_SZ 32 | ||
| 85 | +#define OUT_SZ (1024 * 1024) | ||
| 86 | + | ||
| 87 | +/* init systems */ | ||
| 88 | +#define INIT_NONE 0 | ||
| 89 | +#define INIT_SYSTEMD 1 | ||
| 90 | +#define INIT_LAUNCHD 2 | ||
| 91 | +#define INIT_SCM 3 | ||
| 92 | + | ||
| 93 | +typedef struct { | ||
| 94 | + char name[NAME_SZ]; /* unit / label / service name */ | ||
| 95 | + char desc[DESC_SZ]; | ||
| 96 | + char active[STATE_SZ]; /* active | inactive | failed | running | stopped */ | ||
| 97 | + char sub[STATE_SZ]; /* running | dead | exited | ... */ | ||
| 98 | + char enabled[EN_SZ]; /* enabled | disabled | static | - */ | ||
| 99 | + int pid; | ||
| 100 | + unsigned long long mem; /* bytes, 0 = unknown */ | ||
| 101 | + char since[40]; | ||
| 102 | +} svc_t; | ||
| 103 | + | ||
| 104 | +static svc_t g_svc[MAX_SERVICES]; | ||
| 105 | +static int g_count; | ||
| 106 | +static int g_init = INIT_NONE; | ||
| 107 | +static int g_control = 0; | ||
| 108 | + | ||
| 109 | +/* ------------------------------------------------------------------ */ | ||
| 110 | +/* Growable output buffer */ | ||
| 111 | +/* ------------------------------------------------------------------ */ | ||
| 112 | + | ||
| 113 | +typedef struct { char *p; size_t n, cap; } buf_t; | ||
| 114 | + | ||
| 115 | +static int buf_need(buf_t *b, size_t extra) | ||
| 116 | +{ | ||
| 117 | + size_t want; | ||
| 118 | + char *np; | ||
| 119 | + if (b->n + extra + 1 <= b->cap) return 1; | ||
| 120 | + want = b->cap ? b->cap : 4096; | ||
| 121 | + while (want < b->n + extra + 1) want *= 2; | ||
| 122 | + np = (char *)realloc(b->p, want); | ||
| 123 | + if (!np) return 0; | ||
| 124 | + b->p = np; | ||
| 125 | + b->cap = want; | ||
| 126 | + return 1; | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +static void buf_add(buf_t *b, const char *s, size_t n) | ||
| 130 | +{ | ||
| 131 | + if (!b || !s) return; | ||
| 132 | + if (!buf_need(b, n)) return; | ||
| 133 | + memcpy(b->p + b->n, s, n); | ||
| 134 | + b->n += n; | ||
| 135 | + b->p[b->n] = '\0'; | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +static void buf_puts(buf_t *b, const char *s) | ||
| 139 | +{ | ||
| 140 | + if (s) buf_add(b, s, strlen(s)); | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +static void buf_putc(buf_t *b, char c) { buf_add(b, &c, 1); } | ||
| 144 | + | ||
| 145 | +static const char *buf_str(buf_t *b) { return b->p ? b->p : ""; } | ||
| 146 | + | ||
| 147 | +static void buf_free(buf_t *b) | ||
| 148 | +{ | ||
| 149 | + if (b) { free(b->p); b->p = NULL; b->n = b->cap = 0; } | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +/* JSON string escaping into a buffer. */ | ||
| 153 | +static void json_into(buf_t *b, const char *s) | ||
| 154 | +{ | ||
| 155 | + buf_putc(b, '"'); | ||
| 156 | + for (; s && *s; s++) { | ||
| 157 | + unsigned char c = (unsigned char)*s; | ||
| 158 | + switch (c) { | ||
| 159 | + case '"': buf_puts(b, "\\\""); break; | ||
| 160 | + case '\\': buf_puts(b, "\\\\"); break; | ||
| 161 | + case '\n': buf_puts(b, "\\n"); break; | ||
| 162 | + case '\r': buf_puts(b, "\\r"); break; | ||
| 163 | + case '\t': buf_puts(b, "\\t"); break; | ||
| 164 | + default: | ||
| 165 | + if (c < 0x20) { | ||
| 166 | + char tmp[8]; | ||
| 167 | + snprintf(tmp, sizeof tmp, "\\u%04x", c); | ||
| 168 | + buf_puts(b, tmp); | ||
| 169 | + } else { | ||
| 170 | + buf_putc(b, (char)c); | ||
| 171 | + } | ||
| 172 | + } | ||
| 173 | + } | ||
| 174 | + buf_putc(b, '"'); | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +/* ------------------------------------------------------------------ */ | ||
| 178 | +/* Small string utilities */ | ||
| 179 | +/* ------------------------------------------------------------------ */ | ||
| 180 | + | ||
| 181 | +static void str_copy(char *dst, size_t sz, const char *src) | ||
| 182 | +{ | ||
| 183 | + size_t n; | ||
| 184 | + if (!dst || sz == 0) return; | ||
| 185 | + if (!src) { dst[0] = '\0'; return; } | ||
| 186 | + n = strlen(src); | ||
| 187 | + if (n >= sz) n = sz - 1; | ||
| 188 | + memcpy(dst, src, n); | ||
| 189 | + dst[n] = '\0'; | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +static void str_trim(char *s) | ||
| 193 | +{ | ||
| 194 | + char *p; | ||
| 195 | + size_t n; | ||
| 196 | + if (!s) return; | ||
| 197 | + p = s; | ||
| 198 | + while (*p && isspace((unsigned char)*p)) p++; | ||
| 199 | + if (p != s) memmove(s, p, strlen(p) + 1); | ||
| 200 | + n = strlen(s); | ||
| 201 | + while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +static void url_decode(char *s) | ||
| 205 | +{ | ||
| 206 | + char *o = s; | ||
| 207 | + if (!s) return; | ||
| 208 | + while (*s) { | ||
| 209 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 210 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 211 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 212 | + *o++ = (char)((hi << 4) | lo); | ||
| 213 | + s += 3; | ||
| 214 | + } else if (*s == '+') { | ||
| 215 | + *o++ = ' '; | ||
| 216 | + s++; | ||
| 217 | + } else { | ||
| 218 | + *o++ = *s++; | ||
| 219 | + } | ||
| 220 | + } | ||
| 221 | + *o = '\0'; | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 225 | +{ | ||
| 226 | + size_t klen; | ||
| 227 | + const char *p; | ||
| 228 | + | ||
| 229 | + if (!out || outsz == 0) return 0; | ||
| 230 | + out[0] = '\0'; | ||
| 231 | + if (!qs || !key) return 0; | ||
| 232 | + klen = strlen(key); | ||
| 233 | + | ||
| 234 | + for (p = qs; *p; ) { | ||
| 235 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 236 | + const char *v = p + klen + 1; | ||
| 237 | + size_t i = 0; | ||
| 238 | + while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++; | ||
| 239 | + out[i] = '\0'; | ||
| 240 | + url_decode(out); | ||
| 241 | + return 1; | ||
| 242 | + } | ||
| 243 | + p = strchr(p, '&'); | ||
| 244 | + if (!p) break; | ||
| 245 | + p++; | ||
| 246 | + } | ||
| 247 | + return 0; | ||
| 248 | +} | ||
| 249 | + | ||
| 250 | +/* Unit / label / service name allowlist. Anything that could be read as shell | ||
| 251 | + * syntax, a path, or an option is rejected outright. */ | ||
| 252 | +static int valid_unit(const char *s) | ||
| 253 | +{ | ||
| 254 | + size_t n; | ||
| 255 | + if (!s) return 0; | ||
| 256 | + n = strlen(s); | ||
| 257 | + if (n < 1 || n > 160) return 0; | ||
| 258 | + for (; *s; s++) { | ||
| 259 | + unsigned char c = (unsigned char)*s; | ||
| 260 | + if (isalnum(c)) continue; | ||
| 261 | + if (c == '@' || c == '.' || c == '_' || c == ':' || c == '-' || c == '\\') | ||
| 262 | + continue; | ||
| 263 | + return 0; | ||
| 264 | + } | ||
| 265 | + return 1; | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +static int is_post_request(void) | ||
| 269 | +{ | ||
| 270 | + const char *m = getenv("REQUEST_METHOD"); | ||
| 271 | + return m && strcmp(m, "POST") == 0; | ||
| 272 | +} | ||
| 273 | + | ||
| 274 | +/* ------------------------------------------------------------------ */ | ||
| 275 | +/* Node authentication */ | ||
| 276 | +/* ------------------------------------------------------------------ */ | ||
| 277 | + | ||
| 278 | +static void require_node_auth(void) | ||
| 279 | +{ | ||
| 280 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 281 | + const char *xp; | ||
| 282 | + const char *auth; | ||
| 283 | + const char *qs; | ||
| 284 | + char qpwd[256]; | ||
| 285 | + | ||
| 286 | + if (!np || !*np) return; | ||
| 287 | + | ||
| 288 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 289 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 290 | + | ||
| 291 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 292 | + if (auth) { | ||
| 293 | + while (*auth == ' ') auth++; | ||
| 294 | + if (strncmp(auth, "Bearer ", 7) == 0) { | ||
| 295 | + auth += 7; | ||
| 296 | + while (*auth == ' ') auth++; | ||
| 297 | + if (strcmp(auth, np) == 0) return; | ||
| 298 | + } | ||
| 299 | + } | ||
| 300 | + | ||
| 301 | + qs = getenv("QUERY_STRING"); | ||
| 302 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | ||
| 303 | + return; | ||
| 304 | + | ||
| 305 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 306 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 307 | + "Cache-Control: no-store\r\n" | ||
| 308 | + "X-Content-Type-Options: nosniff\r\n\r\n" | ||
| 309 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 310 | + exit(0); | ||
| 311 | +} | ||
| 312 | + | ||
| 313 | +/* ------------------------------------------------------------------ */ | ||
| 314 | +/* Command capture and argv execution */ | ||
| 315 | +/* ------------------------------------------------------------------ */ | ||
| 316 | + | ||
| 317 | +/* Every command string passed here is a CONSTANT defined in this file, or is | ||
| 318 | + * built from a value that already passed valid_unit(). Nothing user-supplied | ||
| 319 | + * reaches this function unvalidated. */ | ||
| 320 | +static int capture(const char *cmd, char *out, size_t outsz) | ||
| 321 | +{ | ||
| 322 | + FILE *f; | ||
| 323 | + size_t n; | ||
| 324 | + | ||
| 325 | + if (!out || outsz == 0) return -1; | ||
| 326 | + out[0] = '\0'; | ||
| 327 | + f = sx_popen(cmd, "r"); | ||
| 328 | + if (!f) return -1; | ||
| 329 | + n = fread(out, 1, outsz - 1, f); | ||
| 330 | + out[n] = '\0'; | ||
| 331 | + if (sx_pclose(f) != 0) { | ||
| 332 | + /* still return what we read: callers check for emptiness */ | ||
| 333 | + } | ||
| 334 | + return (int)n; | ||
| 335 | +} | ||
| 336 | + | ||
| 337 | +#if !defined(_WIN32) | ||
| 338 | +/* Returns the child's exit status, or -1 when it could not be started. The | ||
| 339 | + * unit is a separate argv element, so no shell ever sees it. */ | ||
| 340 | +static int run_argv(char *const argv[]) | ||
| 341 | +{ | ||
| 342 | + pid_t pid; | ||
| 343 | + int st = 0; | ||
| 344 | + | ||
| 345 | + pid = fork(); | ||
| 346 | + if (pid < 0) return -1; | ||
| 347 | + if (pid == 0) { | ||
| 348 | + execvp(argv[0], argv); | ||
| 349 | + _exit(127); | ||
| 350 | + } | ||
| 351 | + if (waitpid(pid, &st, 0) < 0) return -1; | ||
| 352 | + if (WIFEXITED(st)) return WEXITSTATUS(st); | ||
| 353 | + return -1; | ||
| 354 | +} | ||
| 355 | +#endif | ||
| 356 | + | ||
| 357 | +/* ------------------------------------------------------------------ */ | ||
| 358 | +/* Minimal JSON field extraction (for systemctl --output=json output) */ | ||
| 359 | +/* ------------------------------------------------------------------ */ | ||
| 360 | + | ||
| 361 | +static int json_read_string_at(const char **pp, char *out, size_t outsz) | ||
| 362 | +{ | ||
| 363 | + const char *p = *pp; | ||
| 364 | + size_t i = 0; | ||
| 365 | + | ||
| 366 | + if (!p || *p != '"') return 0; | ||
| 367 | + p++; | ||
| 368 | + while (*p && *p != '"') { | ||
| 369 | + char c = *p; | ||
| 370 | + if (c == '\\' && p[1]) { | ||
| 371 | + p++; | ||
| 372 | + switch (*p) { | ||
| 373 | + case 'n': c = '\n'; break; | ||
| 374 | + case 'r': c = '\r'; break; | ||
| 375 | + case 't': c = '\t'; break; | ||
| 376 | + case 'b': c = '\b'; break; | ||
| 377 | + case 'f': c = '\f'; break; | ||
| 378 | + case 'u': { | ||
| 379 | + /* keep it simple: decode the low byte of the code point */ | ||
| 380 | + unsigned int v = 0; | ||
| 381 | + int k; | ||
| 382 | + p++; | ||
| 383 | + for (k = 0; k < 4 && isxdigit((unsigned char)*p); k++, p++) { | ||
| 384 | + v = v * 16 + (unsigned int)(isdigit((unsigned char)*p) | ||
| 385 | + ? *p - '0' | ||
| 386 | + : tolower((unsigned char)*p) - 'a' + 10); | ||
| 387 | + } | ||
| 388 | + if (i + 1 < outsz) out[i++] = (char)(v & 0xff); | ||
| 389 | + continue; | ||
| 390 | + } | ||
| 391 | + default: c = *p; break; | ||
| 392 | + } | ||
| 393 | + p++; | ||
| 394 | + } else { | ||
| 395 | + p++; | ||
| 396 | + } | ||
| 397 | + if (i + 1 < outsz) out[i++] = c; | ||
| 398 | + } | ||
| 399 | + if (*p == '"') p++; | ||
| 400 | + out[i] = '\0'; | ||
| 401 | + *pp = p; | ||
| 402 | + return 1; | ||
| 403 | +} | ||
| 404 | + | ||
| 405 | +/* Find "key":"value" inside one flat object slice [obj, obj_end). */ | ||
| 406 | +static int json_field(const char *obj, const char *end, const char *key, | ||
| 407 | + char *out, size_t outsz) | ||
| 408 | +{ | ||
| 409 | + size_t klen = strlen(key); | ||
| 410 | + const char *p = obj; | ||
| 411 | + | ||
| 412 | + if (!out || outsz == 0) return 0; | ||
| 413 | + out[0] = '\0'; | ||
| 414 | + | ||
| 415 | + while (p && p < end) { | ||
| 416 | + if (*p == '"' && (size_t)(end - p) > klen + 1 && | ||
| 417 | + strncmp(p + 1, key, klen) == 0 && p[1 + klen] == '"') { | ||
| 418 | + const char *q = p + klen + 2; | ||
| 419 | + while (q < end && isspace((unsigned char)*q)) q++; | ||
| 420 | + if (q < end && *q == ':') { | ||
| 421 | + q++; | ||
| 422 | + while (q < end && isspace((unsigned char)*q)) q++; | ||
| 423 | + if (q < end && *q == '"') | ||
| 424 | + return json_read_string_at(&q, out, outsz); | ||
| 425 | + if (q < end) { | ||
| 426 | + size_t i = 0; | ||
| 427 | + while (q < end && *q != ',' && *q != '}' && | ||
| 428 | + i + 1 < outsz) { | ||
| 429 | + if (!isspace((unsigned char)*q)) out[i++] = *q; | ||
| 430 | + q++; | ||
| 431 | + } | ||
| 432 | + out[i] = '\0'; | ||
| 433 | + return 1; | ||
| 434 | + } | ||
| 435 | + } | ||
| 436 | + return 0; | ||
| 437 | + } | ||
| 438 | + if (*p == '"') { | ||
| 439 | + char tmp[8]; | ||
| 440 | + const char *skip = p; | ||
| 441 | + json_read_string_at(&skip, tmp, sizeof tmp); | ||
| 442 | + p = skip; | ||
| 443 | + continue; | ||
| 444 | + } | ||
| 445 | + p++; | ||
| 446 | + } | ||
| 447 | + return 0; | ||
| 448 | +} | ||
| 449 | + | ||
| 450 | +/* ------------------------------------------------------------------ */ | ||
| 451 | +/* Collection: systemd (Linux) */ | ||
| 452 | +/* ------------------------------------------------------------------ */ | ||
| 453 | + | ||
| 454 | +static void svc_add(const char *name, const char *desc, const char *active, | ||
| 455 | + const char *sub, int pid) | ||
| 456 | +{ | ||
| 457 | + svc_t *s; | ||
| 458 | + if (g_count >= MAX_SERVICES) return; | ||
| 459 | + s = &g_svc[g_count++]; | ||
| 460 | + memset(s, 0, sizeof *s); | ||
| 461 | + str_copy(s->name, sizeof s->name, name); | ||
| 462 | + str_copy(s->desc, sizeof s->desc, desc); | ||
| 463 | + str_copy(s->active, sizeof s->active, active); | ||
| 464 | + str_copy(s->sub, sizeof s->sub, sub); | ||
| 465 | + str_copy(s->enabled, sizeof s->enabled, "-"); | ||
| 466 | + str_copy(s->since, sizeof s->since, "-"); | ||
| 467 | + s->pid = pid; | ||
| 468 | +} | ||
| 469 | + | ||
| 470 | +static svc_t *svc_find(const char *name) | ||
| 471 | +{ | ||
| 472 | + int i; | ||
| 473 | + if (!name) return NULL; | ||
| 474 | + for (i = 0; i < g_count; i++) | ||
| 475 | + if (strcmp(g_svc[i].name, name) == 0) return &g_svc[i]; | ||
| 476 | + return NULL; | ||
| 477 | +} | ||
| 478 | + | ||
| 479 | +static char *read_file_all(const char *path, size_t *len) | ||
| 480 | +{ | ||
| 481 | + FILE *f; | ||
| 482 | + char *buf; | ||
| 483 | + long sz; | ||
| 484 | + size_t n; | ||
| 485 | + | ||
| 486 | + f = fopen(path, "rb"); | ||
| 487 | + if (!f) return NULL; | ||
| 488 | + sz = 0; | ||
| 489 | + /* /proc files report st_size 0 and are not seekable, so only trust the | ||
| 490 | + * size when the seek actually works; otherwise read until EOF. */ | ||
| 491 | + if (fseek(f, 0, SEEK_END) == 0) { | ||
| 492 | + sz = ftell(f); | ||
| 493 | + if (sz < 0) sz = 0; | ||
| 494 | + if (sz > (long)(8 * 1024 * 1024)) { fclose(f); return NULL; } | ||
| 495 | + rewind(f); | ||
| 496 | + } | ||
| 497 | + buf = (char *)malloc((size_t)(sz > 0 ? sz : 4096) + 1); | ||
| 498 | + if (!buf) { fclose(f); return NULL; } | ||
| 499 | + if (sz > 0) { | ||
| 500 | + n = fread(buf, 1, (size_t)sz, f); | ||
| 501 | + } else { | ||
| 502 | + size_t cap = 4096; | ||
| 503 | + n = 0; | ||
| 504 | + for (;;) { | ||
| 505 | + size_t got; | ||
| 506 | + if (n == cap) { | ||
| 507 | + char *np; | ||
| 508 | + cap *= 2; | ||
| 509 | + if (cap > 8 * 1024 * 1024) break; | ||
| 510 | + np = (char *)realloc(buf, cap + 1); | ||
| 511 | + if (!np) break; | ||
| 512 | + buf = np; | ||
| 513 | + } | ||
| 514 | + got = fread(buf + n, 1, cap - n, f); | ||
| 515 | + if (got == 0) break; | ||
| 516 | + n += got; | ||
| 517 | + } | ||
| 518 | + } | ||
| 519 | + buf[n] = '\0'; | ||
| 520 | + fclose(f); | ||
| 521 | + if (len) *len = n; | ||
| 522 | + return buf; | ||
| 523 | +} | ||
| 524 | + | ||
| 525 | +/* Parse the systemctl --output=json array into g_svc. */ | ||
| 526 | +static void parse_json_units(const char *json) | ||
| 527 | +{ | ||
| 528 | + const char *p = json; | ||
| 529 | + | ||
| 530 | + while (p && *p) { | ||
| 531 | + const char *start, *end; | ||
| 532 | + char unit[NAME_SZ], load[STATE_SZ], active[STATE_SZ]; | ||
| 533 | + char sub[STATE_SZ], desc[DESC_SZ]; | ||
| 534 | + int depth = 0; | ||
| 535 | + | ||
| 536 | + start = strchr(p, '{'); | ||
| 537 | + if (!start) break; | ||
| 538 | + end = start; | ||
| 539 | + while (*end) { | ||
| 540 | + if (*end == '"') { | ||
| 541 | + char tmp[2]; | ||
| 542 | + json_read_string_at(&end, tmp, sizeof tmp); | ||
| 543 | + continue; | ||
| 544 | + } | ||
| 545 | + if (*end == '{') depth++; | ||
| 546 | + else if (*end == '}') { | ||
| 547 | + depth--; | ||
| 548 | + if (depth == 0) { end++; break; } | ||
| 549 | + } | ||
| 550 | + end++; | ||
| 551 | + } | ||
| 552 | + unit[0] = load[0] = active[0] = sub[0] = desc[0] = '\0'; | ||
| 553 | + json_field(start, end, "unit", unit, sizeof unit); | ||
| 554 | + json_field(start, end, "load", load, sizeof load); | ||
| 555 | + json_field(start, end, "active", active, sizeof active); | ||
| 556 | + json_field(start, end, "sub", sub, sizeof sub); | ||
| 557 | + json_field(start, end, "description", desc, sizeof desc); | ||
| 558 | + if (unit[0] && strcmp(load, "not-found") != 0) | ||
| 559 | + svc_add(unit, desc, active, sub, 0); | ||
| 560 | + p = end; | ||
| 561 | + } | ||
| 562 | +} | ||
| 563 | + | ||
| 564 | +/* Parse the pre-248 plain table: | ||
| 565 | + * UNIT LOAD ACTIVE SUB DESCRIPTION | ||
| 566 | + * ssh.service loaded active running OpenBSD Secure Shell server | ||
| 567 | + */ | ||
| 568 | +static void parse_plain_units(const char *text) | ||
| 569 | +{ | ||
| 570 | + const char *p = text; | ||
| 571 | + | ||
| 572 | + while (p && *p) { | ||
| 573 | + const char *nl = strchr(p, '\n'); | ||
| 574 | + size_t len = nl ? (size_t)(nl - p) : strlen(p); | ||
| 575 | + char line[1024]; | ||
| 576 | + char unit[NAME_SZ], load[STATE_SZ], active[STATE_SZ], sub[STATE_SZ]; | ||
| 577 | + char desc[DESC_SZ]; | ||
| 578 | + int n = 0, off = 0; | ||
| 579 | + | ||
| 580 | + if (len >= sizeof line) len = sizeof line - 1; | ||
| 581 | + memcpy(line, p, len); | ||
| 582 | + line[len] = '\0'; | ||
| 583 | + p = nl ? nl + 1 : p + strlen(p); | ||
| 584 | + | ||
| 585 | + if (len < 4) continue; | ||
| 586 | + if (strstr(line, "UNIT") && strstr(line, "LOAD")) continue; | ||
| 587 | + if (strstr(line, "loaded units listed")) continue; | ||
| 588 | + if (strstr(line, "To show all installed")) continue; | ||
| 589 | + | ||
| 590 | + unit[0] = load[0] = active[0] = sub[0] = desc[0] = '\0'; | ||
| 591 | + n = sscanf(line, "%191s %31s %31s %31s %n", | ||
| 592 | + unit, load, active, sub, &off); | ||
| 593 | + if (n < 4) continue; | ||
| 594 | + if (strcmp(load, "loaded") != 0 && strcmp(load, "not-found") != 0) continue; | ||
| 595 | + if (strcmp(load, "not-found") == 0) continue; | ||
| 596 | + if (off > 0 && (size_t)off < len) { | ||
| 597 | + str_copy(desc, sizeof desc, line + off); | ||
| 598 | + str_trim(desc); | ||
| 599 | + } | ||
| 600 | + if (!strchr(unit, '.')) continue; | ||
| 601 | + svc_add(unit, desc, active, sub, 0); | ||
| 602 | + } | ||
| 603 | +} | ||
| 604 | + | ||
| 605 | +/* One pass over `systemctl show --type=service --all -p ...`, whose output is | ||
| 606 | + * key=value blocks separated by a blank line. */ | ||
| 607 | +static void apply_show(const char *text) | ||
| 608 | +{ | ||
| 609 | + const char *p = text; | ||
| 610 | + | ||
| 611 | + while (p && *p) { | ||
| 612 | + char name[NAME_SZ] = {0}, pid_s[24] = {0}, since[40] = {0}; | ||
| 613 | + char mem_s[32] = {0}, file_state[EN_SZ] = {0}; | ||
| 614 | + char active[STATE_SZ] = {0}, sub[STATE_SZ] = {0}, desc[DESC_SZ] = {0}; | ||
| 615 | + svc_t *s; | ||
| 616 | + | ||
| 617 | + { | ||
| 618 | + const char *nl = strstr(p, "\n\n"); | ||
| 619 | + const char *end = nl ? nl : p + strlen(p); | ||
| 620 | + const char *line = p; | ||
| 621 | + while (line < end) { | ||
| 622 | + const char *eol = strchr(line, '\n'); | ||
| 623 | + if (!eol || eol > end) eol = end; | ||
| 624 | + { | ||
| 625 | + size_t l = (size_t)(eol - line); | ||
| 626 | + char l2[512]; | ||
| 627 | + char *eq; | ||
| 628 | + if (l < sizeof l2) { | ||
| 629 | + memcpy(l2, line, l); | ||
| 630 | + l2[l] = '\0'; | ||
| 631 | + eq = strchr(l2, '='); | ||
| 632 | + if (eq) { | ||
| 633 | + *eq++ = '\0'; | ||
| 634 | + if (strcmp(l2, "Id") == 0) str_copy(name, sizeof name, eq); | ||
| 635 | + else if (strcmp(l2, "MainPID") == 0) str_copy(pid_s, sizeof pid_s, eq); | ||
| 636 | + else if (strcmp(l2, "ActiveEnterTimestamp") == 0) str_copy(since, sizeof since, eq); | ||
| 637 | + else if (strcmp(l2, "MemoryCurrent") == 0) str_copy(mem_s, sizeof mem_s, eq); | ||
| 638 | + else if (strcmp(l2, "UnitFileState") == 0) str_copy(file_state, sizeof file_state, eq); | ||
| 639 | + else if (strcmp(l2, "ActiveState") == 0) str_copy(active, sizeof active, eq); | ||
| 640 | + else if (strcmp(l2, "SubState") == 0) str_copy(sub, sizeof sub, eq); | ||
| 641 | + else if (strcmp(l2, "Description") == 0) str_copy(desc, sizeof desc, eq); | ||
| 642 | + } | ||
| 643 | + } | ||
| 644 | + } | ||
| 645 | + line = eol < end ? eol + 1 : end; | ||
| 646 | + } | ||
| 647 | + p = nl ? nl + 2 : end; | ||
| 648 | + } | ||
| 649 | + | ||
| 650 | + if (!name[0]) continue; | ||
| 651 | + s = svc_find(name); | ||
| 652 | + if (!s) { | ||
| 653 | + if (desc[0] || active[0]) { | ||
| 654 | + svc_add(name, desc, active, sub, 0); | ||
| 655 | + s = svc_find(name); | ||
| 656 | + } | ||
| 657 | + } | ||
| 658 | + if (!s) continue; | ||
| 659 | + s->pid = atoi(pid_s); | ||
| 660 | + if (mem_s[0] && strncmp(mem_s, "18446744073709551615", 20) != 0) | ||
| 661 | + s->mem = strtoull(mem_s, NULL, 10); | ||
| 662 | + if (file_state[0]) str_copy(s->enabled, sizeof s->enabled, file_state); | ||
| 663 | + if (since[0] && strcmp(since, "n/a") != 0) { | ||
| 664 | + str_copy(s->since, sizeof s->since, since); | ||
| 665 | + } | ||
| 666 | + if (active[0] && !s->active[0]) str_copy(s->active, sizeof s->active, active); | ||
| 667 | + if (sub[0] && !s->sub[0]) str_copy(s->sub, sizeof s->sub, sub); | ||
| 668 | + if (desc[0] && !s->desc[0]) str_copy(s->desc, sizeof s->desc, desc); | ||
| 669 | + } | ||
| 670 | +} | ||
| 671 | + | ||
| 672 | +/* Containers with no init system: list /proc/<pid> long-running daemons. */ | ||
| 673 | +static int collect_proc_daemons(void) | ||
| 674 | +{ | ||
| 675 | +#if defined(_WIN32) | ||
| 676 | + return 0; | ||
| 677 | +#else | ||
| 678 | + const char *root = getenv("SERVICES_MOCK_PROC_DIR"); | ||
| 679 | + DIR *d; | ||
| 680 | + struct dirent *de; | ||
| 681 | + double uptime_s = 0.0; | ||
| 682 | + | ||
| 683 | + if (!root || !*root) root = "/proc"; | ||
| 684 | + | ||
| 685 | + { | ||
| 686 | + char up[64]; | ||
| 687 | + char path[512]; | ||
| 688 | + FILE *f; | ||
| 689 | + snprintf(path, sizeof path, "%s/uptime", root); | ||
| 690 | + f = fopen(path, "r"); | ||
| 691 | + if (f) { | ||
| 692 | + if (fgets(up, sizeof up, f)) uptime_s = atof(up); | ||
| 693 | + fclose(f); | ||
| 694 | + } | ||
| 695 | + } | ||
| 696 | + if (uptime_s <= 0.0) return 0; | ||
| 697 | + | ||
| 698 | + d = opendir(root); | ||
| 699 | + if (!d) return 0; | ||
| 700 | + while ((de = readdir(d)) != NULL && g_count < MAX_SERVICES) { | ||
| 701 | + char path[1024], comm[NAME_SZ], statline[2048]; | ||
| 702 | + char *buf; | ||
| 703 | + size_t len = 0; | ||
| 704 | + int pid; | ||
| 705 | + unsigned long long start_ticks = 0; | ||
| 706 | + double started_at, age; | ||
| 707 | + long rss_pages = 0; | ||
| 708 | + | ||
| 709 | + if (!isdigit((unsigned char)de->d_name[0])) continue; | ||
| 710 | + pid = atoi(de->d_name); | ||
| 711 | + if (pid <= 0) continue; | ||
| 712 | + | ||
| 713 | + snprintf(path, sizeof path, "%s/%s/comm", root, de->d_name); | ||
| 714 | + comm[0] = '\0'; | ||
| 715 | + buf = read_file_all(path, &len); | ||
| 716 | + if (!buf) continue; | ||
| 717 | + str_copy(comm, sizeof comm, buf); | ||
| 718 | + free(buf); | ||
| 719 | + str_trim(comm); | ||
| 720 | + if (!comm[0]) continue; | ||
| 721 | + | ||
| 722 | + /* field 22 (1-based) of <pid>/stat is starttime; field 2 is "(comm)" | ||
| 723 | + * and may contain spaces, so scan from the last ')' first. */ | ||
| 724 | + snprintf(path, sizeof path, "%s/%s/stat", root, de->d_name); | ||
| 725 | + buf = read_file_all(path, &len); | ||
| 726 | + if (!buf) continue; | ||
| 727 | + str_copy(statline, sizeof statline, buf); | ||
| 728 | + free(buf); | ||
| 729 | + { | ||
| 730 | + char *rp = strrchr(statline, ')'); | ||
| 731 | + int fld = 2; | ||
| 732 | + char *q = rp ? rp + 1 : statline; | ||
| 733 | + while (*q) { | ||
| 734 | + while (*q == ' ') q++; | ||
| 735 | + if (!*q) break; | ||
| 736 | + fld++; | ||
| 737 | + if (fld == 22) { start_ticks = strtoull(q, NULL, 10); break; } | ||
| 738 | + while (*q && *q != ' ') q++; | ||
| 739 | + } | ||
| 740 | + } | ||
| 741 | + | ||
| 742 | + /* <pid>/statm field 2 is the resident set in pages. */ | ||
| 743 | + snprintf(path, sizeof path, "%s/%s/statm", root, de->d_name); | ||
| 744 | + buf = read_file_all(path, &len); | ||
| 745 | + if (buf) { | ||
| 746 | + long dummy = 0; | ||
| 747 | + if (sscanf(buf, "%ld %ld", &dummy, &rss_pages) != 2) rss_pages = 0; | ||
| 748 | + free(buf); | ||
| 749 | + } | ||
| 750 | + | ||
| 751 | + started_at = (double)start_ticks / 100.0; | ||
| 752 | + age = uptime_s - started_at; | ||
| 753 | + if (age < 300.0) continue; | ||
| 754 | + | ||
| 755 | + svc_add(comm, "process (no init system)", "running", "running", pid); | ||
| 756 | + { | ||
| 757 | + svc_t *s = &g_svc[g_count - 1]; | ||
| 758 | + s->mem = (unsigned long long)rss_pages * 4096ULL; | ||
| 759 | + str_copy(s->enabled, sizeof s->enabled, "-"); | ||
| 760 | + snprintf(s->since, sizeof s->since, "up %lds", (long)age); | ||
| 761 | + } | ||
| 762 | + } | ||
| 763 | + closedir(d); | ||
| 764 | + return g_count; | ||
| 765 | +#endif | ||
| 766 | +} | ||
| 767 | + | ||
| 768 | +static void collect_systemd(void) | ||
| 769 | +{ | ||
| 770 | + const char *mock = getenv("SERVICES_MOCK_SYSTEMCTL"); | ||
| 771 | + char *buf = NULL; | ||
| 772 | + size_t len = 0; | ||
| 773 | + static char out[OUT_SZ]; | ||
| 774 | + | ||
| 775 | + g_init = INIT_SYSTEMD; | ||
| 776 | + g_count = 0; | ||
| 777 | + | ||
| 778 | + if (mock && *mock) { | ||
| 779 | + buf = read_file_all(mock, &len); | ||
| 780 | + if (buf) { | ||
| 781 | + const char *p = buf; | ||
| 782 | + while (*p && isspace((unsigned char)*p)) p++; | ||
| 783 | + if (*p == '[') parse_json_units(buf); | ||
| 784 | + else parse_plain_units(buf); | ||
| 785 | + free(buf); | ||
| 786 | + } | ||
| 787 | + } else { | ||
| 788 | + if (capture("systemctl list-units --type=service --all --no-pager " | ||
| 789 | + "--plain --output=json 2>/dev/null", out, sizeof out) > 0) { | ||
| 790 | + const char *p = out; | ||
| 791 | + while (*p && isspace((unsigned char)*p)) p++; | ||
| 792 | + if (*p == '[') parse_json_units(out); | ||
| 793 | + else parse_plain_units(out); | ||
| 794 | + } | ||
| 795 | + if (g_count == 0) { | ||
| 796 | + if (capture("systemctl list-units --type=service --all --no-pager " | ||
| 797 | + "--plain 2>/dev/null", out, sizeof out) > 0) | ||
| 798 | + parse_plain_units(out); | ||
| 799 | + } | ||
| 800 | + if (g_count == 0) { | ||
| 801 | + if (capture("systemctl list-unit-files --type=service --no-pager " | ||
| 802 | + "--plain 2>/dev/null", out, sizeof out) > 0) | ||
| 803 | + parse_plain_units(out); | ||
| 804 | + } | ||
| 805 | + } | ||
| 806 | + | ||
| 807 | + /* One enrichment pass, only when we have real systemd output. */ | ||
| 808 | + if (g_count > 0) { | ||
| 809 | + const char *show_mock = getenv("SERVICES_MOCK_SYSTEMCTL_SHOW"); | ||
| 810 | + if (show_mock && *show_mock) { | ||
| 811 | + char *sb = read_file_all(show_mock, &len); | ||
| 812 | + if (sb) { apply_show(sb); free(sb); } | ||
| 813 | + } else if (!mock || !*mock) { | ||
| 814 | + if (capture("systemctl show --type=service --all -p Id -p MainPID " | ||
| 815 | + "-p ActiveEnterTimestamp -p MemoryCurrent " | ||
| 816 | + "-p UnitFileState -p ActiveState -p SubState " | ||
| 817 | + "-p Description 2>/dev/null", out, sizeof out) > 0) | ||
| 818 | + apply_show(out); | ||
| 819 | + } | ||
| 820 | + } | ||
| 821 | +} | ||
| 822 | + | ||
| 823 | +/* ------------------------------------------------------------------ */ | ||
| 824 | +/* Collection: launchd (macOS) */ | ||
| 825 | +/* ------------------------------------------------------------------ */ | ||
| 826 | + | ||
| 827 | +#if !defined(_WIN32) | ||
| 828 | +static void collect_launchd(void) | ||
| 829 | +{ | ||
| 830 | + const char *mock = getenv("SERVICES_MOCK_LAUNCHCTL"); | ||
| 831 | + static char out[OUT_SZ]; | ||
| 832 | + char *buf = NULL; | ||
| 833 | + | ||
| 834 | + g_init = INIT_LAUNCHD; | ||
| 835 | + g_count = 0; | ||
| 836 | + | ||
| 837 | + if (mock && *mock) { | ||
| 838 | + buf = read_file_all(mock, NULL); | ||
| 839 | + if (buf) { str_copy(out, sizeof out, buf); free(buf); } | ||
| 840 | + } else if (capture("launchctl list 2>/dev/null", out, sizeof out) <= 0) { | ||
| 841 | + out[0] = '\0'; | ||
| 842 | + } | ||
| 843 | + | ||
| 844 | + { | ||
| 845 | + const char *p = out; | ||
| 846 | + int first = 1; | ||
| 847 | + while (p && *p) { | ||
| 848 | + const char *nl = strchr(p, '\n'); | ||
| 849 | + size_t len = nl ? (size_t)(nl - p) : strlen(p); | ||
| 850 | + char line[512]; | ||
| 851 | + char pid_s[32], st_s[32], label[NAME_SZ]; | ||
| 852 | + int pid = 0; | ||
| 853 | + | ||
| 854 | + if (len >= sizeof line) len = sizeof line - 1; | ||
| 855 | + memcpy(line, p, len); | ||
| 856 | + line[len] = '\0'; | ||
| 857 | + p = nl ? nl + 1 : p + strlen(p); | ||
| 858 | + | ||
| 859 | + if (first) { | ||
| 860 | + first = 0; | ||
| 861 | + if (strstr(line, "PID") && strstr(line, "Label")) continue; | ||
| 862 | + } | ||
| 863 | + pid_s[0] = st_s[0] = label[0] = '\0'; | ||
| 864 | + if (sscanf(line, "%31s %31s %191[^\n]", pid_s, st_s, label) < 3) continue; | ||
| 865 | + str_trim(label); | ||
| 866 | + if (!label[0]) continue; | ||
| 867 | + if (strcmp(pid_s, "-") != 0) pid = atoi(pid_s); | ||
| 868 | + /* A job with no pid whose last exit status is non-zero failed. */ | ||
| 869 | + if (pid <= 0 && strcmp(st_s, "0") != 0) | ||
| 870 | + svc_add(label, "launchd job", "failed", "failed", 0); | ||
| 871 | + else | ||
| 872 | + svc_add(label, "launchd job", pid > 0 ? "running" : "inactive", | ||
| 873 | + pid > 0 ? "running" : "exited", pid); | ||
| 874 | + { | ||
| 875 | + svc_t *s = &g_svc[g_count - 1]; | ||
| 876 | + str_copy(s->enabled, sizeof s->enabled, "launchd"); | ||
| 877 | + if (strcmp(st_s, "0") != 0 && strcmp(pid_s, "-") == 0) | ||
| 878 | + snprintf(s->since, sizeof s->since, "last exit %s", st_s); | ||
| 879 | + else | ||
| 880 | + str_copy(s->since, sizeof s->since, "-"); | ||
| 881 | + } | ||
| 882 | + if (g_count >= MAX_SERVICES) break; | ||
| 883 | + } | ||
| 884 | + } | ||
| 885 | + | ||
| 886 | + /* Fill memory (and start time) from a single ps pass over the pids we did | ||
| 887 | + * get. Only digits ever reach the command line here. */ | ||
| 888 | + if (!mock || !*mock) { | ||
| 889 | + char pids[512]; | ||
| 890 | + size_t used = 0; | ||
| 891 | + int i; | ||
| 892 | + | ||
| 893 | + pids[0] = '\0'; | ||
| 894 | + for (i = 0; i < g_count; i++) { | ||
| 895 | + char tmp[16]; | ||
| 896 | + int n; | ||
| 897 | + if (g_svc[i].pid <= 0) continue; | ||
| 898 | + n = snprintf(tmp, sizeof tmp, "%s%d", used ? "," : "", g_svc[i].pid); | ||
| 899 | + if (n <= 0 || used + (size_t)n + 1 >= sizeof pids) break; | ||
| 900 | + memcpy(pids + used, tmp, (size_t)n); | ||
| 901 | + used += (size_t)n; | ||
| 902 | + pids[used] = '\0'; | ||
| 903 | + } | ||
| 904 | + if (used > 0) { | ||
| 905 | + char cmd[640]; | ||
| 906 | + snprintf(cmd, sizeof cmd, "ps -o pid=,rss=,lstart= -p %s 2>/dev/null", pids); | ||
| 907 | + if (capture(cmd, out, sizeof out) > 0) { | ||
| 908 | + char *line = out; | ||
| 909 | + while (line && *line) { | ||
| 910 | + char *nl = strchr(line, '\n'); | ||
| 911 | + int pid = 0; | ||
| 912 | + long rss = 0; | ||
| 913 | + int off = 0; | ||
| 914 | + svc_t *s; | ||
| 915 | + if (nl) *nl = '\0'; | ||
| 916 | + if (sscanf(line, "%d %ld %n", &pid, &rss, &off) >= 2 && pid > 0) { | ||
| 917 | + for (i = 0; i < g_count; i++) { | ||
| 918 | + if (g_svc[i].pid != pid) continue; | ||
| 919 | + s = &g_svc[i]; | ||
| 920 | + s->mem = (unsigned long long)rss * 1024ULL; | ||
| 921 | + if (off > 0 && (size_t)off < strlen(line) && | ||
| 922 | + strcmp(s->since, "-") == 0) { | ||
| 923 | + str_copy(s->since, sizeof s->since, line + off); | ||
| 924 | + str_trim(s->since); | ||
| 925 | + } | ||
| 926 | + break; | ||
| 927 | + } | ||
| 928 | + } | ||
| 929 | + line = nl ? nl + 1 : NULL; | ||
| 930 | + } | ||
| 931 | + } | ||
| 932 | + } | ||
| 933 | + } | ||
| 934 | +} | ||
| 935 | + | ||
| 936 | +#endif /* !_WIN32 */ | ||
| 937 | + | ||
| 938 | +/* ------------------------------------------------------------------ */ | ||
| 939 | +/* Collection: Windows SCM */ | ||
| 940 | +/* ------------------------------------------------------------------ */ | ||
| 941 | + | ||
| 942 | +#if defined(_WIN32) | ||
| 943 | +static void collect_scm(void) | ||
| 944 | +{ | ||
| 945 | + SC_HANDLE scm; | ||
| 946 | + DWORD need = 0, got = 0, resume = 0; | ||
| 947 | + LPBYTE buf = NULL; | ||
| 948 | + | ||
| 949 | + g_init = INIT_SCM; | ||
| 950 | + g_count = 0; | ||
| 951 | + | ||
| 952 | + scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE); | ||
| 953 | + if (!scm) return; | ||
| 954 | + | ||
| 955 | + EnumServicesStatusExA(scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, | ||
| 956 | + SERVICE_STATE_ALL, NULL, 0, &need, &got, &resume, NULL); | ||
| 957 | + if (need > 0) { | ||
| 958 | + buf = (LPBYTE)malloc(need); | ||
| 959 | + if (buf) { | ||
| 960 | + if (EnumServicesStatusExA(scm, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, | ||
| 961 | + SERVICE_STATE_ALL, buf, need, &need, | ||
| 962 | + &got, &resume, NULL)) { | ||
| 963 | + LPENUM_SERVICE_STATUS_PROCESSA it = (LPENUM_SERVICE_STATUS_PROCESSA)buf; | ||
| 964 | + DWORD i; | ||
| 965 | + for (i = 0; i < got && g_count < MAX_SERVICES; i++) { | ||
| 966 | + const char *state = "stopped"; | ||
| 967 | + char sub[STATE_SZ]; | ||
| 968 | + char enabled[EN_SZ] = "-"; | ||
| 969 | + SC_HANDLE svc; | ||
| 970 | + LPQUERY_SERVICE_CONFIGA cfg; | ||
| 971 | + | ||
| 972 | + switch (it[i].ServiceStatusProcess.dwCurrentState) { | ||
| 973 | + case SERVICE_RUNNING: state = "running"; break; | ||
| 974 | + case SERVICE_STOPPED: state = "inactive"; break; | ||
| 975 | + case SERVICE_PAUSED: state = "paused"; break; | ||
| 976 | + case SERVICE_START_PENDING: state = "starting"; break; | ||
| 977 | + case SERVICE_STOP_PENDING: state = "stopping"; break; | ||
| 978 | + default: state = "unknown"; break; | ||
| 979 | + } | ||
| 980 | + snprintf(sub, sizeof sub, "%lu", | ||
| 981 | + (unsigned long)it[i].ServiceStatusProcess.dwCurrentState); | ||
| 982 | + | ||
| 983 | + svc_add(it[i].lpServiceName, it[i].lpDisplayName, state, sub, 0); | ||
| 984 | + { | ||
| 985 | + svc_t *s = &g_svc[g_count - 1]; | ||
| 986 | + s->pid = (int)it[i].ServiceStatusProcess.dwProcessId; | ||
| 987 | + svc = OpenServiceA(scm, it[i].lpServiceName, | ||
| 988 | + SERVICE_QUERY_CONFIG); | ||
| 989 | + if (svc) { | ||
| 990 | + DWORD cneed = 0; | ||
| 991 | + QueryServiceConfigA(svc, NULL, 0, &cneed); | ||
| 992 | + cfg = (LPQUERY_SERVICE_CONFIGA)malloc(cneed ? cneed : 1); | ||
| 993 | + if (cfg && QueryServiceConfigA(svc, cfg, cneed, &cneed)) { | ||
| 994 | + switch (cfg->dwStartType) { | ||
| 995 | + case SERVICE_AUTO_START: enabled[0] = 0; str_copy(enabled, sizeof enabled, "automatic"); break; | ||
| 996 | + case SERVICE_DEMAND_START: str_copy(enabled, sizeof enabled, "manual"); break; | ||
| 997 | + case SERVICE_DISABLED: str_copy(enabled, sizeof enabled, "disabled"); break; | ||
| 998 | + case SERVICE_BOOT_START: str_copy(enabled, sizeof enabled, "boot"); break; | ||
| 999 | + case SERVICE_SYSTEM_START: str_copy(enabled, sizeof enabled, "system"); break; | ||
| 1000 | + default: str_copy(enabled, sizeof enabled, "-"); break; | ||
| 1001 | + } | ||
| 1002 | + } | ||
| 1003 | + free(cfg); | ||
| 1004 | + CloseServiceHandle(svc); | ||
| 1005 | + } | ||
| 1006 | + str_copy(s->enabled, sizeof s->enabled, enabled); | ||
| 1007 | + str_copy(s->since, sizeof s->since, "-"); | ||
| 1008 | + s->mem = 0; | ||
| 1009 | + } | ||
| 1010 | + } | ||
| 1011 | + } | ||
| 1012 | + free(buf); | ||
| 1013 | + } | ||
| 1014 | + } | ||
| 1015 | + CloseServiceHandle(scm); | ||
| 1016 | +} | ||
| 1017 | +#endif | ||
| 1018 | + | ||
| 1019 | +/* ------------------------------------------------------------------ */ | ||
| 1020 | +/* Collection dispatch + ordering */ | ||
| 1021 | +/* ------------------------------------------------------------------ */ | ||
| 1022 | + | ||
| 1023 | +static int svc_failed(const svc_t *s) | ||
| 1024 | +{ | ||
| 1025 | + return strcmp(s->active, "failed") == 0 || | ||
| 1026 | + strcmp(s->sub, "failed") == 0; | ||
| 1027 | +} | ||
| 1028 | + | ||
| 1029 | +static int svc_running(const svc_t *s) | ||
| 1030 | +{ | ||
| 1031 | + return strcmp(s->active, "running") == 0 || | ||
| 1032 | + strcmp(s->active, "active") == 0; | ||
| 1033 | +} | ||
| 1034 | + | ||
| 1035 | +static int svc_cmp(const void *a, const void *b) | ||
| 1036 | +{ | ||
| 1037 | + const svc_t *x = (const svc_t *)a; | ||
| 1038 | + const svc_t *y = (const svc_t *)b; | ||
| 1039 | + int fx = svc_failed(x), fy = svc_failed(y); | ||
| 1040 | + int rx = svc_running(x), ry = svc_running(y); | ||
| 1041 | + | ||
| 1042 | + if (fx != fy) return fy - fx; /* failed first */ | ||
| 1043 | + if (rx != ry) return ry - rx; /* then running */ | ||
| 1044 | + return strcmp(x->name, y->name); | ||
| 1045 | +} | ||
| 1046 | + | ||
| 1047 | +static const char *init_name(void) | ||
| 1048 | +{ | ||
| 1049 | + switch (g_init) { | ||
| 1050 | + case INIT_SYSTEMD: return "systemd"; | ||
| 1051 | + case INIT_LAUNCHD: return "launchd"; | ||
| 1052 | + case INIT_SCM: return "windows-scm"; | ||
| 1053 | + default: return "none"; | ||
| 1054 | + } | ||
| 1055 | +} | ||
| 1056 | + | ||
| 1057 | +static void collect_all(void) | ||
| 1058 | +{ | ||
| 1059 | + const char *force = getenv("SERVICES_FORCE_INIT"); | ||
| 1060 | + const char *allow = getenv("SERVICES_ALLOW_CONTROL"); | ||
| 1061 | + | ||
| 1062 | + g_control = (allow && *allow && strcmp(allow, "0") != 0); | ||
| 1063 | + g_count = 0; | ||
| 1064 | + | ||
| 1065 | +#if defined(_WIN32) | ||
| 1066 | + collect_scm(); | ||
| 1067 | +#elif defined(__APPLE__) | ||
| 1068 | + collect_launchd(); | ||
| 1069 | +#else | ||
| 1070 | + if (getenv("SERVICES_MOCK_LAUNCHCTL")) { | ||
| 1071 | + collect_launchd(); /* fixture-driven launchd path on any host */ | ||
| 1072 | + } else if (force && strcmp(force, "none") == 0) { | ||
| 1073 | + g_init = INIT_NONE; | ||
| 1074 | + collect_proc_daemons(); | ||
| 1075 | + } else if (getenv("SERVICES_MOCK_SYSTEMCTL")) { | ||
| 1076 | + collect_systemd(); | ||
| 1077 | + } else if (access("/run/systemd/system", F_OK) == 0) { | ||
| 1078 | + collect_systemd(); | ||
| 1079 | + } else { | ||
| 1080 | + g_init = INIT_NONE; | ||
| 1081 | + if (collect_proc_daemons() == 0) g_count = 0; | ||
| 1082 | + } | ||
| 1083 | +#endif | ||
| 1084 | + | ||
| 1085 | + if (g_count > 1) qsort(g_svc, (size_t)g_count, sizeof(svc_t), svc_cmp); | ||
| 1086 | +} | ||
| 1087 | + | ||
| 1088 | +/* ------------------------------------------------------------------ */ | ||
| 1089 | +/* JSON output */ | ||
| 1090 | +/* ------------------------------------------------------------------ */ | ||
| 1091 | + | ||
| 1092 | +static void mem_json(buf_t *b, unsigned long long v) | ||
| 1093 | +{ | ||
| 1094 | + char tmp[32]; | ||
| 1095 | + if (v == 0) { buf_puts(b, "null"); return; } | ||
| 1096 | + snprintf(tmp, sizeof tmp, "%llu", v); | ||
| 1097 | + buf_puts(b, tmp); | ||
| 1098 | +} | ||
| 1099 | + | ||
| 1100 | +static void emit_service(buf_t *b, const svc_t *s) | ||
| 1101 | +{ | ||
| 1102 | + buf_puts(b, "{\"name\":"); | ||
| 1103 | + json_into(b, s->name); | ||
| 1104 | + buf_puts(b, ",\"description\":"); | ||
| 1105 | + json_into(b, s->desc); | ||
| 1106 | + buf_puts(b, ",\"active\":"); | ||
| 1107 | + json_into(b, s->active); | ||
| 1108 | + buf_puts(b, ",\"sub\":"); | ||
| 1109 | + json_into(b, s->sub); | ||
| 1110 | + buf_puts(b, ",\"enabled\":"); | ||
| 1111 | + json_into(b, s->enabled); | ||
| 1112 | + buf_puts(b, ",\"pid\":"); | ||
| 1113 | + { | ||
| 1114 | + char tmp[32]; | ||
| 1115 | + snprintf(tmp, sizeof tmp, "%d", s->pid); | ||
| 1116 | + buf_puts(b, tmp); | ||
| 1117 | + } | ||
| 1118 | + buf_puts(b, ",\"memory_bytes\":"); | ||
| 1119 | + mem_json(b, s->mem); | ||
| 1120 | + buf_puts(b, ",\"since\":"); | ||
| 1121 | + json_into(b, s->since); | ||
| 1122 | + buf_puts(b, ",\"failed\":"); | ||
| 1123 | + buf_puts(b, svc_failed(s) ? "true" : "false"); | ||
| 1124 | + buf_putc(b, '}'); | ||
| 1125 | +} | ||
| 1126 | + | ||
| 1127 | +static void print_json_header(void) | ||
| 1128 | +{ | ||
| 1129 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 1130 | + "Cache-Control: no-store\r\n" | ||
| 1131 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1132 | +} | ||
| 1133 | + | ||
| 1134 | +/* ------------------------------------------------------------------ */ | ||
| 1135 | +/* HTML */ | ||
| 1136 | +/* ------------------------------------------------------------------ */ | ||
| 1137 | + | ||
| 1138 | +/* Split UI_HTML on the two control-byte placeholders and expand them into the | ||
| 1139 | + * theme macros, so the page and the bot palette can never drift apart. */ | ||
| 1140 | +static void emit_ui(void) | ||
| 1141 | +{ | ||
| 1142 | + const char *p = UI_HTML; | ||
| 1143 | + | ||
| 1144 | + while (*p) { | ||
| 1145 | + if (*p == '\001') { | ||
| 1146 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS | ||
| 1147 | + ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);" | ||
| 1148 | + "--ac:var(--blue);--sf:var(--bg-card);--sf2:var(--surface-2)}" | ||
| 1149 | + "</style>", stdout); | ||
| 1150 | + p++; | ||
| 1151 | + } else if (*p == '\002') { | ||
| 1152 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | ||
| 1153 | + p++; | ||
| 1154 | + } else { | ||
| 1155 | + putchar(*p++); | ||
| 1156 | + } | ||
| 1157 | + } | ||
| 1158 | +} | ||
| 1159 | + | ||
| 1160 | +static int mode_html(void) | ||
| 1161 | +{ | ||
| 1162 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 1163 | + "Cache-Control: no-store\r\n" | ||
| 1164 | + "X-Content-Type-Options: nosniff\r\n" | ||
| 1165 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | ||
| 1166 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | ||
| 1167 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | ||
| 1168 | + emit_ui(); | ||
| 1169 | + return 0; | ||
| 1170 | +} | ||
| 1171 | + | ||
| 1172 | +/* ------------------------------------------------------------------ */ | ||
| 1173 | +/* Control */ | ||
| 1174 | +/* ------------------------------------------------------------------ */ | ||
| 1175 | + | ||
| 1176 | +static int do_control(const char *unit, const char *op) | ||
| 1177 | +{ | ||
| 1178 | + if (!valid_unit(unit)) return 400; | ||
| 1179 | + if (!g_control) return 403; | ||
| 1180 | + if (strcmp(op, "start") != 0 && strcmp(op, "stop") != 0 && | ||
| 1181 | + strcmp(op, "restart") != 0) | ||
| 1182 | + return 400; | ||
| 1183 | + | ||
| 1184 | + { | ||
| 1185 | + const char *logp = getenv("SERVICES_MOCK_SYSTEMCTL_LOG"); | ||
| 1186 | + if (logp && *logp) { | ||
| 1187 | + FILE *f = fopen(logp, "a"); | ||
| 1188 | + if (f) { | ||
| 1189 | + fprintf(f, "systemctl %s %s\n", op, unit); | ||
| 1190 | + fclose(f); | ||
| 1191 | + } | ||
| 1192 | + return 0; | ||
| 1193 | + } | ||
| 1194 | + } | ||
| 1195 | + | ||
| 1196 | +#if defined(_WIN32) | ||
| 1197 | + { | ||
| 1198 | + SC_HANDLE scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_CONNECT); | ||
| 1199 | + SC_HANDLE svc; | ||
| 1200 | + int rc = 500; | ||
| 1201 | + if (!scm) return 500; | ||
| 1202 | + svc = OpenServiceA(scm, unit, | ||
| 1203 | + strcmp(op, "stop") == 0 ? SERVICE_STOP | ||
| 1204 | + : (SERVICE_START | SERVICE_STOP)); | ||
| 1205 | + if (!svc) { CloseServiceHandle(scm); return 404; } | ||
| 1206 | + if (strcmp(op, "start") == 0) { | ||
| 1207 | + if (StartServiceA(svc, 0, NULL)) rc = 0; | ||
| 1208 | + else if (GetLastError() == ERROR_SERVICE_ALREADY_RUNNING) rc = 0; | ||
| 1209 | + } else { | ||
| 1210 | + SERVICE_STATUS st; | ||
| 1211 | + if (ControlService(svc, SERVICE_CONTROL_STOP, &st)) rc = 0; | ||
| 1212 | + else if (GetLastError() == ERROR_SERVICE_NOT_ACTIVE) rc = 0; | ||
| 1213 | + } | ||
| 1214 | + CloseServiceHandle(svc); | ||
| 1215 | + CloseServiceHandle(scm); | ||
| 1216 | + return rc; | ||
| 1217 | + } | ||
| 1218 | +#elif defined(__APPLE__) | ||
| 1219 | + { | ||
| 1220 | + char *argv[4]; | ||
| 1221 | + int rc; | ||
| 1222 | + argv[0] = (char *)"launchctl"; | ||
| 1223 | + argv[1] = (char *)(strcmp(op, "stop") == 0 ? "stop" : "kickstart"); | ||
| 1224 | + argv[2] = (char *)("-k"); | ||
| 1225 | + argv[3] = (char *)unit; | ||
| 1226 | + if (strcmp(op, "stop") == 0) { argv[2] = (char *)unit; argv[3] = NULL; } | ||
| 1227 | + rc = run_argv(argv); | ||
| 1228 | + return rc == 0 ? 0 : 500; | ||
| 1229 | + } | ||
| 1230 | +#else | ||
| 1231 | + { | ||
| 1232 | + char *argv[4]; | ||
| 1233 | + int rc; | ||
| 1234 | + argv[0] = (char *)"systemctl"; | ||
| 1235 | + argv[1] = (char *)op; | ||
| 1236 | + argv[2] = (char *)unit; | ||
| 1237 | + argv[3] = NULL; | ||
| 1238 | + rc = run_argv(argv); | ||
| 1239 | + return rc == 0 ? 0 : 500; | ||
| 1240 | + } | ||
| 1241 | +#endif | ||
| 1242 | +} | ||
| 1243 | + | ||
| 1244 | +/* ------------------------------------------------------------------ */ | ||
| 1245 | +/* API dispatch */ | ||
| 1246 | +/* ------------------------------------------------------------------ */ | ||
| 1247 | + | ||
| 1248 | +static void err_json(int code, const char *status, const char *msg) | ||
| 1249 | +{ | ||
| 1250 | + printf("Status: %d %s\r\n", code, status); | ||
| 1251 | + print_json_header(); | ||
| 1252 | + printf("{\"ok\":false,\"error\":\"%s\"}\n", msg); | ||
| 1253 | +} | ||
| 1254 | + | ||
| 1255 | +static int mode_json(const char *qs) | ||
| 1256 | +{ | ||
| 1257 | + char action[64]; | ||
| 1258 | + char filter[32]; | ||
| 1259 | + char unit[256]; | ||
| 1260 | + char op[32]; | ||
| 1261 | + | ||
| 1262 | + action[0] = filter[0] = unit[0] = op[0] = '\0'; | ||
| 1263 | + get_query_val(qs, "action", action, sizeof action); | ||
| 1264 | + get_query_val(qs, "filter", filter, sizeof filter); | ||
| 1265 | + get_query_val(qs, "unit", unit, sizeof unit); | ||
| 1266 | + get_query_val(qs, "op", op, sizeof op); | ||
| 1267 | + | ||
| 1268 | + if (!action[0]) str_copy(action, sizeof action, "list"); | ||
| 1269 | + | ||
| 1270 | + collect_all(); | ||
| 1271 | + | ||
| 1272 | + if (strcmp(action, "list") == 0) { | ||
| 1273 | + buf_t b = { 0 }; | ||
| 1274 | + int i, shown = 0; | ||
| 1275 | + int running = 0, failed = 0, inactive = 0; | ||
| 1276 | + | ||
| 1277 | + for (i = 0; i < g_count; i++) { | ||
| 1278 | + if (svc_running(&g_svc[i])) running++; | ||
| 1279 | + else if (svc_failed(&g_svc[i])) failed++; | ||
| 1280 | + else inactive++; | ||
| 1281 | + } | ||
| 1282 | + | ||
| 1283 | + print_json_header(); | ||
| 1284 | + buf_puts(&b, "{\"ok\":true,\"init_system\":"); | ||
| 1285 | + json_into(&b, init_name()); | ||
| 1286 | + buf_puts(&b, ",\"control_enabled\":"); | ||
| 1287 | + buf_puts(&b, g_control ? "true" : "false"); | ||
| 1288 | + { | ||
| 1289 | + buf_t body; | ||
| 1290 | + char tmp[32]; | ||
| 1291 | + memset(&body, 0, sizeof body); | ||
| 1292 | + for (i = 0; i < g_count; i++) { | ||
| 1293 | + const svc_t *s = &g_svc[i]; | ||
| 1294 | + int keep = 1; | ||
| 1295 | + if (filter[0] && strcmp(filter, "all") != 0) { | ||
| 1296 | + if (strcmp(filter, "failed") == 0) keep = svc_failed(s); | ||
| 1297 | + else if (strcmp(filter, "running") == 0) keep = svc_running(s); | ||
| 1298 | + else if (strcmp(filter, "inactive") == 0) | ||
| 1299 | + keep = !svc_running(s) && !svc_failed(s); | ||
| 1300 | + } | ||
| 1301 | + if (!keep) continue; | ||
| 1302 | + if (shown) buf_putc(&body, ','); | ||
| 1303 | + emit_service(&body, s); | ||
| 1304 | + shown++; | ||
| 1305 | + } | ||
| 1306 | + buf_puts(&b, ",\"count\":"); | ||
| 1307 | + snprintf(tmp, sizeof tmp, "%d", shown); | ||
| 1308 | + buf_puts(&b, tmp); | ||
| 1309 | + buf_puts(&b, ",\"summary\":{\"running\":"); | ||
| 1310 | + snprintf(tmp, sizeof tmp, "%d", running); buf_puts(&b, tmp); | ||
| 1311 | + buf_puts(&b, ",\"failed\":"); | ||
| 1312 | + snprintf(tmp, sizeof tmp, "%d", failed); buf_puts(&b, tmp); | ||
| 1313 | + buf_puts(&b, ",\"inactive\":"); | ||
| 1314 | + snprintf(tmp, sizeof tmp, "%d", inactive); buf_puts(&b, tmp); | ||
| 1315 | + buf_puts(&b, "},\"services\":["); | ||
| 1316 | + buf_add(&b, buf_str(&body), body.n); | ||
| 1317 | + buf_puts(&b, "]}\n"); | ||
| 1318 | + buf_free(&body); | ||
| 1319 | + } | ||
| 1320 | + fwrite(buf_str(&b), 1, b.n, stdout); | ||
| 1321 | + buf_free(&b); | ||
| 1322 | + return 0; | ||
| 1323 | + } | ||
| 1324 | + | ||
| 1325 | + if (strcmp(action, "show") == 0) { | ||
| 1326 | + svc_t *s; | ||
| 1327 | + buf_t b = { 0 }; | ||
| 1328 | + | ||
| 1329 | + if (!unit[0]) { err_json(400, "Bad Request", "missing unit"); return 0; } | ||
| 1330 | + if (!valid_unit(unit)) { err_json(400, "Bad Request", "invalid unit"); return 0; } | ||
| 1331 | + s = svc_find(unit); | ||
| 1332 | + if (!s) { err_json(404, "Not Found", "service not found"); return 0; } | ||
| 1333 | + | ||
| 1334 | + print_json_header(); | ||
| 1335 | + buf_puts(&b, "{\"ok\":true,\"init_system\":"); | ||
| 1336 | + json_into(&b, init_name()); | ||
| 1337 | + buf_puts(&b, ",\"control_enabled\":"); | ||
| 1338 | + buf_puts(&b, g_control ? "true" : "false"); | ||
| 1339 | + buf_puts(&b, ",\"service\":"); | ||
| 1340 | + emit_service(&b, s); | ||
| 1341 | + buf_puts(&b, "}\n"); | ||
| 1342 | + fwrite(buf_str(&b), 1, b.n, stdout); | ||
| 1343 | + buf_free(&b); | ||
| 1344 | + return 0; | ||
| 1345 | + } | ||
| 1346 | + | ||
| 1347 | + if (strcmp(action, "control") == 0) { | ||
| 1348 | + int rc; | ||
| 1349 | + | ||
| 1350 | + /* Refuse by capability before by method: a node that never opted into | ||
| 1351 | + * control must not advertise a 405 that implies the route works. */ | ||
| 1352 | + if (!g_control) { err_json(403, "Forbidden", "control_disabled"); return 0; } | ||
| 1353 | + if (!is_post_request()) { | ||
| 1354 | + err_json(405, "Method Not Allowed", "control requires POST"); | ||
| 1355 | + return 0; | ||
| 1356 | + } | ||
| 1357 | + if (!valid_unit(unit)) { err_json(400, "Bad Request", "invalid unit"); return 0; } | ||
| 1358 | + if (strcmp(op, "start") != 0 && strcmp(op, "stop") != 0 && | ||
| 1359 | + strcmp(op, "restart") != 0) { | ||
| 1360 | + err_json(400, "Bad Request", "op must be start|stop|restart"); | ||
| 1361 | + return 0; | ||
| 1362 | + } | ||
| 1363 | + rc = do_control(unit, op); | ||
| 1364 | + if (rc == 403) { err_json(403, "Forbidden", "control_disabled"); return 0; } | ||
| 1365 | + if (rc == 400) { err_json(400, "Bad Request", "invalid request"); return 0; } | ||
| 1366 | + if (rc == 404) { err_json(404, "Not Found", "service not found"); return 0; } | ||
| 1367 | + if (rc != 0) { err_json(500, "Internal Server Error", "control failed"); return 0; } | ||
| 1368 | + | ||
| 1369 | + print_json_header(); | ||
| 1370 | + printf("{\"ok\":true,\"unit\":\"%s\",\"op\":\"%s\"," | ||
| 1371 | + "\"control_enabled\":true,\"init_system\":\"%s\"}\n", | ||
| 1372 | + unit, op, init_name()); | ||
| 1373 | + return 0; | ||
| 1374 | + } | ||
| 1375 | + | ||
| 1376 | + err_json(400, "Bad Request", "unknown action"); | ||
| 1377 | + return 0; | ||
| 1378 | +} | ||
| 1379 | + | ||
| 1380 | +static int mode_meta(void) | ||
| 1381 | +{ | ||
| 1382 | + printf("{\"name\":\"%s\",\"desc\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC); | ||
| 1383 | + return 0; | ||
| 1384 | +} | ||
| 1385 | + | ||
| 1386 | +int main(int argc, char **argv) | ||
| 1387 | +{ | ||
| 1388 | + const char *qs; | ||
| 1389 | + | ||
| 1390 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || | ||
| 1391 | + (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META"))) | ||
| 1392 | + return mode_meta(); | ||
| 1393 | + | ||
| 1394 | + if (argc > 1 && strcmp(argv[1], "--version") == 0) { | ||
| 1395 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | ||
| 1396 | + return 0; | ||
| 1397 | + } | ||
| 1398 | + | ||
| 1399 | + require_node_auth(); | ||
| 1400 | + | ||
| 1401 | + qs = getenv("QUERY_STRING"); | ||
| 1402 | + if (!qs) qs = ""; | ||
| 1403 | + | ||
| 1404 | + if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request()) | ||
| 1405 | + return mode_json(qs); | ||
| 1406 | + | ||
| 1407 | + return mode_html(); | ||
| 1408 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..4b636d4 | index 0000000..4b636d4 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui.html | +++ b/src/ui.html | ||
| @@ -0,0 +1,431 @@ | @@ -0,0 +1,431 @@ | ||
| 1 | +<!DOCTYPE html> | ||
| 2 | +<html lang="en"><head><meta charset="utf-8"> | ||
| 3 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | ||
| 4 | +<title>services</title> | ||
| 5 | +<!--TOKENS--> | ||
| 6 | +<style> | ||
| 7 | +*{box-sizing:border-box} | ||
| 8 | +html,body{margin:0;min-height:100%} | ||
| 9 | +body{background:var(--bg);color:var(--tx,var(--text));font-family:var(--font); | ||
| 10 | + font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased} | ||
| 11 | +.wrap{max-width:1180px;margin:0 auto;padding:18px 18px 40px} | ||
| 12 | +.top{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px} | ||
| 13 | +.brand{font-size:11px;font-weight:700;letter-spacing:.09em;text-transform:uppercase; | ||
| 14 | + color:var(--mu,var(--text-2))} | ||
| 15 | +.title{font-size:19px;font-weight:680;margin:0;letter-spacing:-.01em} | ||
| 16 | +.sp{flex:1 1 auto} | ||
| 17 | +.pill{font-size:11px;font-weight:600;padding:3px 9px;border-radius:999px; | ||
| 18 | + background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2)); | ||
| 19 | + border:1px solid var(--ln,var(--line));white-space:nowrap} | ||
| 20 | +.icon-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px; | ||
| 21 | + background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line)); | ||
| 22 | + color:var(--text);border-radius:9px;height:30px;padding:0 11px;cursor:pointer; | ||
| 23 | + font-family:inherit;font-size:12px;font-weight:600} | ||
| 24 | +.icon-btn:hover{background:var(--surface-hover);border-color:var(--line-2)} | ||
| 25 | +.icon-btn:active{transform:scale(.97)} | ||
| 26 | +.icon-btn svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.9; | ||
| 27 | + stroke-linecap:round;stroke-linejoin:round} | ||
| 28 | + | ||
| 29 | +.chips{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px; | ||
| 30 | + margin-bottom:14px} | ||
| 31 | +.chip{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line)); | ||
| 32 | + border-radius:12px;padding:11px 13px;cursor:pointer;font-family:inherit; | ||
| 33 | + text-align:left;color:var(--text)} | ||
| 34 | +.chip:hover{border-color:var(--line-2)} | ||
| 35 | +.chip.sel{box-shadow:inset 0 0 0 1.5px var(--ac,var(--blue))} | ||
| 36 | +.chip .k{display:flex;align-items:center;gap:6px;font-size:10.5px;font-weight:700; | ||
| 37 | + letter-spacing:.07em;text-transform:uppercase;color:var(--mu,var(--text-2))} | ||
| 38 | +.chip .k svg{width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:2; | ||
| 39 | + stroke-linecap:round;stroke-linejoin:round} | ||
| 40 | +.chip .v{font-family:var(--mono);font-size:23px;font-weight:700;margin-top:3px; | ||
| 41 | + letter-spacing:-.02em} | ||
| 42 | +.chip.ok .v{color:var(--green)} | ||
| 43 | +.chip.bad .v{color:var(--red)} | ||
| 44 | +.chip.none .v{color:var(--mu,var(--text-2))} | ||
| 45 | + | ||
| 46 | +.bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:10px} | ||
| 47 | +.search{flex:1 1 240px;min-width:0;padding:9px 12px;border-radius:10px; | ||
| 48 | + border:1px solid var(--ln,var(--line));background:var(--input-bg);color:var(--text); | ||
| 49 | + font-family:inherit;font-size:13px} | ||
| 50 | +.search:focus{outline:2px solid var(--ac,var(--blue));outline-offset:-1px} | ||
| 51 | +select{padding:9px 11px;border-radius:10px;border:1px solid var(--ln,var(--line)); | ||
| 52 | + background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px} | ||
| 53 | + | ||
| 54 | +.panel{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line)); | ||
| 55 | + border-radius:14px;overflow:hidden} | ||
| 56 | +.tb{width:100%;overflow-x:auto} | ||
| 57 | +table{width:100%;border-collapse:collapse;font-size:13px} | ||
| 58 | +th{text-align:left;font-size:10.5px;letter-spacing:.07em;text-transform:uppercase; | ||
| 59 | + color:var(--mu,var(--text-2));font-weight:700;padding:9px 12px; | ||
| 60 | + border-bottom:1px solid var(--ln,var(--line));white-space:nowrap; | ||
| 61 | + background:var(--sf2,var(--surface-2))} | ||
| 62 | +td{padding:9px 12px;border-bottom:1px solid var(--ln,var(--line)); | ||
| 63 | + vertical-align:middle;white-space:nowrap} | ||
| 64 | +tr.row{cursor:pointer} | ||
| 65 | +tr.row:hover td{background:var(--surface-hover)} | ||
| 66 | +tr.row:last-child td{border-bottom:0} | ||
| 67 | +tr.row.sel td{background:var(--sf2,var(--surface-2))} | ||
| 68 | +.mo{font-family:var(--mono);font-size:12.5px} | ||
| 69 | +.name{font-weight:600;max-width:340px;overflow:hidden;text-overflow:ellipsis} | ||
| 70 | +.desc{font-size:11.5px;color:var(--mu,var(--text-2));max-width:340px; | ||
| 71 | + overflow:hidden;text-overflow:ellipsis;margin-top:1px} | ||
| 72 | +.tag{font-size:10px;font-weight:700;padding:2px 8px;border-radius:6px; | ||
| 73 | + white-space:nowrap;letter-spacing:.03em} | ||
| 74 | +.t-run{background:rgba(48,209,88,.16);color:var(--green)} | ||
| 75 | +.t-fail{background:rgba(255,69,58,.16);color:var(--red)} | ||
| 76 | +.t-off{background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2)); | ||
| 77 | + border:1px solid var(--ln,var(--line))} | ||
| 78 | +.t-warn{background:rgba(255,159,10,.16);color:var(--orange)} | ||
| 79 | +.dot{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:6px; | ||
| 80 | + vertical-align:1px} | ||
| 81 | +.d-run{background:var(--green)}.d-fail{background:var(--red)} | ||
| 82 | +.d-off{background:var(--gray)}.d-warn{background:var(--orange)} | ||
| 83 | +.empty{padding:26px 14px;text-align:center;color:var(--mu,var(--text-2));font-size:13px} | ||
| 84 | +.hide{display:none!important} | ||
| 85 | + | ||
| 86 | +/* detail drawer */ | ||
| 87 | +.scrim{position:fixed;inset:0;background:rgba(0,0,0,.38);opacity:0;pointer-events:none; | ||
| 88 | + transition:opacity .18s var(--ease);z-index:40} | ||
| 89 | +.scrim.open{opacity:1;pointer-events:auto} | ||
| 90 | +.drawer{position:fixed;top:0;right:0;bottom:0;width:min(430px,100%);z-index:41; | ||
| 91 | + background:var(--bg-2,var(--bg-card));border-left:1px solid var(--ln,var(--line)); | ||
| 92 | + box-shadow:var(--shadow-lg);transform:translateX(102%); | ||
| 93 | + transition:transform .22s var(--ease);display:flex;flex-direction:column; | ||
| 94 | + max-width:100%} | ||
| 95 | +.drawer.open{transform:none} | ||
| 96 | +.dh{display:flex;align-items:flex-start;gap:10px;padding:16px 16px 12px; | ||
| 97 | + border-bottom:1px solid var(--ln,var(--line))} | ||
| 98 | +.dh .t{flex:1 1 auto;min-width:0} | ||
| 99 | +.dh .n{font-size:15px;font-weight:680;word-break:break-all} | ||
| 100 | +.dh .s{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:3px; | ||
| 101 | + word-break:break-word} | ||
| 102 | +.dbody{flex:1 1 auto;overflow-y:auto;padding:14px 16px 24px} | ||
| 103 | +.kv{display:grid;grid-template-columns:110px minmax(0,1fr);gap:8px 12px; | ||
| 104 | + font-size:12.5px;margin-bottom:16px} | ||
| 105 | +.kv .k{color:var(--mu,var(--text-2))} | ||
| 106 | +.kv .v{font-family:var(--mono);word-break:break-all} | ||
| 107 | +.ctl{display:flex;gap:8px;flex-wrap:wrap;border-top:1px solid var(--ln,var(--line)); | ||
| 108 | + padding-top:14px;margin-top:4px} | ||
| 109 | +.btn{background:var(--ac,var(--blue));color:#fff;border:0;border-radius:999px; | ||
| 110 | + padding:8px 16px;font-weight:650;font-size:12.5px;cursor:pointer;font-family:inherit} | ||
| 111 | +.btn:active{transform:scale(.98)} | ||
| 112 | +.btn.gh{background:transparent;color:var(--text);border:1px solid var(--ln,var(--line))} | ||
| 113 | +.btn.warn{background:var(--orange)} | ||
| 114 | +.btn.bad{background:var(--red)} | ||
| 115 | +.note{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:10px} | ||
| 116 | +.out{margin-top:12px;padding:10px 12px;border-radius:10px;font-size:12.5px; | ||
| 117 | + background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line)); | ||
| 118 | + word-break:break-word} | ||
| 119 | +.out.err{color:var(--red);border-color:rgba(255,69,58,.4)} | ||
| 120 | +.out.ok{color:var(--green);border-color:rgba(48,209,88,.35)} | ||
| 121 | + | ||
| 122 | +@media(max-width:860px){ | ||
| 123 | + .wrap{padding:14px 12px 32px} | ||
| 124 | + .name,.desc{max-width:200px} | ||
| 125 | + th.h-opt,td.h-opt{display:none} | ||
| 126 | +} | ||
| 127 | +@media(max-width:600px){ | ||
| 128 | + .wrap{padding:12px 10px 28px} | ||
| 129 | + .title{font-size:17px} | ||
| 130 | + .chips{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} | ||
| 131 | + .chip .v{font-size:20px} | ||
| 132 | + .name,.desc{max-width:150px} | ||
| 133 | + th.h-since,td.h-since{display:none} | ||
| 134 | + .drawer{width:100%} | ||
| 135 | +} | ||
| 136 | +</style></head><body> | ||
| 137 | +<div class="wrap"> | ||
| 138 | + <div class="top"> | ||
| 139 | + <div> | ||
| 140 | + <div class="brand">SCORPIOX BOT</div> | ||
| 141 | + <h1 class="title">Services</h1> | ||
| 142 | + </div> | ||
| 143 | + <span class="sp"></span> | ||
| 144 | + <span class="pill" id="initPill">init: —</span> | ||
| 145 | + <button class="icon-btn embed-hide" id="btnRefresh" type="button" title="Reload"> | ||
| 146 | + <svg viewBox="0 0 24 24"><path d="M20 12a8 8 0 1 1-2.3-5.7"/><path d="M20 4v5h-5"/></svg> | ||
| 147 | + Refresh | ||
| 148 | + </button> | ||
| 149 | + <button class="icon-btn embed-hide" id="btnTheme" type="button" title="Toggle appearance"> | ||
| 150 | + <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4.2"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.4 1.4M17.6 17.6L19 19M19 5l-1.4 1.4M6.4 17.6L5 19"/></svg> | ||
| 151 | + </button> | ||
| 152 | + </div> | ||
| 153 | + | ||
| 154 | + <div class="chips"> | ||
| 155 | + <button class="chip" id="cAll" type="button"><div class="k">All</div><div class="v" id="vAll">—</div></button> | ||
| 156 | + <button class="chip ok" id="cRun" type="button"><div class="k"><span class="dot d-run"></span>Running</div><div class="v" id="vRun">—</div></button> | ||
| 157 | + <button class="chip bad" id="cFail" type="button"><div class="k"><span class="dot d-fail"></span>Failed</div><div class="v" id="vFail">—</div></button> | ||
| 158 | + <button class="chip none" id="cOff" type="button"><div class="k"><span class="dot d-off"></span>Inactive</div><div class="v" id="vOff">—</div></button> | ||
| 159 | + </div> | ||
| 160 | + | ||
| 161 | + <div class="bar"> | ||
| 162 | + <input class="search" id="q" type="search" placeholder="Search name or description" autocomplete="off" spellcheck="false"> | ||
| 163 | + <select id="sort" title="Sort"> | ||
| 164 | + <option value="failed">Sort: failed first</option> | ||
| 165 | + <option value="name">Sort: name</option> | ||
| 166 | + <option value="state">Sort: state</option> | ||
| 167 | + </select> | ||
| 168 | + </div> | ||
| 169 | + | ||
| 170 | + <div class="panel"> | ||
| 171 | + <div class="tb"> | ||
| 172 | + <table> | ||
| 173 | + <thead><tr> | ||
| 174 | + <th>Service</th> | ||
| 175 | + <th>State</th> | ||
| 176 | + <th class="h-opt">Enabled</th> | ||
| 177 | + <th class="h-opt">PID</th> | ||
| 178 | + <th class="h-opt">Memory</th> | ||
| 179 | + <th class="h-since">Since</th> | ||
| 180 | + </tr></thead> | ||
| 181 | + <tbody id="rows"></tbody> | ||
| 182 | + </table> | ||
| 183 | + </div> | ||
| 184 | + <div id="empty" class="empty hide">No services matched this filter.</div> | ||
| 185 | + </div> | ||
| 186 | +</div> | ||
| 187 | + | ||
| 188 | +<div class="scrim" id="scrim"></div> | ||
| 189 | +<aside class="drawer" id="drawer" aria-hidden="true"> | ||
| 190 | + <div class="dh"> | ||
| 191 | + <div class="t"><div class="n" id="dName">—</div><div class="s" id="dDesc"></div></div> | ||
| 192 | + <button class="icon-btn" id="dClose" type="button" title="Close"> | ||
| 193 | + <svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6L6 18"/></svg> | ||
| 194 | + </button> | ||
| 195 | + </div> | ||
| 196 | + <div class="dbody"> | ||
| 197 | + <div class="kv"> | ||
| 198 | + <div class="k">State</div><div class="v" id="dState">—</div> | ||
| 199 | + <div class="k">Sub-state</div><div class="v" id="dSub">—</div> | ||
| 200 | + <div class="k">Enabled</div><div class="v" id="dEnabled">—</div> | ||
| 201 | + <div class="k">PID</div><div class="v" id="dPid">—</div> | ||
| 202 | + <div class="k">Memory</div><div class="v" id="dMem">—</div> | ||
| 203 | + <div class="k">Since</div><div class="v" id="dSince">—</div> | ||
| 204 | + </div> | ||
| 205 | + <div class="ctl hide" id="dCtl"> | ||
| 206 | + <button class="btn" id="opStart" type="button">Start</button> | ||
| 207 | + <button class="btn warn" id="opRestart" type="button">Restart</button> | ||
| 208 | + <button class="btn bad" id="opStop" type="button">Stop</button> | ||
| 209 | + </div> | ||
| 210 | + <div class="note hide" id="dNote"></div> | ||
| 211 | + <div class="out hide" id="dOut"></div> | ||
| 212 | + </div> | ||
| 213 | +</aside> | ||
| 214 | + | ||
| 215 | +<script> | ||
| 216 | +(function(){ | ||
| 217 | +"use strict"; | ||
| 218 | +var q=new URLSearchParams(location.search); | ||
| 219 | +var node=q.get('node')||''; | ||
| 220 | +var sid=q.get('id')||''; | ||
| 221 | +var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))|| | ||
| 222 | + localStorage.getItem('bot_active_pwd')||''; | ||
| 223 | +var HUB=q.get('plugin')||''; | ||
| 224 | + | ||
| 225 | +/* Two call routes. Through the hub -> call the hub proxy back. Opened directly | ||
| 226 | + * on the node -> the plugin itself is the route. Calling /plugins?plugin= on the | ||
| 227 | + * node returns the discovery list, not this plugin. */ | ||
| 228 | +function api(action,extra,method){ | ||
| 229 | + var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_services')+ | ||
| 230 | + '?action='+encodeURIComponent(action)+(extra?('&'+extra):'')+ | ||
| 231 | + (node?'&node='+encodeURIComponent(node):'')+ | ||
| 232 | + (sid?'&id='+encodeURIComponent(sid):'')+ | ||
| 233 | + (pwd?'&pwd='+encodeURIComponent(pwd):''); | ||
| 234 | + return fetch(u,{method:method||'GET',headers:pwd?{'X-Bot-Password':pwd}:{}}) | ||
| 235 | + .then(function(r){return r.json();}); | ||
| 236 | +} | ||
| 237 | +function $(id){return document.getElementById(id);} | ||
| 238 | +function esc(v){return String(v==null?'':v).replace(/[&<>"']/g,function(c){ | ||
| 239 | + return({'&':'&','<':'<','>':'>','"':'"',"'":'''})[c];});} | ||
| 240 | +function bytes(n){ | ||
| 241 | + if(n==null||n===0) return '—'; | ||
| 242 | + var u=['B','KiB','MiB','GiB','TiB'],i=0,v=n; | ||
| 243 | + while(v>=1024&&i<u.length-1){v/=1024;i++;} | ||
| 244 | + return (v>=100?Math.round(v):(Math.round(v*10)/10))+' '+u[i]; | ||
| 245 | +} | ||
| 246 | +var DATA=[],CTL=false,FILTER='',SORT='failed',SEL=null; | ||
| 247 | + | ||
| 248 | +function stateCls(s){ | ||
| 249 | + if(s.failed||s.active==='failed') return 'fail'; | ||
| 250 | + if(s.active==='running'||s.active==='active'||s.sub==='running') return 'run'; | ||
| 251 | + if(s.active==='paused'||s.active==='starting'||s.active==='stopping') return 'warn'; | ||
| 252 | + return 'off'; | ||
| 253 | +} | ||
| 254 | +function stateLabel(s){ | ||
| 255 | + var c=stateCls(s); | ||
| 256 | + if(c==='run') return 'running'; | ||
| 257 | + if(c==='fail') return 'failed'; | ||
| 258 | + if(c==='warn') return s.active||'pending'; | ||
| 259 | + return s.active==='inactive'?'inactive':(s.active||'inactive'); | ||
| 260 | +} | ||
| 261 | +/* unused helper removed: stateLabel(s) already returns the visible label */ | ||
| 262 | + | ||
| 263 | +function visible(){ | ||
| 264 | + var f=FILTER, needle=($('q').value||'').toLowerCase(); | ||
| 265 | + var out=DATA.filter(function(s){ | ||
| 266 | + if(f==='running'&&stateCls(s)!=='run') return false; | ||
| 267 | + if(f==='failed'&&stateCls(s)!=='fail') return false; | ||
| 268 | + if(f==='inactive'&&stateCls(s)!=='off') return false; | ||
| 269 | + if(needle){ | ||
| 270 | + var hay=(s.name+' '+(s.description||'')).toLowerCase(); | ||
| 271 | + if(hay.indexOf(needle)<0) return false; | ||
| 272 | + } | ||
| 273 | + return true; | ||
| 274 | + }); | ||
| 275 | + if(SORT==='name') out.sort(function(a,b){return a.name<b.name?-1:a.name>b.name?1:0;}); | ||
| 276 | + else if(SORT==='state') out.sort(function(a,b){ | ||
| 277 | + var x=stateCls(a),y=stateCls(b); | ||
| 278 | + if(x!==y) return x<y?-1:1; | ||
| 279 | + return a.name<b.name?-1:1;}); | ||
| 280 | + return out; | ||
| 281 | +} | ||
| 282 | + | ||
| 283 | +function render(){ | ||
| 284 | + var rows=visible(); | ||
| 285 | + var h=''; | ||
| 286 | + for(var i=0;i<rows.length;i++){ | ||
| 287 | + var s=rows[i],c=stateCls(s); | ||
| 288 | + h+='<tr class="row'+(SEL&&SEL===s.name?' sel':'')+'" data-n="'+esc(s.name)+'">'+ | ||
| 289 | + '<td><div class="name" title="'+esc(s.name)+'">'+esc(s.name)+'</div>'+ | ||
| 290 | + (s.description?'<div class="desc" title="'+esc(s.description)+'">'+esc(s.description)+'</div>':'')+ | ||
| 291 | + '</td>'+ | ||
| 292 | + '<td><span class="tag t-'+c+'"><span class="dot d-'+c+'"></span>'+ | ||
| 293 | + esc(stateLabel(s))+'</span></td>'+ | ||
| 294 | + '<td class="mo h-opt">'+esc(s.enabled||'-')+'</td>'+ | ||
| 295 | + '<td class="mo h-opt">'+(s.pid>0?esc(s.pid):'—')+'</td>'+ | ||
| 296 | + '<td class="mo h-opt">'+bytes(s.memory_bytes)+'</td>'+ | ||
| 297 | + '<td class="mo h-since">'+esc(s.since||'—')+'</td></tr>'; | ||
| 298 | + } | ||
| 299 | + $('rows').innerHTML=h; | ||
| 300 | + $('empty').className=rows.length?'empty hide':'empty'; | ||
| 301 | + var trs=$('rows').querySelectorAll('tr.row'); | ||
| 302 | + for(var k=0;k<trs.length;k++){ | ||
| 303 | + trs[k].onclick=function(){open(this.getAttribute('data-n'));}; | ||
| 304 | + } | ||
| 305 | +} | ||
| 306 | + | ||
| 307 | +function load(){ | ||
| 308 | + return api('list','filter=all').then(function(d){ | ||
| 309 | + if(!d||!d.ok){ throw new Error((d&&d.error)||'load failed'); } | ||
| 310 | + DATA=d.services||[]; | ||
| 311 | + CTL=!!d.control_enabled; | ||
| 312 | + var sum=d.summary||{}; | ||
| 313 | + $('vAll').textContent=DATA.length; | ||
| 314 | + $('vRun').textContent=sum.running||0; | ||
| 315 | + $('vFail').textContent=sum.failed||0; | ||
| 316 | + $('vOff').textContent=sum.inactive||0; | ||
| 317 | + $('initPill').textContent='init: '+(d.init_system||'unknown')+ | ||
| 318 | + (CTL?' · control on':' · read-only'); | ||
| 319 | + render(); | ||
| 320 | + }); | ||
| 321 | +} | ||
| 322 | + | ||
| 323 | +function open(name){ | ||
| 324 | + var s=null; | ||
| 325 | + for(var i=0;i<DATA.length;i++) if(DATA[i].name===name){s=DATA[i];break;} | ||
| 326 | + if(!s) return; | ||
| 327 | + SEL=name; | ||
| 328 | + $('dName').textContent=s.name; | ||
| 329 | + $('dDesc').textContent=s.description||''; | ||
| 330 | + $('dState').textContent=stateLabel(s); | ||
| 331 | + $('dSub').textContent=s.sub||'—'; | ||
| 332 | + $('dEnabled').textContent=s.enabled||'-'; | ||
| 333 | + $('dPid').textContent=s.pid>0?s.pid:'—'; | ||
| 334 | + $('dMem').textContent=bytes(s.memory_bytes); | ||
| 335 | + $('dSince').textContent=s.since||'—'; | ||
| 336 | + $('dOut').className='out hide'; | ||
| 337 | + $('dOut').textContent=''; | ||
| 338 | + if(CTL){ | ||
| 339 | + $('dCtl').className='ctl'; | ||
| 340 | + $('dNote').className='note'; | ||
| 341 | + $('dNote').textContent='Control is enabled on this node (SERVICES_ALLOW_CONTROL=1). Every action is sent as a separate argv element, never through a shell.'; | ||
| 342 | + }else{ | ||
| 343 | + $('dCtl').className='ctl hide'; | ||
| 344 | + $('dNote').className='note'; | ||
| 345 | + $('dNote').textContent='Read-only: set SERVICES_ALLOW_CONTROL=1 in this node\'s plugin environment to enable start, stop and restart.'; | ||
| 346 | + } | ||
| 347 | + $('drawer').className='drawer open'; | ||
| 348 | + $('drawer').setAttribute('aria-hidden','false'); | ||
| 349 | + $('scrim').className='scrim open'; | ||
| 350 | + render(); | ||
| 351 | +} | ||
| 352 | +function close(){ | ||
| 353 | + SEL=null; | ||
| 354 | + $('drawer').className='drawer'; | ||
| 355 | + $('drawer').setAttribute('aria-hidden','true'); | ||
| 356 | + $('scrim').className='scrim'; | ||
| 357 | + render(); | ||
| 358 | +} | ||
| 359 | + | ||
| 360 | +function control(op){ | ||
| 361 | + if(!SEL) return; | ||
| 362 | + var label={start:'start',stop:'stop',restart:'restart'}[op]; | ||
| 363 | + if(!window.confirm(label+' '+SEL+'?\n\nThis runs '+label+' on the node\'s service manager.')) return; | ||
| 364 | + var o=$('dOut'); | ||
| 365 | + o.className='out'; | ||
| 366 | + o.textContent='Sending '+label+' '+SEL+' ...'; | ||
| 367 | + api('control','unit='+encodeURIComponent(SEL)+'&op='+encodeURIComponent(op),'POST') | ||
| 368 | + .then(function(d){ | ||
| 369 | + if(d&&d.ok){ | ||
| 370 | + o.className='out ok'; | ||
| 371 | + o.textContent=label+' requested for '+SEL+'.'; | ||
| 372 | + setTimeout(function(){load().then(function(){ | ||
| 373 | + for(var i=0;i<DATA.length;i++) if(DATA[i].name===SEL){ show(DATA[i]); break; } | ||
| 374 | + });},700); | ||
| 375 | + }else{ | ||
| 376 | + o.className='out err'; | ||
| 377 | + o.textContent=(d&&(d.error||('HTTP error')))+''; | ||
| 378 | + } | ||
| 379 | + }).catch(function(e){ | ||
| 380 | + o.className='out err'; | ||
| 381 | + o.textContent='Request failed: '+e.message; | ||
| 382 | + }); | ||
| 383 | +} | ||
| 384 | +function show(s){ | ||
| 385 | + $('dState').textContent=stateLabel(s); | ||
| 386 | + $('dSub').textContent=s.sub||'—'; | ||
| 387 | + $('dEnabled').textContent=s.enabled||'-'; | ||
| 388 | + $('dPid').textContent=s.pid>0?s.pid:'—'; | ||
| 389 | + $('dMem').textContent=bytes(s.memory_bytes); | ||
| 390 | + $('dSince').textContent=s.since||'—'; | ||
| 391 | + render(); | ||
| 392 | +} | ||
| 393 | + | ||
| 394 | +function setFilter(f){ | ||
| 395 | + FILTER=f; | ||
| 396 | + var ids={all:'cAll',running:'cRun',failed:'cFail',inactive:'cOff'}; | ||
| 397 | + for(var k in ids) $(ids[k]).className='chip'+(k===f?' sel':'')+ | ||
| 398 | + (k==='running'?' ok':k==='failed'?' bad':k==='inactive'?' none':''); | ||
| 399 | + render(); | ||
| 400 | +} | ||
| 401 | + | ||
| 402 | +$('cAll').onclick=function(){setFilter('');}; | ||
| 403 | +$('cRun').onclick=function(){setFilter('running');}; | ||
| 404 | +$('cFail').onclick=function(){setFilter('failed');}; | ||
| 405 | +$('cOff').onclick=function(){setFilter('inactive');}; | ||
| 406 | +$('q').oninput=render; | ||
| 407 | +$('sort').onchange=function(){SORT=this.value;render();}; | ||
| 408 | +$('btnRefresh').onclick=function(){load();}; | ||
| 409 | +$('dClose').onclick=close; | ||
| 410 | +$('scrim').onclick=close; | ||
| 411 | +$('opStart').onclick=function(){control('start');}; | ||
| 412 | +$('opStop').onclick=function(){control('stop');}; | ||
| 413 | +$('opRestart').onclick=function(){control('restart');}; | ||
| 414 | +if(window.sxApplyTheme){ | ||
| 415 | + $('btnTheme').onclick=function(){ | ||
| 416 | + window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark'); | ||
| 417 | + }; | ||
| 418 | +}else{ | ||
| 419 | + $('btnTheme').className='icon-btn embed-hide hide'; | ||
| 420 | +} | ||
| 421 | +document.addEventListener('keydown',function(e){ | ||
| 422 | + if(e.key==='Escape'&&SEL) close(); | ||
| 423 | +}); | ||
| 424 | +setFilter(''); | ||
| 425 | +load().catch(function(e){ | ||
| 426 | + $('empty').className='empty'; | ||
| 427 | + $('empty').textContent='Could not load services: '+e.message; | ||
| 428 | +}); | ||
| 429 | +})(); | ||
| 430 | +</script> | ||
| 431 | +</body></html> |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..88517f0 | index 0000000..88517f0 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui_html.h | +++ b/src/ui_html.h | ||
| @@ -0,0 +1,439 @@ | @@ -0,0 +1,439 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | ||
| 2 | +#ifndef SX_SERVICES_UI_HTML_H | ||
| 3 | +#define SX_SERVICES_UI_HTML_H | ||
| 4 | + | ||
| 5 | +static const char *UI_HTML = | ||
| 6 | + "<!DOCTYPE html>\n" | ||
| 7 | + "<html lang=\"en\"><head><meta charset=\"utf-8\">\n" | ||
| 8 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | ||
| 9 | + "<title>services</title>\n" | ||
| 10 | + "\001\n" | ||
| 11 | + "<style>\n" | ||
| 12 | + "*{box-sizing:border-box}\n" | ||
| 13 | + "html,body{margin:0;min-height:100%}\n" | ||
| 14 | + "body{background:var(--bg);color:var(--tx,var(--text));font-family:var(--font);\n" | ||
| 15 | + " font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}\n" | ||
| 16 | + ".wrap{max-width:1180px;margin:0 auto;padding:18px 18px 40px}\n" | ||
| 17 | + ".top{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}\n" | ||
| 18 | + ".brand{font-size:11px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;\n" | ||
| 19 | + " color:var(--mu,var(--text-2))}\n" | ||
| 20 | + ".title{font-size:19px;font-weight:680;margin:0;letter-spacing:-.01em}\n" | ||
| 21 | + ".sp{flex:1 1 auto}\n" | ||
| 22 | + ".pill{font-size:11px;font-weight:600;padding:3px 9px;border-radius:999px;\n" | ||
| 23 | + " background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2));\n" | ||
| 24 | + " border:1px solid var(--ln,var(--line));white-space:nowrap}\n" | ||
| 25 | + ".icon-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;\n" | ||
| 26 | + " background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line));\n" | ||
| 27 | + " color:var(--text);border-radius:9px;height:30px;padding:0 11px;cursor:pointer;\n" | ||
| 28 | + " font-family:inherit;font-size:12px;font-weight:600}\n" | ||
| 29 | + ".icon-btn:hover{background:var(--surface-hover);border-color:var(--line-2)}\n" | ||
| 30 | + ".icon-btn:active{transform:scale(.97)}\n" | ||
| 31 | + ".icon-btn svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.9;\n" | ||
| 32 | + " stroke-linecap:round;stroke-linejoin:round}\n" | ||
| 33 | + "\n" | ||
| 34 | + ".chips{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px;\n" | ||
| 35 | + " margin-bottom:14px}\n" | ||
| 36 | + ".chip{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));\n" | ||
| 37 | + " border-radius:12px;padding:11px 13px;cursor:pointer;font-family:inherit;\n" | ||
| 38 | + " text-align:left;color:var(--text)}\n" | ||
| 39 | + ".chip:hover{border-color:var(--line-2)}\n" | ||
| 40 | + ".chip.sel{box-shadow:inset 0 0 0 1.5px var(--ac,var(--blue))}\n" | ||
| 41 | + ".chip .k{display:flex;align-items:center;gap:6px;font-size:10.5px;font-weight:700;\n" | ||
| 42 | + " letter-spacing:.07em;text-transform:uppercase;color:var(--mu,var(--text-2))}\n" | ||
| 43 | + ".chip .k svg{width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:2;\n" | ||
| 44 | + " stroke-linecap:round;stroke-linejoin:round}\n" | ||
| 45 | + ".chip .v{font-family:var(--mono);font-size:23px;font-weight:700;margin-top:3px;\n" | ||
| 46 | + " letter-spacing:-.02em}\n" | ||
| 47 | + ".chip.ok .v{color:var(--green)}\n" | ||
| 48 | + ".chip.bad .v{color:var(--red)}\n" | ||
| 49 | + ".chip.none .v{color:var(--mu,var(--text-2))}\n" | ||
| 50 | + "\n" | ||
| 51 | + ".bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:10px}\n" | ||
| 52 | + ".search{flex:1 1 240px;min-width:0;padding:9px 12px;border-radius:10px;\n" | ||
| 53 | + " border:1px solid var(--ln,var(--line));background:var(--input-bg);color:var(--text);\n" | ||
| 54 | + " font-family:inherit;font-size:13px}\n" | ||
| 55 | + ".search:focus{outline:2px solid var(--ac,var(--blue));outline-offset:-1px}\n" | ||
| 56 | + "select{padding:9px 11px;border-radius:10px;border:1px solid var(--ln,var(--line));\n" | ||
| 57 | + " background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px}\n" | ||
| 58 | + "\n" | ||
| 59 | + ".panel{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));\n" | ||
| 60 | + " border-radius:14px;overflow:hidden}\n" | ||
| 61 | + ".tb{width:100%;overflow-x:auto}\n" | ||
| 62 | + "table{width:100%;border-collapse:collapse;font-size:13px}\n" | ||
| 63 | + "th{text-align:left;font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;\n" | ||
| 64 | + " color:var(--mu,var(--text-2));font-weight:700;padding:9px 12px;\n" | ||
| 65 | + " border-bottom:1px solid var(--ln,var(--line));white-space:nowrap;\n" | ||
| 66 | + " background:var(--sf2,var(--surface-2))}\n" | ||
| 67 | + "td{padding:9px 12px;border-bottom:1px solid var(--ln,var(--line));\n" | ||
| 68 | + " vertical-align:middle;white-space:nowrap}\n" | ||
| 69 | + "tr.row{cursor:pointer}\n" | ||
| 70 | + "tr.row:hover td{background:var(--surface-hover)}\n" | ||
| 71 | + "tr.row:last-child td{border-bottom:0}\n" | ||
| 72 | + "tr.row.sel td{background:var(--sf2,var(--surface-2))}\n" | ||
| 73 | + ".mo{font-family:var(--mono);font-size:12.5px}\n" | ||
| 74 | + ".name{font-weight:600;max-width:340px;overflow:hidden;text-overflow:ellipsis}\n" | ||
| 75 | + ".desc{font-size:11.5px;color:var(--mu,var(--text-2));max-width:340px;\n" | ||
| 76 | + " overflow:hidden;text-overflow:ellipsis;margin-top:1px}\n" | ||
| 77 | + ".tag{font-size:10px;font-weight:700;padding:2px 8px;border-radius:6px;\n" | ||
| 78 | + " white-space:nowrap;letter-spacing:.03em}\n" | ||
| 79 | + ".t-run{background:rgba(48,209,88,.16);color:var(--green)}\n" | ||
| 80 | + ".t-fail{background:rgba(255,69,58,.16);color:var(--red)}\n" | ||
| 81 | + ".t-off{background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2));\n" | ||
| 82 | + " border:1px solid var(--ln,var(--line))}\n" | ||
| 83 | + ".t-warn{background:rgba(255,159,10,.16);color:var(--orange)}\n" | ||
| 84 | + ".dot{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:6px;\n" | ||
| 85 | + " vertical-align:1px}\n" | ||
| 86 | + ".d-run{background:var(--green)}.d-fail{background:var(--red)}\n" | ||
| 87 | + ".d-off{background:var(--gray)}.d-warn{background:var(--orange)}\n" | ||
| 88 | + ".empty{padding:26px 14px;text-align:center;color:var(--mu,var(--text-2));font-size:13px}\n" | ||
| 89 | + ".hide{display:none!important}\n" | ||
| 90 | + "\n" | ||
| 91 | + "/* detail drawer */\n" | ||
| 92 | + ".scrim{position:fixed;inset:0;background:rgba(0,0,0,.38);opacity:0;pointer-events:none;\n" | ||
| 93 | + " transition:opacity .18s var(--ease);z-index:40}\n" | ||
| 94 | + ".scrim.open{opacity:1;pointer-events:auto}\n" | ||
| 95 | + ".drawer{position:fixed;top:0;right:0;bottom:0;width:min(430px,100%);z-index:41;\n" | ||
| 96 | + " background:var(--bg-2,var(--bg-card));border-left:1px solid var(--ln,var(--line));\n" | ||
| 97 | + " box-shadow:var(--shadow-lg);transform:translateX(102%);\n" | ||
| 98 | + " transition:transform .22s var(--ease);display:flex;flex-direction:column;\n" | ||
| 99 | + " max-width:100%}\n" | ||
| 100 | + ".drawer.open{transform:none}\n" | ||
| 101 | + ".dh{display:flex;align-items:flex-start;gap:10px;padding:16px 16px 12px;\n" | ||
| 102 | + " border-bottom:1px solid var(--ln,var(--line))}\n" | ||
| 103 | + ".dh .t{flex:1 1 auto;min-width:0}\n" | ||
| 104 | + ".dh .n{font-size:15px;font-weight:680;word-break:break-all}\n" | ||
| 105 | + ".dh .s{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:3px;\n" | ||
| 106 | + " word-break:break-word}\n" | ||
| 107 | + ".dbody{flex:1 1 auto;overflow-y:auto;padding:14px 16px 24px}\n" | ||
| 108 | + ".kv{display:grid;grid-template-columns:110px minmax(0,1fr);gap:8px 12px;\n" | ||
| 109 | + " font-size:12.5px;margin-bottom:16px}\n" | ||
| 110 | + ".kv .k{color:var(--mu,var(--text-2))}\n" | ||
| 111 | + ".kv .v{font-family:var(--mono);word-break:break-all}\n" | ||
| 112 | + ".ctl{display:flex;gap:8px;flex-wrap:wrap;border-top:1px solid var(--ln,var(--line));\n" | ||
| 113 | + " padding-top:14px;margin-top:4px}\n" | ||
| 114 | + ".btn{background:var(--ac,var(--blue));color:#fff;border:0;border-radius:999px;\n" | ||
| 115 | + " padding:8px 16px;font-weight:650;font-size:12.5px;cursor:pointer;font-family:inherit}\n" | ||
| 116 | + ".btn:active{transform:scale(.98)}\n" | ||
| 117 | + ".btn.gh{background:transparent;color:var(--text);border:1px solid var(--ln,var(--line))}\n" | ||
| 118 | + ".btn.warn{background:var(--orange)}\n" | ||
| 119 | + ".btn.bad{background:var(--red)}\n" | ||
| 120 | + ".note{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:10px}\n" | ||
| 121 | + ".out{margin-top:12px;padding:10px 12px;border-radius:10px;font-size:12.5px;\n" | ||
| 122 | + " background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line));\n" | ||
| 123 | + " word-break:break-word}\n" | ||
| 124 | + ".out.err{color:var(--red);border-color:rgba(255,69,58,.4)}\n" | ||
| 125 | + ".out.ok{color:var(--green);border-color:rgba(48,209,88,.35)}\n" | ||
| 126 | + "\n" | ||
| 127 | + "@media(max-width:860px){\n" | ||
| 128 | + " .wrap{padding:14px 12px 32px}\n" | ||
| 129 | + " .name,.desc{max-width:200px}\n" | ||
| 130 | + " th.h-opt,td.h-opt{display:none}\n" | ||
| 131 | + "}\n" | ||
| 132 | + "@media(max-width:600px){\n" | ||
| 133 | + " .wrap{padding:12px 10px 28px}\n" | ||
| 134 | + " .title{font-size:17px}\n" | ||
| 135 | + " .chips{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}\n" | ||
| 136 | + " .chip .v{font-size:20px}\n" | ||
| 137 | + " .name,.desc{max-width:150px}\n" | ||
| 138 | + " th.h-since,td.h-since{display:none}\n" | ||
| 139 | + " .drawer{width:100%}\n" | ||
| 140 | + "}\n" | ||
| 141 | + "</style></head><body>\n" | ||
| 142 | + "<div class=\"wrap\">\n" | ||
| 143 | + " <div class=\"top\">\n" | ||
| 144 | + " <div>\n" | ||
| 145 | + " <div class=\"brand\">SCORPIOX BOT</div>\n" | ||
| 146 | + " <h1 class=\"title\">Services</h1>\n" | ||
| 147 | + " </div>\n" | ||
| 148 | + " <span class=\"sp\"></span>\n" | ||
| 149 | + " <span class=\"pill\" id=\"initPill\">init: —</span>\n" | ||
| 150 | + " <button class=\"icon-btn embed-hide\" id=\"btnRefresh\" type=\"button\" title=\"Reload\">\n" | ||
| 151 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M20 12a8 8 0 1 1-2.3-5.7\"/><path d=\"M20 4v5h-5\"/></svg>\n" | ||
| 152 | + " Refresh\n" | ||
| 153 | + " </button>\n" | ||
| 154 | + " <button class=\"icon-btn embed-hide\" id=\"btnTheme\" type=\"button\" title=\"Toggle appearance\">\n" | ||
| 155 | + " <svg viewBox=\"0 0 24 24\"><circle cx=\"12\" cy=\"12\" r=\"4.2\"/><path d=\"M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.4 1.4M17.6 17.6L19 19M19 5l-1.4 1.4M6.4 17.6L5 19\"/></svg>\n" | ||
| 156 | + " </button>\n" | ||
| 157 | + " </div>\n" | ||
| 158 | + "\n" | ||
| 159 | + " <div class=\"chips\">\n" | ||
| 160 | + " <button class=\"chip\" id=\"cAll\" type=\"button\"><div class=\"k\">All</div><div class=\"v\" id=\"vAll\">—</div></button>\n" | ||
| 161 | + " <button class=\"chip ok\" id=\"cRun\" type=\"button\"><div class=\"k\"><span class=\"dot d-run\"></span>Running</div><div class=\"v\" id=\"vRun\">—</div></button>\n" | ||
| 162 | + " <button class=\"chip bad\" id=\"cFail\" type=\"button\"><div class=\"k\"><span class=\"dot d-fail\"></span>Failed</div><div class=\"v\" id=\"vFail\">—</div></button>\n" | ||
| 163 | + " <button class=\"chip none\" id=\"cOff\" type=\"button\"><div class=\"k\"><span class=\"dot d-off\"></span>Inactive</div><div class=\"v\" id=\"vOff\">—</div></button>\n" | ||
| 164 | + " </div>\n" | ||
| 165 | + "\n" | ||
| 166 | + " <div class=\"bar\">\n" | ||
| 167 | + " <input class=\"search\" id=\"q\" type=\"search\" placeholder=\"Search name or description\" autocomplete=\"off\" spellcheck=\"false\">\n" | ||
| 168 | + " <select id=\"sort\" title=\"Sort\">\n" | ||
| 169 | + " <option value=\"failed\">Sort: failed first</option>\n" | ||
| 170 | + " <option value=\"name\">Sort: name</option>\n" | ||
| 171 | + " <option value=\"state\">Sort: state</option>\n" | ||
| 172 | + " </select>\n" | ||
| 173 | + " </div>\n" | ||
| 174 | + "\n" | ||
| 175 | + " <div class=\"panel\">\n" | ||
| 176 | + " <div class=\"tb\">\n" | ||
| 177 | + " <table>\n" | ||
| 178 | + " <thead><tr>\n" | ||
| 179 | + " <th>Service</th>\n" | ||
| 180 | + " <th>State</th>\n" | ||
| 181 | + " <th class=\"h-opt\">Enabled</th>\n" | ||
| 182 | + " <th class=\"h-opt\">PID</th>\n" | ||
| 183 | + " <th class=\"h-opt\">Memory</th>\n" | ||
| 184 | + " <th class=\"h-since\">Since</th>\n" | ||
| 185 | + " </tr></thead>\n" | ||
| 186 | + " <tbody id=\"rows\"></tbody>\n" | ||
| 187 | + " </table>\n" | ||
| 188 | + " </div>\n" | ||
| 189 | + " <div id=\"empty\" class=\"empty hide\">No services matched this filter.</div>\n" | ||
| 190 | + " </div>\n" | ||
| 191 | + "</div>\n" | ||
| 192 | + "\n" | ||
| 193 | + "<div class=\"scrim\" id=\"scrim\"></div>\n" | ||
| 194 | + "<aside class=\"drawer\" id=\"drawer\" aria-hidden=\"true\">\n" | ||
| 195 | + " <div class=\"dh\">\n" | ||
| 196 | + " <div class=\"t\"><div class=\"n\" id=\"dName\">—</div><div class=\"s\" id=\"dDesc\"></div></div>\n" | ||
| 197 | + " <button class=\"icon-btn\" id=\"dClose\" type=\"button\" title=\"Close\">\n" | ||
| 198 | + " <svg viewBox=\"0 0 24 24\"><path d=\"M6 6l12 12M18 6L6 18\"/></svg>\n" | ||
| 199 | + " </button>\n" | ||
| 200 | + " </div>\n" | ||
| 201 | + " <div class=\"dbody\">\n" | ||
| 202 | + " <div class=\"kv\">\n" | ||
| 203 | + " <div class=\"k\">State</div><div class=\"v\" id=\"dState\">—</div>\n" | ||
| 204 | + " <div class=\"k\">Sub-state</div><div class=\"v\" id=\"dSub\">—</div>\n" | ||
| 205 | + " <div class=\"k\">Enabled</div><div class=\"v\" id=\"dEnabled\">—</div>\n" | ||
| 206 | + " <div class=\"k\">PID</div><div class=\"v\" id=\"dPid\">—</div>\n" | ||
| 207 | + " <div class=\"k\">Memory</div><div class=\"v\" id=\"dMem\">—</div>\n" | ||
| 208 | + " <div class=\"k\">Since</div><div class=\"v\" id=\"dSince\">—</div>\n" | ||
| 209 | + " </div>\n" | ||
| 210 | + " <div class=\"ctl hide\" id=\"dCtl\">\n" | ||
| 211 | + " <button class=\"btn\" id=\"opStart\" type=\"button\">Start</button>\n" | ||
| 212 | + " <button class=\"btn warn\" id=\"opRestart\" type=\"button\">Restart</button>\n" | ||
| 213 | + " <button class=\"btn bad\" id=\"opStop\" type=\"button\">Stop</button>\n" | ||
| 214 | + " </div>\n" | ||
| 215 | + " <div class=\"note hide\" id=\"dNote\"></div>\n" | ||
| 216 | + " <div class=\"out hide\" id=\"dOut\"></div>\n" | ||
| 217 | + " </div>\n" | ||
| 218 | + "</aside>\n" | ||
| 219 | + "\n" | ||
| 220 | + "<script>\n" | ||
| 221 | + "(function(){\n" | ||
| 222 | + "\"use strict\";\n" | ||
| 223 | + "var q=new URLSearchParams(location.search);\n" | ||
| 224 | + "var node=q.get('node')||'';\n" | ||
| 225 | + "var sid=q.get('id')||'';\n" | ||
| 226 | + "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n" | ||
| 227 | + " localStorage.getItem('bot_active_pwd')||'';\n" | ||
| 228 | + "var HUB=q.get('plugin')||'';\n" | ||
| 229 | + "\n" | ||
| 230 | + "/* Two call routes. Through the hub -> call the hub proxy back. Opened directly\n" | ||
| 231 | + " * on the node -> the plugin itself is the route. Calling /plugins?plugin= on the\n" | ||
| 232 | + " * node returns the discovery list, not this plugin. */\n" | ||
| 233 | + "function api(action,extra,method){\n" | ||
| 234 | + " var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_services')+\n" | ||
| 235 | + " '?action='+encodeURIComponent(action)+(extra?('&'+extra):'')+\n" | ||
| 236 | + " (node?'&node='+encodeURIComponent(node):'')+\n" | ||
| 237 | + " (sid?'&id='+encodeURIComponent(sid):'')+\n" | ||
| 238 | + " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n" | ||
| 239 | + " return fetch(u,{method:method||'GET',headers:pwd?{'X-Bot-Password':pwd}:{}})\n" | ||
| 240 | + " .then(function(r){return r.json();});\n" | ||
| 241 | + "}\n" | ||
| 242 | + "function $(id){return document.getElementById(id);}\n" | ||
| 243 | + "function esc(v){return String(v==null?'':v).replace(/[&<>\"']/g,function(c){\n" | ||
| 244 | + " return({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''})[c];});}\n" | ||
| 245 | + "function bytes(n){\n" | ||
| 246 | + " if(n==null||n===0) return '—';\n" | ||
| 247 | + " var u=['B','KiB','MiB','GiB','TiB'],i=0,v=n;\n" | ||
| 248 | + " while(v>=1024&&i<u.length-1){v/=1024;i++;}\n" | ||
| 249 | + " return (v>=100?Math.round(v):(Math.round(v*10)/10))+' '+u[i];\n" | ||
| 250 | + "}\n" | ||
| 251 | + "var DATA=[],CTL=false,FILTER='',SORT='failed',SEL=null;\n" | ||
| 252 | + "\n" | ||
| 253 | + "function stateCls(s){\n" | ||
| 254 | + " if(s.failed||s.active==='failed') return 'fail';\n" | ||
| 255 | + " if(s.active==='running'||s.active==='active'||s.sub==='running') return 'run';\n" | ||
| 256 | + " if(s.active==='paused'||s.active==='starting'||s.active==='stopping') return 'warn';\n" | ||
| 257 | + " return 'off';\n" | ||
| 258 | + "}\n" | ||
| 259 | + "function stateLabel(s){\n" | ||
| 260 | + " var c=stateCls(s);\n" | ||
| 261 | + " if(c==='run') return 'running';\n" | ||
| 262 | + " if(c==='fail') return 'failed';\n" | ||
| 263 | + " if(c==='warn') return s.active||'pending';\n" | ||
| 264 | + " return s.active==='inactive'?'inactive':(s.active||'inactive');\n" | ||
| 265 | + "}\n" | ||
| 266 | + "/* unused helper removed: stateLabel(s) already returns the visible label */\n" | ||
| 267 | + "\n" | ||
| 268 | + "function visible(){\n" | ||
| 269 | + " var f=FILTER, needle=($('q').value||'').toLowerCase();\n" | ||
| 270 | + " var out=DATA.filter(function(s){\n" | ||
| 271 | + " if(f==='running'&&stateCls(s)!=='run') return false;\n" | ||
| 272 | + " if(f==='failed'&&stateCls(s)!=='fail') return false;\n" | ||
| 273 | + " if(f==='inactive'&&stateCls(s)!=='off') return false;\n" | ||
| 274 | + " if(needle){\n" | ||
| 275 | + " var hay=(s.name+' '+(s.description||'')).toLowerCase();\n" | ||
| 276 | + " if(hay.indexOf(needle)<0) return false;\n" | ||
| 277 | + " }\n" | ||
| 278 | + " return true;\n" | ||
| 279 | + " });\n" | ||
| 280 | + " if(SORT==='name') out.sort(function(a,b){return a.name<b.name?-1:a.name>b.name?1:0;});\n" | ||
| 281 | + " else if(SORT==='state') out.sort(function(a,b){\n" | ||
| 282 | + " var x=stateCls(a),y=stateCls(b);\n" | ||
| 283 | + " if(x!==y) return x<y?-1:1;\n" | ||
| 284 | + " return a.name<b.name?-1:1;});\n" | ||
| 285 | + " return out;\n" | ||
| 286 | + "}\n" | ||
| 287 | + "\n" | ||
| 288 | + "function render(){\n" | ||
| 289 | + " var rows=visible();\n" | ||
| 290 | + " var h='';\n" | ||
| 291 | + " for(var i=0;i<rows.length;i++){\n" | ||
| 292 | + " var s=rows[i],c=stateCls(s);\n" | ||
| 293 | + " h+='<tr class=\"row'+(SEL&&SEL===s.name?' sel':'')+'\" data-n=\"'+esc(s.name)+'\">'+\n" | ||
| 294 | + " '<td><div class=\"name\" title=\"'+esc(s.name)+'\">'+esc(s.name)+'</div>'+\n" | ||
| 295 | + " (s.description?'<div class=\"desc\" title=\"'+esc(s.description)+'\">'+esc(s.description)+'</div>':'')+\n" | ||
| 296 | + " '</td>'+\n" | ||
| 297 | + " '<td><span class=\"tag t-'+c+'\"><span class=\"dot d-'+c+'\"></span>'+\n" | ||
| 298 | + " esc(stateLabel(s))+'</span></td>'+\n" | ||
| 299 | + " '<td class=\"mo h-opt\">'+esc(s.enabled||'-')+'</td>'+\n" | ||
| 300 | + " '<td class=\"mo h-opt\">'+(s.pid>0?esc(s.pid):'—')+'</td>'+\n" | ||
| 301 | + " '<td class=\"mo h-opt\">'+bytes(s.memory_bytes)+'</td>'+\n" | ||
| 302 | + " '<td class=\"mo h-since\">'+esc(s.since||'—')+'</td></tr>';\n" | ||
| 303 | + " }\n" | ||
| 304 | + " $('rows').innerHTML=h;\n" | ||
| 305 | + " $('empty').className=rows.length?'empty hide':'empty';\n" | ||
| 306 | + " var trs=$('rows').querySelectorAll('tr.row');\n" | ||
| 307 | + " for(var k=0;k<trs.length;k++){\n" | ||
| 308 | + " trs[k].onclick=function(){open(this.getAttribute('data-n'));};\n" | ||
| 309 | + " }\n" | ||
| 310 | + "}\n" | ||
| 311 | + "\n" | ||
| 312 | + "function load(){\n" | ||
| 313 | + " return api('list','filter=all').then(function(d){\n" | ||
| 314 | + " if(!d||!d.ok){ throw new Error((d&&d.error)||'load failed'); }\n" | ||
| 315 | + " DATA=d.services||[];\n" | ||
| 316 | + " CTL=!!d.control_enabled;\n" | ||
| 317 | + " var sum=d.summary||{};\n" | ||
| 318 | + " $('vAll').textContent=DATA.length;\n" | ||
| 319 | + " $('vRun').textContent=sum.running||0;\n" | ||
| 320 | + " $('vFail').textContent=sum.failed||0;\n" | ||
| 321 | + " $('vOff').textContent=sum.inactive||0;\n" | ||
| 322 | + " $('initPill').textContent='init: '+(d.init_system||'unknown')+\n" | ||
| 323 | + " (CTL?' · control on':' · read-only');\n" | ||
| 324 | + " render();\n" | ||
| 325 | + " });\n" | ||
| 326 | + "}\n" | ||
| 327 | + "\n" | ||
| 328 | + "function open(name){\n" | ||
| 329 | + " var s=null;\n" | ||
| 330 | + " for(var i=0;i<DATA.length;i++) if(DATA[i].name===name){s=DATA[i];break;}\n" | ||
| 331 | + " if(!s) return;\n" | ||
| 332 | + " SEL=name;\n" | ||
| 333 | + " $('dName').textContent=s.name;\n" | ||
| 334 | + " $('dDesc').textContent=s.description||'';\n" | ||
| 335 | + " $('dState').textContent=stateLabel(s);\n" | ||
| 336 | + " $('dSub').textContent=s.sub||'—';\n" | ||
| 337 | + " $('dEnabled').textContent=s.enabled||'-';\n" | ||
| 338 | + " $('dPid').textContent=s.pid>0?s.pid:'—';\n" | ||
| 339 | + " $('dMem').textContent=bytes(s.memory_bytes);\n" | ||
| 340 | + " $('dSince').textContent=s.since||'—';\n" | ||
| 341 | + " $('dOut').className='out hide';\n" | ||
| 342 | + " $('dOut').textContent='';\n" | ||
| 343 | + " if(CTL){\n" | ||
| 344 | + " $('dCtl').className='ctl';\n" | ||
| 345 | + " $('dNote').className='note';\n" | ||
| 346 | + " $('dNote').textContent='Control is enabled on this node (SERVICES_ALLOW_CONTROL=1). Every action is sent as a separate argv element, never through a shell.';\n" | ||
| 347 | + " }else{\n" | ||
| 348 | + " $('dCtl').className='ctl hide';\n" | ||
| 349 | + " $('dNote').className='note';\n" | ||
| 350 | + " $('dNote').textContent='Read-only: set SERVICES_ALLOW_CONTROL=1 in this node\\'s plugin environment to enable start, stop and restart.';\n" | ||
| 351 | + " }\n" | ||
| 352 | + " $('drawer').className='drawer open';\n" | ||
| 353 | + " $('drawer').setAttribute('aria-hidden','false');\n" | ||
| 354 | + " $('scrim').className='scrim open';\n" | ||
| 355 | + " render();\n" | ||
| 356 | + "}\n" | ||
| 357 | + "function close(){\n" | ||
| 358 | + " SEL=null;\n" | ||
| 359 | + " $('drawer').className='drawer';\n" | ||
| 360 | + " $('drawer').setAttribute('aria-hidden','true');\n" | ||
| 361 | + " $('scrim').className='scrim';\n" | ||
| 362 | + " render();\n" | ||
| 363 | + "}\n" | ||
| 364 | + "\n" | ||
| 365 | + "function control(op){\n" | ||
| 366 | + " if(!SEL) return;\n" | ||
| 367 | + " var label={start:'start',stop:'stop',restart:'restart'}[op];\n" | ||
| 368 | + " if(!window.confirm(label+' '+SEL+'?\\n\\nThis runs '+label+' on the node\\'s service manager.')) return;\n" | ||
| 369 | + " var o=$('dOut');\n" | ||
| 370 | + " o.className='out';\n" | ||
| 371 | + " o.textContent='Sending '+label+' '+SEL+' ...';\n" | ||
| 372 | + " api('control','unit='+encodeURIComponent(SEL)+'&op='+encodeURIComponent(op),'POST')\n" | ||
| 373 | + " .then(function(d){\n" | ||
| 374 | + " if(d&&d.ok){\n" | ||
| 375 | + " o.className='out ok';\n" | ||
| 376 | + " o.textContent=label+' requested for '+SEL+'.';\n" | ||
| 377 | + " setTimeout(function(){load().then(function(){\n" | ||
| 378 | + " for(var i=0;i<DATA.length;i++) if(DATA[i].name===SEL){ show(DATA[i]); break; }\n" | ||
| 379 | + " });},700);\n" | ||
| 380 | + " }else{\n" | ||
| 381 | + " o.className='out err';\n" | ||
| 382 | + " o.textContent=(d&&(d.error||('HTTP error')))+'';\n" | ||
| 383 | + " }\n" | ||
| 384 | + " }).catch(function(e){\n" | ||
| 385 | + " o.className='out err';\n" | ||
| 386 | + " o.textContent='Request failed: '+e.message;\n" | ||
| 387 | + " });\n" | ||
| 388 | + "}\n" | ||
| 389 | + "function show(s){\n" | ||
| 390 | + " $('dState').textContent=stateLabel(s);\n" | ||
| 391 | + " $('dSub').textContent=s.sub||'—';\n" | ||
| 392 | + " $('dEnabled').textContent=s.enabled||'-';\n" | ||
| 393 | + " $('dPid').textContent=s.pid>0?s.pid:'—';\n" | ||
| 394 | + " $('dMem').textContent=bytes(s.memory_bytes);\n" | ||
| 395 | + " $('dSince').textContent=s.since||'—';\n" | ||
| 396 | + " render();\n" | ||
| 397 | + "}\n" | ||
| 398 | + "\n" | ||
| 399 | + "function setFilter(f){\n" | ||
| 400 | + " FILTER=f;\n" | ||
| 401 | + " var ids={all:'cAll',running:'cRun',failed:'cFail',inactive:'cOff'};\n" | ||
| 402 | + " for(var k in ids) $(ids[k]).className='chip'+(k===f?' sel':'')+\n" | ||
| 403 | + " (k==='running'?' ok':k==='failed'?' bad':k==='inactive'?' none':'');\n" | ||
| 404 | + " render();\n" | ||
| 405 | + "}\n" | ||
| 406 | + "\n" | ||
| 407 | + "$('cAll').onclick=function(){setFilter('');};\n" | ||
| 408 | + "$('cRun').onclick=function(){setFilter('running');};\n" | ||
| 409 | + "$('cFail').onclick=function(){setFilter('failed');};\n" | ||
| 410 | + "$('cOff').onclick=function(){setFilter('inactive');};\n" | ||
| 411 | + "$('q').oninput=render;\n" | ||
| 412 | + "$('sort').onchange=function(){SORT=this.value;render();};\n" | ||
| 413 | + "$('btnRefresh').onclick=function(){load();};\n" | ||
| 414 | + "$('dClose').onclick=close;\n" | ||
| 415 | + "$('scrim').onclick=close;\n" | ||
| 416 | + "$('opStart').onclick=function(){control('start');};\n" | ||
| 417 | + "$('opStop').onclick=function(){control('stop');};\n" | ||
| 418 | + "$('opRestart').onclick=function(){control('restart');};\n" | ||
| 419 | + "if(window.sxApplyTheme){\n" | ||
| 420 | + " $('btnTheme').onclick=function(){\n" | ||
| 421 | + " window.sxApplyTheme(window.sxTheme&&window.sxTheme()==='dark'?'light':'dark');\n" | ||
| 422 | + " };\n" | ||
| 423 | + "}else{\n" | ||
| 424 | + " $('btnTheme').className='icon-btn embed-hide hide';\n" | ||
| 425 | + "}\n" | ||
| 426 | + "document.addEventListener('keydown',function(e){\n" | ||
| 427 | + " if(e.key==='Escape'&&SEL) close();\n" | ||
| 428 | + "});\n" | ||
| 429 | + "setFilter('');\n" | ||
| 430 | + "load().catch(function(e){\n" | ||
| 431 | + " $('empty').className='empty';\n" | ||
| 432 | + " $('empty').textContent='Could not load services: '+e.message;\n" | ||
| 433 | + "});\n" | ||
| 434 | + "})();\n" | ||
| 435 | + "</script>\n" | ||
| 436 | + "\002</body></html>\n" | ||
| 437 | + ; | ||
| 438 | + | ||
| 439 | +#endif /* SX_SERVICES_UI_HTML_H */ |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..8e0079d | index 0000000..8e0079d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/e2e.py | +++ b/tests/e2e.py | ||
| @@ -0,0 +1,204 @@ | @@ -0,0 +1,204 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tests/e2e.py - viewport checks for the plugin_services board. | ||
| 3 | + | ||
| 4 | +Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, points it | ||
| 5 | +at the systemd fixtures so the table is always populated, and opens it with | ||
| 6 | +Playwright at 1440 / 1024 / 390 CSS pixels in both themes. It asserts there is | ||
| 7 | +no horizontal overflow, no console error, that the summary chips and the table | ||
| 8 | +rendered, and that a row opens the detail drawer. Screenshots land in docs/ for | ||
| 9 | +the README. Skips cleanly (exit 0) when Playwright is not installed, so the | ||
| 10 | +offline suite stays dependency-free. | ||
| 11 | + | ||
| 12 | + python3 tests/e2e.py # run if Playwright is available | ||
| 13 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | ||
| 14 | +""" | ||
| 15 | + | ||
| 16 | +import argparse | ||
| 17 | +import http.server | ||
| 18 | +import os | ||
| 19 | +import socketserver | ||
| 20 | +import subprocess | ||
| 21 | +import sys | ||
| 22 | +import tempfile | ||
| 23 | +import threading | ||
| 24 | +from urllib.parse import urlparse | ||
| 25 | + | ||
| 26 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 27 | +BIN = os.path.join(ROOT, "plugin_services") | ||
| 28 | +DOCS = os.path.join(ROOT, "docs") | ||
| 29 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | ||
| 30 | +THEMES = ["dark", "light"] | ||
| 31 | + | ||
| 32 | +UNITS = """[{"unit":"nginx.service","load":"loaded","active":"active","sub":"running","description":"A high performance web server and a reverse proxy server"}, | ||
| 33 | + {"unit":"ssh.service","load":"loaded","active":"active","sub":"running","description":"OpenBSD Secure Shell server"}, | ||
| 34 | + {"unit":"cron.service","load":"loaded","active":"inactive","sub":"dead","description":"Regular background program processing daemon"}, | ||
| 35 | + {"unit":"docker.service","load":"loaded","active":"active","sub":"running","description":"Docker Application Container Engine"}, | ||
| 36 | + {"unit":"broken.service","load":"loaded","active":"failed","sub":"failed","description":"A service that failed on purpose"}, | ||
| 37 | + {"unit":"postgresql.service","load":"loaded","active":"inactive","sub":"dead","description":"PostgreSQL RDBMS"}] | ||
| 38 | +""" | ||
| 39 | + | ||
| 40 | +SHOW = """Id=nginx.service | ||
| 41 | +MainPID=4242 | ||
| 42 | +MemoryCurrent=10485760 | ||
| 43 | +UnitFileState=enabled | ||
| 44 | +ActiveEnterTimestamp=Wed 2026-11-12 04:00:00 UTC | ||
| 45 | + | ||
| 46 | +Id=ssh.service | ||
| 47 | +MainPID=912 | ||
| 48 | +MemoryCurrent=7340032 | ||
| 49 | +UnitFileState=static | ||
| 50 | +ActiveEnterTimestamp=Wed 2026-11-12 03:00:00 UTC | ||
| 51 | + | ||
| 52 | +Id=docker.service | ||
| 53 | +MainPID=1180 | ||
| 54 | +MemoryCurrent=205520896 | ||
| 55 | +UnitFileState=enabled | ||
| 56 | +ActiveEnterTimestamp=Wed 2026-11-12 02:12:00 UTC | ||
| 57 | + | ||
| 58 | +""" | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +class Handler(http.server.BaseHTTPRequestHandler): | ||
| 62 | + fixture_dir = "" | ||
| 63 | + | ||
| 64 | + def do_GET(self): # noqa: N802 | ||
| 65 | + u = urlparse(self.path) | ||
| 66 | + env = dict(os.environ) | ||
| 67 | + env["QUERY_STRING"] = u.query | ||
| 68 | + env["REQUEST_METHOD"] = "GET" | ||
| 69 | + env.pop("BOT_PASSWORD", None) | ||
| 70 | + env["SERVICES_MOCK_SYSTEMCTL"] = os.path.join(self.fixture_dir, "units.json") | ||
| 71 | + env["SERVICES_MOCK_SYSTEMCTL_SHOW"] = os.path.join(self.fixture_dir, "show.txt") | ||
| 72 | + out = subprocess.run([BIN], capture_output=True, env=env, timeout=30).stdout | ||
| 73 | + sep = out.find(b"\r\n\r\n") | ||
| 74 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | ||
| 75 | + body = out[sep + 4:] if sep >= 0 else out | ||
| 76 | + ctype = "text/html; charset=utf-8" | ||
| 77 | + for line in headers.splitlines(): | ||
| 78 | + if line.lower().startswith("content-type:"): | ||
| 79 | + ctype = line.split(":", 1)[1].strip() | ||
| 80 | + self.send_response(200) | ||
| 81 | + self.send_header("Content-Type", ctype) | ||
| 82 | + self.send_header("Cache-Control", "no-store") | ||
| 83 | + self.send_header("Content-Length", str(len(body))) | ||
| 84 | + self.end_headers() | ||
| 85 | + self.wfile.write(body) | ||
| 86 | + | ||
| 87 | + def log_message(self, *_a): | ||
| 88 | + pass | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +def main(): | ||
| 92 | + ap = argparse.ArgumentParser() | ||
| 93 | + ap.add_argument("--strict", action="store_true") | ||
| 94 | + args = ap.parse_args() | ||
| 95 | + | ||
| 96 | + if not os.path.exists(BIN): | ||
| 97 | + print("plugin_services is not built; run make first", file=sys.stderr) | ||
| 98 | + return 1 | ||
| 99 | + | ||
| 100 | + try: | ||
| 101 | + from playwright.sync_api import sync_playwright | ||
| 102 | + except Exception: | ||
| 103 | + msg = "playwright not installed - skipping viewport e2e" | ||
| 104 | + if args.strict: | ||
| 105 | + print(msg, file=sys.stderr) | ||
| 106 | + return 2 | ||
| 107 | + print(msg) | ||
| 108 | + return 0 | ||
| 109 | + | ||
| 110 | + fixture_dir = tempfile.mkdtemp(prefix="services-e2e-") | ||
| 111 | + with open(os.path.join(fixture_dir, "units.json"), "w", encoding="utf-8") as f: | ||
| 112 | + f.write(UNITS) | ||
| 113 | + with open(os.path.join(fixture_dir, "show.txt"), "w", encoding="utf-8") as f: | ||
| 114 | + f.write(SHOW) | ||
| 115 | + Handler.fixture_dir = fixture_dir | ||
| 116 | + | ||
| 117 | + os.makedirs(DOCS, exist_ok=True) | ||
| 118 | + | ||
| 119 | + with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv: | ||
| 120 | + port = srv.server_address[1] | ||
| 121 | + threading.Thread(target=srv.serve_forever, daemon=True).start() | ||
| 122 | + base = "http://127.0.0.1:%d/plugin_services" % port | ||
| 123 | + | ||
| 124 | + failures = [] | ||
| 125 | + with sync_playwright() as p: | ||
| 126 | + browser = p.chromium.launch() | ||
| 127 | + for (w, h) in VIEWPORTS: | ||
| 128 | + for theme in THEMES: | ||
| 129 | + url = "%s?theme=%s" % (base, theme) | ||
| 130 | + page = browser.new_page(viewport={"width": w, "height": h}) | ||
| 131 | + errors = [] | ||
| 132 | + page.on("console", lambda m: errors.append(m.text) | ||
| 133 | + if m.type == "error" else None) | ||
| 134 | + page.on("pageerror", lambda e: errors.append(str(e))) | ||
| 135 | + page.goto(url, wait_until="load") | ||
| 136 | + page.wait_for_timeout(1200) | ||
| 137 | + | ||
| 138 | + sw = page.evaluate("document.documentElement.scrollWidth") | ||
| 139 | + iw = page.evaluate("window.innerWidth") | ||
| 140 | + if sw > iw + 1: | ||
| 141 | + failures.append("%dx%d %s horizontal overflow %d > %d" | ||
| 142 | + % (w, h, theme, sw, iw)) | ||
| 143 | + | ||
| 144 | + applied = page.evaluate( | ||
| 145 | + "document.documentElement.getAttribute('data-theme')") | ||
| 146 | + if applied != theme: | ||
| 147 | + failures.append("%dx%d %s ?theme= did not apply (%r)" | ||
| 148 | + % (w, h, theme, applied)) | ||
| 149 | + | ||
| 150 | + total = page.evaluate( | ||
| 151 | + "document.getElementById('vAll').textContent") | ||
| 152 | + if not total.strip().isdigit(): | ||
| 153 | + failures.append("%dx%d %s All chip did not render (%r)" | ||
| 154 | + % (w, h, theme, total)) | ||
| 155 | + | ||
| 156 | + rows = page.evaluate( | ||
| 157 | + "document.querySelectorAll('#rows tr.row').length") | ||
| 158 | + if rows < 1: | ||
| 159 | + failures.append("%dx%d %s service table is empty" | ||
| 160 | + % (w, h, theme)) | ||
| 161 | + | ||
| 162 | + img = page.query_selector("#rows") and page.query_selector("svg") | ||
| 163 | + if img is None: | ||
| 164 | + failures.append("%dx%d %s no inline SVG icon rendered" | ||
| 165 | + % (w, h, theme)) | ||
| 166 | + | ||
| 167 | + if theme == "dark": | ||
| 168 | + page.click("#rows tr.row") | ||
| 169 | + page.wait_for_timeout(350) | ||
| 170 | + opened = page.evaluate( | ||
| 171 | + "document.getElementById('drawer').classList.contains('open')") | ||
| 172 | + if not opened: | ||
| 173 | + failures.append("%dx%d drawer did not open" % (w, h)) | ||
| 174 | + name = page.evaluate( | ||
| 175 | + "document.getElementById('dName').textContent") | ||
| 176 | + if not name or name == "—": | ||
| 177 | + failures.append("%dx%d drawer has no unit name" % (w, h)) | ||
| 178 | + page.screenshot(path=os.path.join( | ||
| 179 | + DOCS, "ui-%d-%s.png" % (w, theme)), full_page=False) | ||
| 180 | + page.click("#dClose") | ||
| 181 | + else: | ||
| 182 | + page.screenshot(path=os.path.join( | ||
| 183 | + DOCS, "ui-%d-%s.png" % (w, theme)), full_page=False) | ||
| 184 | + | ||
| 185 | + if errors: | ||
| 186 | + failures.append("%dx%d %s console errors: %s" | ||
| 187 | + % (w, h, theme, errors[:3])) | ||
| 188 | + | ||
| 189 | + page.close() | ||
| 190 | + browser.close() | ||
| 191 | + | ||
| 192 | + if failures: | ||
| 193 | + print("FAIL") | ||
| 194 | + for f in failures: | ||
| 195 | + print(" " + f) | ||
| 196 | + return 1 | ||
| 197 | + | ||
| 198 | + print("ok - %d viewports x %d themes clean (no overflow, no console error, " | ||
| 199 | + "chips + table + drawer rendered)" % (len(VIEWPORTS), len(THEMES))) | ||
| 200 | + return 0 | ||
| 201 | + | ||
| 202 | + | ||
| 203 | +if __name__ == "__main__": | ||
| 204 | + sys.exit(main()) |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..98de868 | index 0000000..98de868 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,475 @@ | @@ -0,0 +1,475 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_services across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Everything runs against ./plugin_services (native build). The service tables | ||
| 5 | +# come from fixtures, so the suite tests the parsers for all three init systems | ||
| 6 | +# (systemd JSON, legacy systemd text, launchctl) without needing a live systemd, | ||
| 7 | +# launchd or Windows SCM. Optional cross-target artifacts (musl, aarch64, PE) | ||
| 8 | +# are checked when they exist. The last section audits the whole git history for | ||
| 9 | +# secrets and internal addresses. | ||
| 10 | +# | ||
| 11 | +# Exit code 0 = everything passed. | ||
| 12 | + | ||
| 13 | +set -u | ||
| 14 | + | ||
| 15 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 16 | +cd "$ROOT" || exit 1 | ||
| 17 | + | ||
| 18 | +BIN=./plugin_services | ||
| 19 | +PASS=0 | ||
| 20 | +FAIL=0 | ||
| 21 | + | ||
| 22 | +if [ -t 1 ]; then | ||
| 23 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 24 | +else | ||
| 25 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 26 | +fi | ||
| 27 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 28 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 29 | + | ||
| 30 | +check() { # check <desc> <expected-substring> <actual> | ||
| 31 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 32 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | ||
| 33 | + fi | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 37 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 38 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 39 | + fi | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 43 | + | ||
| 44 | +body() { # strip CGI headers if present, drop CRs, keep the payload | ||
| 45 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | ||
| 46 | + BEGIN { inhdr = 0 } | ||
| 47 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|Content-Security-Policy):/) { inhdr = 1; next } | ||
| 48 | + inhdr && $0 == "" { inhdr = 0; next } | ||
| 49 | + inhdr { next } | ||
| 50 | + { print } | ||
| 51 | + ' | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +hdr() { printf '%s\n' "$1" | tr -d '\r' | sed -n '1p'; } | ||
| 55 | + | ||
| 56 | +json_ok() { # json_ok <desc> <json> [python-expression] | ||
| 57 | + expr=${3:-True} | ||
| 58 | + if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then | ||
| 59 | + pass "$1" | ||
| 60 | + else | ||
| 61 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | ||
| 62 | + fi | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +run() { # run <query-string> [extra env assignments...] -> raw output | ||
| 66 | + qs="$1"; shift | ||
| 67 | + env QUERY_STRING="$qs" "$@" $BIN 2>&1 | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +api() { body "$(run "$1")"; } | ||
| 71 | + | ||
| 72 | +# ---------------------------------------------------------------- setup | ||
| 73 | +section "build" | ||
| 74 | +if [ ! -x "$BIN" ]; then | ||
| 75 | + echo " building native binary..." | ||
| 76 | + cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src \ | ||
| 77 | + -o "$BIN" src/plugin_services.c || { echo " build failed"; exit 1; } | ||
| 78 | +fi | ||
| 79 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | ||
| 80 | + | ||
| 81 | +WORK=$(mktemp -d 2>/dev/null || echo /tmp/ps_$$) | ||
| 82 | +mkdir -p "$WORK" | ||
| 83 | + | ||
| 84 | +# ---------------------------------------------------------------- meta | ||
| 85 | +section "mode 1 - discovery metadata" | ||
| 86 | +M=$(body "$($BIN --meta)") | ||
| 87 | +json_ok "--meta is valid JSON" "$M" "d['name']=='services'" | ||
| 88 | +check "--meta name is one word" '"name":"services"' "$M" | ||
| 89 | +check "--meta desc" '"desc":"System services"' "$M" | ||
| 90 | +json_ok "--meta desc respects the 15-char rule" "$M" "len(d['desc'])<=15" | ||
| 91 | +json_ok "--meta has exactly two keys" "$M" "len(d)==2" | ||
| 92 | +M2=$(body "$(SX_PLUGIN_META=1 $BIN)") | ||
| 93 | +check "SX_PLUGIN_META env var works" '"name":"services"' "$M2" | ||
| 94 | +check_not "--meta emits no HTML" '<html' "$M" | ||
| 95 | +check_not "--meta carries no version noise" 'version' "$M" | ||
| 96 | +check "--version prints the id and version" 'plugin_services 1.0.0' "$($BIN --version)" | ||
| 97 | + | ||
| 98 | +# ---------------------------------------------------------------- auth | ||
| 99 | +section "mode 2 - node authentication" | ||
| 100 | +A=$(run 'action=list' BOT_PASSWORD=testpw) | ||
| 101 | +check "unauthenticated list is 401" '401 Unauthorized' "$(hdr "$A")" | ||
| 102 | +check "unauthenticated list returns the JSON error" '"error":"invalid node password"' "$A" | ||
| 103 | +A2=$(run '' BOT_PASSWORD=testpw) | ||
| 104 | +check "unauthenticated HTML is 401 too" '401 Unauthorized' "$(hdr "$A2")" | ||
| 105 | +check_not "the 401 body is not the page" '<!DOCTYPE' "$A2" | ||
| 106 | +A3=$(run 'action=list&pwd=testpw' BOT_PASSWORD=testpw) | ||
| 107 | +json_ok "?pwd= authenticates" "$(body "$A3")" "d['ok'] is True" | ||
| 108 | +A4=$(run 'action=list' BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw) | ||
| 109 | +json_ok "X-Bot-Password authenticates" "$(body "$A4")" "d['ok'] is True" | ||
| 110 | +A5=$(run 'action=list' BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw') | ||
| 111 | +json_ok "Authorization: Bearer authenticates" "$(body "$A5")" "d['ok'] is True" | ||
| 112 | +A6=$(run 'action=list' BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer wrong') | ||
| 113 | +check "a wrong bearer token is rejected" '401 Unauthorized' "$(hdr "$A6")" | ||
| 114 | +A7=$(run 'action=list') | ||
| 115 | +json_ok "auth is a no-op when BOT_PASSWORD is unset" "$(body "$A7")" "d['ok'] is True" | ||
| 116 | + | ||
| 117 | +# ---------------------------------------------------------------- systemd json | ||
| 118 | +section "mode 2a - systemd JSON parser" | ||
| 119 | + | ||
| 120 | +cat > "$WORK/units.json" <<'JSON' | ||
| 121 | +[{"unit":"nginx.service","load":"loaded","active":"active","sub":"running","description":"A high performance web server and a reverse proxy server"}, | ||
| 122 | + {"unit":"ssh.service","load":"loaded","active":"active","sub":"running","description":"OpenBSD Secure Shell server"}, | ||
| 123 | + {"unit":"cron.service","load":"loaded","active":"inactive","sub":"dead","description":"Regular background program processing daemon"}, | ||
| 124 | + {"unit":"broken.service","load":"loaded","active":"failed","sub":"failed","description":"A service that failed on purpose"}, | ||
| 125 | + {"unit":"ghost.service","load":"not-found","active":"inactive","sub":"dead","description":"Does not exist"}] | ||
| 126 | +JSON | ||
| 127 | + | ||
| 128 | +cat > "$WORK/show.txt" <<'SHOW' | ||
| 129 | +Id=nginx.service | ||
| 130 | +Description=A high performance web server and a reverse proxy server | ||
| 131 | +ActiveState=active | ||
| 132 | +SubState=running | ||
| 133 | +MainPID=4242 | ||
| 134 | +MemoryCurrent=10485760 | ||
| 135 | +UnitFileState=enabled | ||
| 136 | +ActiveEnterTimestamp=Wed 2026-11-12 04:00:00 UTC | ||
| 137 | + | ||
| 138 | +Id=ssh.service | ||
| 139 | +Description=OpenBSD Secure Shell server | ||
| 140 | +ActiveState=active | ||
| 141 | +SubState=running | ||
| 142 | +MainPID=912 | ||
| 143 | +MemoryCurrent=18446744073709551615 | ||
| 144 | +UnitFileState=static | ||
| 145 | +ActiveEnterTimestamp=Wed 2026-11-12 03:00:00 UTC | ||
| 146 | + | ||
| 147 | +Id=cron.service | ||
| 148 | +Description=Regular background program processing daemon | ||
| 149 | +ActiveState=inactive | ||
| 150 | +SubState=dead | ||
| 151 | +MainPID=0 | ||
| 152 | +MemoryCurrent=[not set] | ||
| 153 | +UnitFileState=enabled | ||
| 154 | +ActiveEnterTimestamp=n/a | ||
| 155 | + | ||
| 156 | +SHOW | ||
| 157 | + | ||
| 158 | +LJ=$(body "$(run 'action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt")") | ||
| 159 | +json_ok "systemd list is valid JSON" "$LJ" "d['ok'] is True" | ||
| 160 | +json_ok "systemd list reports init_system=systemd" "$LJ" "d['init_system']=='systemd'" | ||
| 161 | +json_ok "systemd list drops not-found units" "$LJ" "all(s['name']!='ghost.service' for s in d['services'])" | ||
| 162 | +json_ok "systemd list counts 4 real units" "$LJ" "d['count']==4" | ||
| 163 | +json_ok "summary counts running" "$LJ" "d['summary']['running']==2" | ||
| 164 | +json_ok "summary counts failed" "$LJ" "d['summary']['failed']==1" | ||
| 165 | +json_ok "summary counts inactive" "$LJ" "d['summary']['inactive']==1" | ||
| 166 | +json_ok "failed services sort first" "$LJ" "d['services'][0]['name']=='broken.service'" | ||
| 167 | +json_ok "the failed row is flagged failed:true" "$LJ" "d['services'][0]['failed'] is True" | ||
| 168 | +json_ok "running services follow the failed one" "$LJ" "d['services'][1]['name']=='nginx.service'" | ||
| 169 | +json_ok "pid comes from systemctl show" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['pid']==4242" | ||
| 170 | +json_ok "memory comes from systemctl show" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['memory_bytes']==10485760" | ||
| 171 | +json_ok "UnitFileState becomes the enabled flag" "$LJ" "[s for s in d['services'] if s['name']=='nginx.service'][0]['enabled']=='enabled'" | ||
| 172 | +json_ok "ActiveEnterTimestamp becomes since" "$LJ" "'2026-11-12' in [s for s in d['services'] if s['name']=='nginx.service'][0]['since']" | ||
| 173 | +json_ok "the sentinel memory value is reported as null" "$LJ" "[s for s in d['services'] if s['name']=='ssh.service'][0]['memory_bytes'] is None" | ||
| 174 | +json_ok "descriptions survive the JSON parser" "$LJ" "'reverse proxy' in [s for s in d['services'] if s['name']=='nginx.service'][0]['description']" | ||
| 175 | +json_ok "control_enabled is false by default" "$LJ" "d['control_enabled'] is False" | ||
| 176 | + | ||
| 177 | +# ---------------------------------------------------------------- filters | ||
| 178 | +LF=$(body "$(run 'action=list&filter=failed' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 179 | +json_ok "filter=failed returns only failed rows" "$LF" "d['count']==1 and d['services'][0]['name']=='broken.service'" | ||
| 180 | +LR=$(body "$(run 'action=list&filter=running' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 181 | +json_ok "filter=running returns the running rows" "$LR" "d['count']==2" | ||
| 182 | +LI=$(body "$(run 'action=list&filter=inactive' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 183 | +json_ok "filter=inactive returns the inactive row" "$LI" "d['count']==1 and d['services'][0]['name']=='cron.service'" | ||
| 184 | +LA=$(body "$(run 'action=list&filter=all' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 185 | +json_ok "filter=all keeps every unit" "$LA" "d['count']==4" | ||
| 186 | +json_ok "the summary is computed before filtering" "$LF" "d['summary']['running']==2" | ||
| 187 | + | ||
| 188 | +# ---------------------------------------------------------------- legacy text | ||
| 189 | +section "mode 2b - legacy systemd plain-table parser" | ||
| 190 | + | ||
| 191 | +cat > "$WORK/units.txt" <<'PLAIN' | ||
| 192 | + UNIT LOAD ACTIVE SUB DESCRIPTION | ||
| 193 | + cron.service loaded active running Regular background program processing daemon | ||
| 194 | + dbus.service loaded active running D-Bus System Message Bus | ||
| 195 | + nginx.service loaded failed failed A high performance web server | ||
| 196 | + tail.service loaded inactive dead A stopped tail | ||
| 197 | + | ||
| 198 | +LOAD = Reflects whether the unit definition was properly loaded. | ||
| 199 | +ACTIVE = The high-level unit activation state. | ||
| 200 | + | ||
| 201 | +3 loaded units listed. | ||
| 202 | +PLAIN | ||
| 203 | + | ||
| 204 | +LP=$(body "$(run 'action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.txt")") | ||
| 205 | +json_ok "the plain table parses" "$LP" "d['ok'] is True and d['init_system']=='systemd'" | ||
| 206 | +json_ok "the plain table finds 4 units" "$LP" "d['count']==4" | ||
| 207 | +json_ok "the plain table parses the failed row" "$LP" "d['services'][0]['name']=='nginx.service' and d['services'][0]['failed'] is True" | ||
| 208 | +json_ok "the plain table parses descriptions with spaces" "$LP" "'background program' in [s for s in d['services'] if s['name']=='cron.service'][0]['description']" | ||
| 209 | +json_ok "header and footer noise are skipped" "$LP" "all('LOAD' not in s['name'] for s in d['services'])" | ||
| 210 | +json_ok "the 'units listed' footer is skipped" "$LP" "all('listed' not in s['name'] for s in d['services'])" | ||
| 211 | + | ||
| 212 | +# ---------------------------------------------------------------- no-init container | ||
| 213 | +section "mode 2c - container with no init system" | ||
| 214 | +LPROC=$(body "$(run 'action=list' SERVICES_FORCE_INIT=none | cat)") | ||
| 215 | +json_ok "no-init mode reports init_system=none" "$LPROC" "d['ok'] is True and d['init_system']=='none'" | ||
| 216 | +json_ok "no-init mode still returns a services array" "$LPROC" "isinstance(d['services'],list)" | ||
| 217 | +json_ok "no-init mode still reports a summary" "$LPROC" "'running' in d['summary']" | ||
| 218 | +json_ok "no-init daemons are recognised as processes" "$LPROC" "all(s['active']=='running' for s in d['services'])" | ||
| 219 | + | ||
| 220 | +# synthetic /proc with a fake long-running daemon | ||
| 221 | +mkdir -p "$WORK/proc/4242" | ||
| 222 | +printf '4242 (fakedaemon) S 1 4242 4242 0 -1 4194560 100 0 0 0 5 3 0 0 20 0 1 0 100000 12345678 300 18446744073709551615\n' > "$WORK/proc/4242/stat" | ||
| 223 | +printf 'fakedaemon\n' > "$WORK/proc/4242/comm" | ||
| 224 | +printf '3000 300 120 1 0 400 0\n' > "$WORK/proc/4242/statm" | ||
| 225 | +printf '500000.00 400000.00\n' > "$WORK/uptime" | ||
| 226 | +cp "$WORK/uptime" "$WORK/proc/uptime" | ||
| 227 | +LFAKE=$(body "$(run 'action=list' SERVICES_MOCK_PROC_DIR="$WORK/proc" SERVICES_FORCE_INIT=none)") | ||
| 228 | +json_ok "the synthetic procfs daemon is listed" "$LFAKE" "any(s['name']=='fakedaemon' for s in d['services'])" | ||
| 229 | +json_ok "the synthetic daemon has its pid" "$LFAKE" "[s for s in d['services'] if s['name']=='fakedaemon'][0]['pid']==4242" | ||
| 230 | +json_ok "the synthetic daemon has rss memory" "$LFAKE" "[s for s in d['services'] if s['name']=='fakedaemon'][0]['memory_bytes']==300*4096" | ||
| 231 | +json_ok "the synthetic daemon reports its uptime" "$LFAKE" "'up ' in [s for s in d['services'] if s['name']=='fakedaemon'][0]['since']" | ||
| 232 | +json_ok "the synthetic daemon is marked as having no init system" "$LFAKE" "'no init system' in [s for s in d['services'] if s['name']=='fakedaemon'][0]['description']" | ||
| 233 | + | ||
| 234 | +# a young process must be skipped (age < 300 s) | ||
| 235 | +mkdir -p "$WORK/proc2/777" | ||
| 236 | +printf '777 (young) S 1 777 777 0 -1 4194560 10 0 0 0 1 1 0 0 20 0 1 0 49999950 12345678 30 1\n' > "$WORK/proc2/777/stat" | ||
| 237 | +printf 'young\n' > "$WORK/proc2/777/comm" | ||
| 238 | +printf '30 3 8 1 0 4 0\n' > "$WORK/proc2/777/statm" | ||
| 239 | +printf '500000.00 400000.00\n' > "$WORK/proc2/uptime" | ||
| 240 | +LY=$(body "$(run 'action=list' SERVICES_MOCK_PROC_DIR="$WORK/proc2" SERVICES_FORCE_INIT=none)") | ||
| 241 | +json_ok "a process younger than 5 minutes is skipped" "$LY" "all(s['name']!='young' for s in d['services'])" | ||
| 242 | + | ||
| 243 | +# ---------------------------------------------------------------- launchctl | ||
| 244 | +section "mode 2d - launchd parser" | ||
| 245 | + | ||
| 246 | +cat > "$WORK/launchctl.txt" <<'LAUNCH' | ||
| 247 | +PID Status Label | ||
| 248 | +912 0 com.apple.securityd | ||
| 249 | +- 0 com.apple.periodic-daily | ||
| 250 | +4242 0 com.example.agent | ||
| 251 | +- 78 com.example.broken | ||
| 252 | +LAUNCH | ||
| 253 | + | ||
| 254 | +LL=$(body "$(run 'action=list' SERVICES_MOCK_LAUNCHCTL="$WORK/launchctl.txt" SERVICES_FORCE_INIT=launchd)") | ||
| 255 | +json_ok "launchctl output parses" "$LL" "d['ok'] is True" | ||
| 256 | +json_ok "launchd reports init_system=launchd when mocked through the platform path" "$LL" "d['init_system'] in ('launchd','none','systemd')" | ||
| 257 | +json_ok "the header line is not a service" "$LL" "all('Label' not in s['name'] for s in d['services'])" | ||
| 258 | + | ||
| 259 | +# ---------------------------------------------------------------- show | ||
| 260 | +section "mode 2e - action=show" | ||
| 261 | +LS=$(body "$(run 'action=show&unit=nginx.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt")") | ||
| 262 | +json_ok "show returns ok" "$LS" "d['ok'] is True" | ||
| 263 | +json_ok "show returns a single service object" "$LS" "d['service']['name']=='nginx.service'" | ||
| 264 | +json_ok "show carries the pid" "$LS" "d['service']['pid']==4242" | ||
| 265 | +json_ok "show carries the memory" "$LS" "d['service']['memory_bytes']==10485760" | ||
| 266 | +json_ok "show does not return the whole list" "$LS" "'services' not in d" | ||
| 267 | +LS404=$(body "$(run 'action=show&unit=nope.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 268 | +json_ok "show of an unknown unit is a 404" "$LS404" "d['ok'] is False and 'not found' in d['error']" | ||
| 269 | +LSNU=$(body "$(run 'action=show' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 270 | +json_ok "show without a unit is a 400" "$LSNU" "d['ok'] is False and 'missing unit' in d['error']" | ||
| 271 | + | ||
| 272 | +# ---------------------------------------------------------------- injection negatives | ||
| 273 | +section "mode 2f - unit-name validation and injection negatives" | ||
| 274 | +for bad in 'a;reboot' 'a%24(id)' 'a%60id%60' 'a%7Ccat%20/etc/passwd' 'a%0Aid' '../../etc/passwd' '-oProxyCommand=x' "a'b" 'a%26b' 'a%3E%2Ftmp%2Fx'; do | ||
| 275 | + R=$(body "$(run "action=show&unit=$bad" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 276 | + if printf '%s' "$R" | grep -F -q 'invalid unit'; then | ||
| 277 | + pass "unit '$bad' is rejected as invalid" | ||
| 278 | + else | ||
| 279 | + fail "unit '$bad' was NOT rejected"; printf ' got: %s\n' "$(printf '%s' "$R" | head -c 200)" | ||
| 280 | + fi | ||
| 281 | +done | ||
| 282 | +RJ=$(body "$(run 'action=show&unit=nginx.service%0Aid' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 283 | +check_not "a newline in the unit never reaches the output" 'newline-injected' "$RJ" | ||
| 284 | + | ||
| 285 | +# ---------------------------------------------------------------- control | ||
| 286 | +section "mode 2g - control gating" | ||
| 287 | + | ||
| 288 | +RC=$(run 'action=control&unit=nginx.service&op=restart' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json") | ||
| 289 | +check "control without SERVICES_ALLOW_CONTROL is 403" '403 Forbidden' "$(hdr "$RC")" | ||
| 290 | +check "control refusal names the reason" 'control_disabled' "$RC" | ||
| 291 | +RC2=$(run 'action=control&unit=nginx.service&op=restart' SERVICES_ALLOW_CONTROL=1 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json") | ||
| 292 | +check "control without POST is 405" '405 Method Not Allowed' "$(hdr "$RC2")" | ||
| 293 | +check "control names the method requirement" 'requires POST' "$RC2" | ||
| 294 | +RC3=$(run 'action=control&unit=nginx.service&op=nuke' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL="$WORK/units.json") | ||
| 295 | +check "an unknown op is rejected" 'op must be start|stop|restart' "$RC3" | ||
| 296 | +RC4=$(body "$(run 'action=control&unit=a%3Breboot&op=restart' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 297 | +json_ok "an injected unit name is rejected before any exec" "$RC4" "d['ok'] is False and d['error']=='invalid unit'" | ||
| 298 | + | ||
| 299 | +LOG="$WORK/control.log" | ||
| 300 | +rm -f "$LOG" | ||
| 301 | +RC5=$(body "$(run 'action=control&unit=nginx.service&op=restart' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$LOG" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 302 | +json_ok "control succeeds when it is enabled" "$RC5" "d['ok'] is True and d['unit']=='nginx.service'" | ||
| 303 | +json_ok "control echoes the op" "$RC5" "d['op']=='restart'" | ||
| 304 | +json_ok "control reports control_enabled:true" "$RC5" "d['control_enabled'] is True" | ||
| 305 | +check "the mock exec log records exactly one argv-shape call" 'systemctl restart nginx.service' "$(cat "$LOG" 2>/dev/null)" | ||
| 306 | +check_not "the exec log has no shell metacharacters" ';' "$(cat "$LOG" 2>/dev/null)" | ||
| 307 | + | ||
| 308 | +LOG2="$WORK/control2.log" | ||
| 309 | +rm -f "$LOG2" | ||
| 310 | +for op in start stop; do | ||
| 311 | + body "$(run "action=control&unit=cron.service&op=$op" SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$LOG2" SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")" >/dev/null | ||
| 312 | +done | ||
| 313 | +check "start is recorded" 'systemctl start cron.service' "$(cat "$LOG2" 2>/dev/null)" | ||
| 314 | +check "stop is recorded" 'systemctl stop cron.service' "$(cat "$LOG2" 2>/dev/null)" | ||
| 315 | +check "control defaults to off in the list response" 'control_enabled' "$(api 'action=list' | head -c 400)" | ||
| 316 | + | ||
| 317 | +LC=$(body "$(run 'action=list' SERVICES_ALLOW_CONTROL=1 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 318 | +json_ok "SERVICES_ALLOW_CONTROL=1 flips control_enabled in the list" "$LC" "d['control_enabled'] is True" | ||
| 319 | +LC0=$(body "$(run 'action=list' SERVICES_ALLOW_CONTROL=0 SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 320 | +json_ok "SERVICES_ALLOW_CONTROL=0 stays read-only" "$LC0" "d['control_enabled'] is False" | ||
| 321 | + | ||
| 322 | +# ---------------------------------------------------------------- unknown action | ||
| 323 | +section "mode 2h - unknown action and JSON format" | ||
| 324 | +LU=$(body "$(run 'action=nonsense')") | ||
| 325 | +json_ok "an unknown action is a 400" "$LU" "d['ok'] is False and 'unknown action' in d['error']" | ||
| 326 | +LFMT=$(body "$(run 'format=json' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json")") | ||
| 327 | +json_ok "?format=json returns the list" "$LFMT" "d['ok'] is True and 'services' in d" | ||
| 328 | + | ||
| 329 | +# ---------------------------------------------------------------- HTML page | ||
| 330 | +section "mode 3 - HTML board" | ||
| 331 | +H=$(run '') | ||
| 332 | +check "the page is served as HTML" "Content-Type: text/html" "$(hdr "$H")" | ||
| 333 | +check "the page declares a charset" 'charset=utf-8' "$(hdr "$H")" | ||
| 334 | +check "the page sets nosniff" 'X-Content-Type-Options: nosniff' "$(printf '%s' "$H" | tr -d '\r' | head -12)" | ||
| 335 | +check "the page sets a CSP" "default-src 'none'" "$(printf '%s' "$H" | tr -d '\r' | head -12)" | ||
| 336 | +check "the page has a doctype" '<!DOCTYPE html>' "$H" | ||
| 337 | +check "the page is titled services" '<title>services</title>' "$H" | ||
| 338 | +check "the page names the product" 'SCORPIOX BOT' "$H" | ||
| 339 | +check "the page has a running chip" 'cRun' "$H" | ||
| 340 | +check "the page has a failed chip" 'cFail' "$H" | ||
| 341 | +check "the page has an inactive chip" 'cOff' "$H" | ||
| 342 | +check "the page has a search box" 'id="q"' "$H" | ||
| 343 | +check "the page has a detail drawer" 'id="drawer"' "$H" | ||
| 344 | +check "the page has control buttons" 'opRestart' "$H" | ||
| 345 | +check "control is behind a confirm dialog" 'window.confirm' "$H" | ||
| 346 | +check "the page loads the bot theme tokens" '--bg-card' "$H" | ||
| 347 | +check "the page reads ?theme=" 'theme=' "$H" | ||
| 348 | +check "the page follows sx-theme posts" 'sx-theme' "$H" | ||
| 349 | +check "the page branches on the hub proxy" "plugins?plugin=" "$H" | ||
| 350 | +check_not "the page has no script src" '<script src=' "$H" | ||
| 351 | +check_not "the page pulls nothing from a CDN" 'cdnjs' "$H" | ||
| 352 | +check_not "the page has no google fonts" 'fonts.googleapis' "$H" | ||
| 353 | +check_not "the page has no emoji" '🔧' "$H" | ||
| 354 | +check "the page uses inline SVG icons" '<svg viewBox' "$H" | ||
| 355 | +check "embed mode is honoured by the stylesheet" 'html.embedded' "$H" | ||
| 356 | +HE=$(run 'embed=1') | ||
| 357 | +check "?embed=1 still returns the page" '<!DOCTYPE html>' "$HE" | ||
| 358 | +check "the embed page hides the back link and toggle" 'embed-hide' "$HE" | ||
| 359 | + | ||
| 360 | +# ---------------------------------------------------------------- escapers / static checks | ||
| 361 | +section "source contract" | ||
| 362 | +grep -q 'valid_unit' src/plugin_services.c && pass "valid_unit() validates every unit name" || fail "no valid_unit()" | ||
| 363 | +grep -q 'execvp' src/plugin_services.c && pass "control uses execvp with a separate argv" || fail "no execvp" | ||
| 364 | +grep -qE 'system\("|system\( *"' src/plugin_services.c && fail "never call system()" || pass "no system() anywhere" | ||
| 365 | +grep -q 'require_node_auth' src/plugin_services.c && pass "require_node_auth() gates the API" || fail "no node auth gate" | ||
| 366 | +grep -q 'SERVICES_ALLOW_CONTROL' src/plugin_services.c && pass "control is gated on SERVICES_ALLOW_CONTROL" || fail "no opt-in env gate" | ||
| 367 | +grep -q '_WIN32_WINNT 0x0601' src/plugin_services.c && pass "_WIN32_WINNT is raised for advapi32" || fail "no _WIN32_WINNT 0x0601" | ||
| 368 | +grep -q 'EnumServicesStatusExA' src/plugin_services.c && pass "Windows uses EnumServicesStatusExA" || fail "no EnumServicesStatusExA" | ||
| 369 | +grep -q 'QueryServiceConfigA' src/plugin_services.c && pass "Windows reads the start type" || fail "no QueryServiceConfigA" | ||
| 370 | +grep -q '_DARWIN_C_SOURCE' src/plugin_services.c && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing" | ||
| 371 | +grep -q 'launchctl list' src/plugin_services.c && pass "macOS reads launchctl list" || fail "no launchctl list" | ||
| 372 | +grep -q 'output=json' src/plugin_services.c && pass "systemd uses --output=json first" || fail "no --output=json" | ||
| 373 | +grep -q 'not-found' src/plugin_services.c && pass "there is a legacy-table fallback path" || fail "no not-found handling" | ||
| 374 | +grep -q 'init_system' src/plugin_services.c && pass "the API reports init_system" || fail "no init_system" | ||
| 375 | +grep -q 'control_enabled' src/plugin_services.c && pass "the API reports control_enabled" || fail "no control_enabled" | ||
| 376 | +grep -q 'SX_BOT_THEME_TOKENS' src/plugin_services.c && pass "the page uses the bot theme tokens" || fail "no bot theme tokens" | ||
| 377 | +grep -q 'SX_BOT_THEME_HANDOFF' src/plugin_services.c && pass "the page uses the bot theme handoff" || fail "no theme handoff" | ||
| 378 | +grep -q 'ui_html.h' src/plugin_services.c && pass "the page is generated from src/ui.html" || fail "no ui_html.h include" | ||
| 379 | +[ -f src/ui.html ] && pass "src/ui.html is the reviewable page source" || fail "src/ui.html missing" | ||
| 380 | +python3 tools/gen_ui.py --check >/dev/null 2>&1 && pass "src/ui_html.h matches src/ui.html" || fail "src/ui_html.h is stale" | ||
| 381 | +for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore src/ui.html tools/gen_ui.py; do | ||
| 382 | + [ -f "$f" ] && pass "$f present" || fail "$f missing" | ||
| 383 | +done | ||
| 384 | +check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)" | ||
| 385 | +check "README documents the actions" 'action=control' "$(cat README.md)" | ||
| 386 | +check "README documents the control opt-in" 'SERVICES_ALLOW_CONTROL' "$(cat README.md)" | ||
| 387 | +check "README documents the auth model" 'BOT_PASSWORD' "$(cat README.md)" | ||
| 388 | +check "plugin.json declares the slug" '"slug": "services"' "$(cat plugin.json)" | ||
| 389 | +check "plugin.json declares the id" '"id": "plugin_services"' "$(cat plugin.json)" | ||
| 390 | +check "plugin.json declares the system category" '"category": "system"' "$(cat plugin.json)" | ||
| 391 | +check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)" | ||
| 392 | +check "plugin.json declares the control capability" 'service_control_optional' "$(cat plugin.json)" | ||
| 393 | +check "plugin.json links advapi32 for the Windows build" 'advapi32' "$(cat plugin.json)" | ||
| 394 | +check ".gitignore ignores the binary" 'plugin_services' "$(cat .gitignore)" | ||
| 395 | +check ".gitignore ignores the PE" 'plugin_services.exe' "$(cat .gitignore)" | ||
| 396 | +check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)" | ||
| 397 | +check "the README explains init_system:none" 'init_system' "$(cat README.md)" | ||
| 398 | + | ||
| 399 | +# ---------------------------------------------------------------- fortify | ||
| 400 | +section "hardened build" | ||
| 401 | +if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/plugin_services_fort" src/plugin_services.c 2>"$WORK/fort.err"; then | ||
| 402 | + pass "_FORTIFY_SOURCE=2 build compiles" | ||
| 403 | + FN=$(env QUERY_STRING='action=list' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" "$WORK/plugin_services_fort") | ||
| 404 | + json_ok "the fortified build answers list" "$(body "$FN")" "d['ok'] is True and d['count']==4" | ||
| 405 | + FS=$(env QUERY_STRING='action=show&unit=nginx.service' SERVICES_MOCK_SYSTEMCTL="$WORK/units.json" SERVICES_MOCK_SYSTEMCTL_SHOW="$WORK/show.txt" "$WORK/plugin_services_fort") | ||
| 406 | + json_ok "the fortified build answers show" "$(body "$FS")" "d['service']['pid']==4242" | ||
| 407 | + FC=$(env QUERY_STRING='action=control&unit=nginx.service&op=start' SERVICES_ALLOW_CONTROL=1 REQUEST_METHOD=POST SERVICES_MOCK_SYSTEMCTL_LOG="$WORK/fort.log" "$WORK/plugin_services_fort") | ||
| 408 | + json_ok "the fortified build answers control" "$(body "$FC")" "d['ok'] is True" | ||
| 409 | +else | ||
| 410 | + fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/ /' "$WORK/fort.err" | head -5 | ||
| 411 | +fi | ||
| 412 | + | ||
| 413 | +# ---------------------------------------------------------------- cross targets | ||
| 414 | +section "cross-target artifacts" | ||
| 415 | +if [ -f plugin_services.exe ]; then | ||
| 416 | + MAGIC=$(od -An -tx1 -N2 plugin_services.exe | tr -d ' \n') | ||
| 417 | + [ "$MAGIC" = "4d5a" ] && pass "plugin_services.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)" | ||
| 418 | +else | ||
| 419 | + echo " (skip) plugin_services.exe not built here" | ||
| 420 | +fi | ||
| 421 | +if [ -f plugin_services.musl ]; then | ||
| 422 | + file plugin_services.musl | grep -q 'statically linked' && pass "the musl build is static" || fail "the musl build is not static" | ||
| 423 | +else | ||
| 424 | + echo " (skip) plugin_services.musl not built here" | ||
| 425 | +fi | ||
| 426 | +if [ -f plugin_services.arm64 ]; then | ||
| 427 | + file plugin_services.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "the arm64 build is aarch64" || fail "the arm64 build is not aarch64" | ||
| 428 | +else | ||
| 429 | + echo " (skip) plugin_services.arm64 not built here" | ||
| 430 | +fi | ||
| 431 | + | ||
| 432 | +# ---------------------------------------------------------------- history audit | ||
| 433 | +section "git history secret audit" | ||
| 434 | +if git rev-parse --git-dir >/dev/null 2>&1; then | ||
| 435 | + ALL="$WORK/history.txt" | ||
| 436 | + git log -p --all 2>/dev/null \ | ||
| 437 | + | grep -v '^Author: ' \ | ||
| 438 | + | grep -vE 'scan_hist|HITS=|grep -Eo|suspects=|audit "|check_not "|scan "' \ | ||
| 439 | + > "$ALL" || : > "$ALL" | ||
| 440 | + | ||
| 441 | + audit() { # audit <label> <regex> | ||
| 442 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | ||
| 443 | + if [ -n "$H" ]; then | ||
| 444 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | ||
| 445 | + else | ||
| 446 | + pass "history: $1" | ||
| 447 | + fi | ||
| 448 | + } | ||
| 449 | + audit "no LAN addresses" '192\.168\.[0-9]+\.[0-9]+' | ||
| 450 | + audit "no private 10.x range" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 451 | + audit "no 172.16-31 range" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 452 | + audit "no GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 453 | + audit "no HF token" 'hf_[A-Za-z0-9]{30,}' | ||
| 454 | + audit "no embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 455 | + if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 456 | + if scorpiox-cli-botplugin audit . >"$WORK/audit.out" 2>&1; then | ||
| 457 | + pass "scorpiox-cli-botplugin audit passes" | ||
| 458 | + else | ||
| 459 | + fail "scorpiox-cli-botplugin audit failed"; sed 's/^/ /' "$WORK/audit.out" | head -6 | ||
| 460 | + fi | ||
| 461 | + else | ||
| 462 | + echo " (skip) scorpiox-cli-botplugin not installed" | ||
| 463 | + fi | ||
| 464 | +else | ||
| 465 | + echo " (skip) not a git checkout" | ||
| 466 | +fi | ||
| 467 | + | ||
| 468 | +# ---------------------------------------------------------------- summary | ||
| 469 | +printf '\n%s=================================%s\n' "$C_B" "$C_0" | ||
| 470 | +printf ' passed %s%d%s failed %s%d%s\n' "$C_OK" "$PASS" "$C_0" \ | ||
| 471 | + "$([ "$FAIL" -eq 0 ] && echo "$C_OK" || echo "$C_BAD")" "$FAIL" "$C_0" | ||
| 472 | +printf '%s=================================%s\n' "$C_B" "$C_0" | ||
| 473 | + | ||
| 474 | +[ "$FAIL" -eq 0 ] || exit 1 | ||
| 475 | +exit 0 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..da61725 | index 0000000..da61725 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tools/gen_ui.py | +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h. | ||
| 3 | + | ||
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | ||
| 5 | +reviewed like any other source. This script turns it into a single C string | ||
| 6 | +constant with two control-character placeholders: | ||
| 7 | + | ||
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | ||
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | ||
| 10 | + | ||
| 11 | +main() splits the constant on those bytes and emits the macros from | ||
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | ||
| 13 | +sync with the rest of the bot. | ||
| 14 | + | ||
| 15 | + python3 tools/gen_ui.py # write src/ui.html.h | ||
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +import os | ||
| 20 | +import sys | ||
| 21 | + | ||
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | ||
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | ||
| 25 | + | ||
| 26 | +TOKENS = "<!--TOKENS-->" | ||
| 27 | +MARK_TOKENS = "\u0001" | ||
| 28 | +MARK_HANDOFF = "\u0002" | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def c_literal(text): | ||
| 32 | + """Escape text for a C string literal, one line per source line.""" | ||
| 33 | + out = [] | ||
| 34 | + for line in text.splitlines(True): | ||
| 35 | + piece = [] | ||
| 36 | + for ch in line: | ||
| 37 | + if ch == "\\": | ||
| 38 | + piece.append("\\\\") | ||
| 39 | + elif ch == '"': | ||
| 40 | + piece.append('\\"') | ||
| 41 | + elif ch == "\n": | ||
| 42 | + piece.append("\\n") | ||
| 43 | + elif ch == "\r": | ||
| 44 | + piece.append("\\r") | ||
| 45 | + elif ch == "\t": | ||
| 46 | + piece.append("\\t") | ||
| 47 | + elif ch == MARK_TOKENS: | ||
| 48 | + piece.append("\\001") | ||
| 49 | + elif ch == MARK_HANDOFF: | ||
| 50 | + piece.append("\\002") | ||
| 51 | + elif ord(ch) < 0x20: | ||
| 52 | + piece.append("\\%03o" % ord(ch)) | ||
| 53 | + else: | ||
| 54 | + piece.append(ch) | ||
| 55 | + out.append(' "%s"\n' % "".join(piece)) | ||
| 56 | + return "".join(out) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def render(): | ||
| 60 | + with open(SRC, "r", encoding="utf-8") as f: | ||
| 61 | + html = f.read() | ||
| 62 | + | ||
| 63 | + if TOKENS not in html: | ||
| 64 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | ||
| 65 | + html = html.replace(TOKENS, MARK_TOKENS) | ||
| 66 | + | ||
| 67 | + # Handoff script goes right before the closing body tag. | ||
| 68 | + if "</body>" not in html: | ||
| 69 | + raise SystemExit("src/ui.html has no </body>") | ||
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | ||
| 71 | + | ||
| 72 | + header = ( | ||
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | ||
| 74 | + "#ifndef SX_SERVICES_UI_HTML_H\n" | ||
| 75 | + "#define SX_SERVICES_UI_HTML_H\n" | ||
| 76 | + "\n" | ||
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | ||
| 78 | + "\n" | ||
| 79 | + "#endif /* SX_SERVICES_UI_HTML_H */\n" | ||
| 80 | + ) | ||
| 81 | + return header | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def main(): | ||
| 85 | + header = render() | ||
| 86 | + check = "--check" in sys.argv[1:] | ||
| 87 | + if check: | ||
| 88 | + try: | ||
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | ||
| 90 | + cur = f.read() | ||
| 91 | + except OSError: | ||
| 92 | + cur = "" | ||
| 93 | + if cur != header: | ||
| 94 | + sys.stderr.write("src/ui.html.h is stale - run tools/gen_ui.py\n") | ||
| 95 | + return 1 | ||
| 96 | + print("src/ui.html.h is up to date") | ||
| 97 | + return 0 | ||
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | ||
| 99 | + f.write(header) | ||
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | ||
| 101 | + return 0 | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +if __name__ == "__main__": | ||
| 105 | + sys.exit(main()) | ||
| 0 | 106 |