| 1 | 1 | new file mode 100644 |
| index 0000000..791c966 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,9 @@ | ||
| 1 | +/plugin_docker | |
| 2 | +/plugin_docker.exe | |
| 3 | +*.o | |
| 4 | +*.obj | |
| 5 | +bin/ | |
| 6 | +*.tmp | |
| 7 | +*.log | |
| 8 | +/plugin_docker.musl | |
| 9 | +/plugin_docker.macos-* |
| 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..cc652e3 | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,56 @@ | ||
| 1 | +# plugin_docker — ScorpioX Bot open-source container dashboard plugin | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_docker | |
| 5 | +# make musl static musl x86_64 -> ./plugin_docker (fully static) | |
| 6 | +# make win64 MinGW-w64 static -> ./plugin_docker.exe | |
| 7 | +# make macos Apple clang -> ./plugin_docker (run on macOS) | |
| 8 | +# make test build + run tests/run.sh | |
| 9 | +# make clean | |
| 10 | + | |
| 11 | +CC ?= cc | |
| 12 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | |
| 13 | +MUSL_CC ?= musl-gcc | |
| 14 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 15 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 16 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 17 | +SRC := src/plugin_docker.c | |
| 18 | +BIN := plugin_docker | |
| 19 | +EXE := plugin_docker.exe | |
| 20 | + | |
| 21 | +.PHONY: all native musl win64 macos test clean distclean help | |
| 22 | + | |
| 23 | +all: native | |
| 24 | + | |
| 25 | +native: $(BIN) | |
| 26 | + | |
| 27 | +$(BIN): $(SRC) | |
| 28 | + @echo "==> native build ($(CC))" | |
| 29 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 30 | + | |
| 31 | +# Static musl build — the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 32 | +musl: $(SRC) | |
| 33 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 34 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN) $(SRC) | |
| 35 | + | |
| 36 | +# Native Win64 static PE — runs on any Windows 10/11 x64 node | |
| 37 | +win64: $(SRC) | |
| 38 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 39 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | |
| 40 | + | |
| 41 | +# Apple clang build (run this on macOS) | |
| 42 | +macos: $(SRC) | |
| 43 | + @echo "==> Apple clang build" | |
| 44 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | |
| 45 | + | |
| 46 | +test: native | |
| 47 | + @sh tests/run.sh | |
| 48 | + | |
| 49 | +clean: | |
| 50 | + rm -f $(BIN) $(EXE) | |
| 51 | + rm -rf bin | |
| 52 | + | |
| 53 | +distclean: clean | |
| 54 | + | |
| 55 | +help: | |
| 56 | + @echo "make | make musl | make win64 | make macos | make test | make clean" |
| 1 | 1 | new file mode 100644 |
| index 0000000..5d2f0ab | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,190 @@ | ||
| 1 | +# plugin_docker — ScorpioX Bot open-source container dashboard plugin | |
| 2 | + | |
| 3 | +A clean-room, MIT-licensed [ScorpioX Bot](https://bot.scorpiox.net) dynamic plugin that shows | |
| 4 | +the containers running on **your own node**, their live CPU and memory use, their last 100 | |
| 5 | +log lines, and lets you safely start, stop and restart them. | |
| 6 | + | |
| 7 | +One C99 file. No dependencies. No daemon of its own. No outbound network requests. | |
| 8 | + | |
| 9 | +``` | |
| 10 | +plugin_docker --meta | |
| 11 | +{"name":"docker","desc":"Containers"} | |
| 12 | +``` | |
| 13 | + | |
| 14 | +--- | |
| 15 | + | |
| 16 | +## What it does | |
| 17 | + | |
| 18 | +| Area | Detail | | |
| 19 | +|---|---| | |
| 20 | +| **Runtime detection** | Auto-detects `docker` or `podman` on `PATH`; `DOCKER_BIN` overrides with an explicit path. If neither exists the UI says so instead of failing. | | |
| 21 | +| **Container list** | `ps -a` gives ID, name, image, state, status and ports; `stats --no-stream` is merged in for CPU and memory. | | |
| 22 | +| **Log viewer** | `logs --tail 100 <id>`, rendered both as a `lines` array and as raw `text`. | | |
| 23 | +| **Control** | `start` / `stop` / `restart`, **POST only**, op allowlisted, one container at a time. | | |
| 24 | +| **Filtering** | Client-side search across name, image, id and ports, plus a state dropdown. | | |
| 25 | +| **Theme** | Follows the Bot theme (`localStorage.bot_theme`), dark by default, no flash. | | |
| 26 | +| **Embed mode** | `?embed=1` drops the back-link so it fits the chat floating window. | | |
| 27 | + | |
| 28 | +### Why it is safe | |
| 29 | + | |
| 30 | +Container identifiers arrive from the browser, so they are the only real attack surface. | |
| 31 | +Before any identifier can reach a command line it must match: | |
| 32 | + | |
| 33 | +``` | |
| 34 | +[A-Za-z0-9_.-]{1,128} and must not start with '-' or '.' | |
| 35 | +``` | |
| 36 | + | |
| 37 | +That single rule blocks flag injection (`cid=--help`), command injection (`cid=a;id`), | |
| 38 | +substitution (`cid=a$(id)`) and over-long inputs. A test asserts each of these. | |
| 39 | + | |
| 40 | +`action=control` additionally refuses to run unless `REQUEST_METHOD` is POST, and `op` must | |
| 41 | +be one of `start`, `stop`, `restart`. | |
| 42 | + | |
| 43 | +--- | |
| 44 | + | |
| 45 | +## Install | |
| 46 | + | |
| 47 | +### Pre-built (no compiler needed) | |
| 48 | + | |
| 49 | +```sh | |
| 50 | +# Linux x86_64 — the static musl binary works on Alpine, Debian, Ubuntu, Arch, Omarchy | |
| 51 | +mkdir -p ~/.scorpiox/plugins | |
| 52 | +curl -fsSL https://dist.scorpiox.net/bot-plugins/docker/1.0.0/linux-x86_64-musl/plugin_docker \ | |
| 53 | + -o ~/.scorpiox/plugins/plugin_docker | |
| 54 | +chmod +x ~/.scorpiox/plugins/plugin_docker | |
| 55 | +~/.scorpiox/plugins/plugin_docker --meta | |
| 56 | +``` | |
| 57 | + | |
| 58 | +On Windows, put `plugin_docker.exe` in `%LOCALAPPDATA%\scorpiox\plugins\`. | |
| 59 | +On a BotCloud container, use `/workspace/.scorpiox/plugins/` so it survives restarts. | |
| 60 | + | |
| 61 | +No server restart is required — `scorpiox-server` resolves plugin routes live. | |
| 62 | + | |
| 63 | +### From source | |
| 64 | + | |
| 65 | +```sh | |
| 66 | +git clone https://plugingit.scorpiox.net/scorpiox-bot-plugin-docker.git | |
| 67 | +cd scorpiox-bot-plugin-docker | |
| 68 | +make # native | |
| 69 | +make musl # fully static Linux — the universal artifact | |
| 70 | +make win64 # static Windows PE via MinGW-w64 | |
| 71 | +make test # 90+ offline assertions, no real runtime needed | |
| 72 | +cp plugin_docker ~/.scorpiox/plugins/ | |
| 73 | +``` | |
| 74 | + | |
| 75 | +### Let your agent do it | |
| 76 | + | |
| 77 | +Paste this into ScorpioX Bot Chat: | |
| 78 | + | |
| 79 | +> Clone `https://plugingit.scorpiox.net/scorpiox-bot-plugin-docker.git`, audit | |
| 80 | +> `src/plugin_docker.c` for safety, customize it for my machine, compile it natively, verify | |
| 81 | +> `--meta`, and install it to `~/.scorpiox/plugins/`. | |
| 82 | + | |
| 83 | +The whole plugin is one readable C file, so an audit is a five-minute job, not a promise. | |
| 84 | + | |
| 85 | +--- | |
| 86 | + | |
| 87 | +## The three-mode contract | |
| 88 | + | |
| 89 | +Every ScorpioX Bot node plugin is one executable that switches on how it is invoked. | |
| 90 | + | |
| 91 | +### 1. Metadata | |
| 92 | + | |
| 93 | +```sh | |
| 94 | +plugin_docker --meta # or SX_PLUGIN_META=1 plugin_docker | |
| 95 | +{"name":"docker","desc":"Containers"} | |
| 96 | +``` | |
| 97 | + | |
| 98 | +`name` is one word, `desc` is 10 characters. Both are rendered in the Hub `...` menu, the | |
| 99 | +session card `:` menu and Settings, so short is not a style preference — long strings break | |
| 100 | +the layout. | |
| 101 | + | |
| 102 | +### 2. JSON API | |
| 103 | + | |
| 104 | +```sh | |
| 105 | +QUERY_STRING='action=list' plugin_docker | |
| 106 | +QUERY_STRING='action=info' plugin_docker | |
| 107 | +QUERY_STRING='action=logs&cid=web' plugin_docker | |
| 108 | +REQUEST_METHOD=POST CONTENT_LENGTH=17 \ | |
| 109 | + QUERY_STRING='action=control' sh -c 'printf "op=start&cid=web" | plugin_docker' | |
| 110 | +``` | |
| 111 | + | |
| 112 | +All responses are `Content-Type: application/json; charset=utf-8` and, deliberately, | |
| 113 | +**never** carry `Content-Length` — the server owns framing. | |
| 114 | + | |
| 115 | +`action=list`: | |
| 116 | + | |
| 117 | +```json | |
| 118 | +{ | |
| 119 | + "ok": true, | |
| 120 | + "action": "list", | |
| 121 | + "runtime": { "available": true, "bin": "docker", "label": "docker" }, | |
| 122 | + "daemon_available": true, | |
| 123 | + "count": 2, | |
| 124 | + "summary": { "total": 2, "running": 2, "exited": 0, "paused": 0, "other": 0 }, | |
| 125 | + "containers": [ | |
| 126 | + { "id": "a1b2c3d4e5f6", "name": "web", "image": "nginx:1.27", | |
| 127 | + "state": "running", "status": "Up 3 hours", | |
| 128 | + "ports": "0.0.0.0:8080->80/tcp", "cpu": "1.25%", "mem": "12.5MiB / 1GiB" } | |
| 129 | + ] | |
| 130 | +} | |
| 131 | +``` | |
| 132 | + | |
| 133 | +When no runtime exists the same shape comes back with | |
| 134 | +`"runtime":{"available":false}` and a `message`, so a caller never has to special-case an | |
| 135 | +error path. | |
| 136 | + | |
| 137 | +| Error | HTTP | Meaning | | |
| 138 | +|---|---|---| | |
| 139 | +| `invalid_cid` | 400 | identifier failed validation | | |
| 140 | +| `invalid_op` | 400 | op was not start/stop/restart | | |
| 141 | +| `unknown_action` | 400 | unknown `action` (response lists supported ones) | | |
| 142 | +| `control_requires_post` | 405 | `action=control` without POST | | |
| 143 | +| `runtime_available` | 503 | no docker and no podman on this node | | |
| 144 | +| (runtime failed) | 409 | the runtime itself returned non-zero | | |
| 145 | + | |
| 146 | +### 3. HTML UI | |
| 147 | + | |
| 148 | +Plain `GET` returns the dashboard. It uses no framework, no CDN and no build step. | |
| 149 | + | |
| 150 | +--- | |
| 151 | + | |
| 152 | +## Routing: the one thing everyone gets wrong | |
| 153 | + | |
| 154 | +The same HTML is served two different ways, and the JS has to build the right URL for each. | |
| 155 | + | |
| 156 | +| Opened as | Fetch must go to | | |
| 157 | +|---|---| | |
| 158 | +| `https://bot.scorpiox.net/plugins?plugin=plugin_docker` (hub) | `/plugins?plugin=plugin_docker&action=list&node=...` | | |
| 159 | +| `https://<node>:8150/plugin_docker` (direct) | `/plugin_docker?action=list` | | |
| 160 | + | |
| 161 | +The plugin detects which one it is by looking for `?plugin=` on its own URL. Getting this | |
| 162 | +backwards produces the classic "works on the node, blank on the hub" bug. | |
| 163 | + | |
| 164 | +--- | |
| 165 | + | |
| 166 | +## Layout | |
| 167 | + | |
| 168 | +``` | |
| 169 | +src/plugin_docker.c 40 KB, the entire plugin (POSIX + _WIN32, C99) | |
| 170 | +tests/run.sh offline suite: mock runtime, injection attempts, HTML, history audit | |
| 171 | +Makefile native / musl / win64 / macos / test / clean | |
| 172 | +build.ps1 Windows build with an MZ header assertion and a --meta smoke test | |
| 173 | +release-dist.sh secret scan -> build -> manifest -> dist upload -> plugingit mirror | |
| 174 | +``` | |
| 175 | + | |
| 176 | +## Tests | |
| 177 | + | |
| 178 | +```sh | |
| 179 | +make test | |
| 180 | +``` | |
| 181 | + | |
| 182 | +The suite needs no container runtime: it writes a mock `DOCKER_BIN` shell script and points | |
| 183 | +`DOCKER_BIN` at it. It then asserts metadata, every JSON shape, both injection classes, | |
| 184 | +POST-only control, the HTML contract (no `Content-Length`, no emoji, no private IPs, embed | |
| 185 | +mode) and finally walks the **entire git history** looking for LAN addresses, PATs, tokens | |
| 186 | +and host passwords. | |
| 187 | + | |
| 188 | +## License | |
| 189 | + | |
| 190 | +MIT. Copyright (c) 2026 SCORPIOX INC. |
| 1 | 1 | new file mode 100644 |
| index 0000000..8581f54 | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,53 @@ | ||
| 1 | +# build.ps1 — Windows MinGW-w64 static build for plugin_docker | |
| 2 | +# | |
| 3 | +# Usage (from the repo root, PowerShell): | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 5 | +# | |
| 6 | +# Produces .\plugin_docker.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_docker.c" | |
| 14 | + $Out = Join-Path $ScriptDir "plugin_docker.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 | + Write-Host "==> building plugin_docker.exe with $Cc" | |
| 31 | + & $Cc -O2 -std=c99 -Wall -Wextra -static -o $Out $Src | |
| 32 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | |
| 33 | + | |
| 34 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | |
| 35 | + | |
| 36 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | |
| 37 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | |
| 38 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | |
| 39 | + throw "output is not a PE executable (missing MZ header)" | |
| 40 | + } | |
| 41 | + | |
| 42 | + Write-Host "==> metadata check" | |
| 43 | + & $Out --meta | |
| 44 | + if ($LASTEXITCODE -ne 0) { throw "--meta failed" } | |
| 45 | + | |
| 46 | + $size = (Get-Item $Out).Length | |
| 47 | + Write-Host "" | |
| 48 | + Write-Host "Built $Out ($size bytes)" | |
| 49 | + Write-Host "Install: Copy-Item plugin_docker.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`"" | |
| 50 | +} | |
| 51 | +finally { | |
| 52 | + Pop-Location | |
| 53 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..a3f9efd | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,350 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh — build, scan and publish plugin_docker 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 -> plugingit mirror. | |
| 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 | + | |
| 27 | +set -euo pipefail | |
| 28 | + | |
| 29 | +SLUG="docker" | |
| 30 | +ID="plugin_docker" | |
| 31 | +VERSION="1.0.0" | |
| 32 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | |
| 33 | + | |
| 34 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | |
| 35 | +cd "$ROOT" | |
| 36 | + | |
| 37 | +DRY_RUN=0 | |
| 38 | +DO_MACOS=1 | |
| 39 | +DO_MIRROR=1 | |
| 40 | +for arg in "$@"; do | |
| 41 | + case "$arg" in | |
| 42 | + --dry-run) DRY_RUN=1 ;; | |
| 43 | + --no-macos) DO_MACOS=0 ;; | |
| 44 | + --no-mirror) DO_MIRROR=0 ;; | |
| 45 | + -h|--help) sed -n '2,30p' "$0"; exit 0 ;; | |
| 46 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | |
| 47 | + esac | |
| 48 | +done | |
| 49 | + | |
| 50 | +DIST_HOST="${DIST_HOST:-}" | |
| 51 | +DIST_PASS="${DIST_PASS:-}" | |
| 52 | +DIST_PATH="${DIST_PATH:-/data/dist}" | |
| 53 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | |
| 54 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | |
| 55 | + | |
| 56 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | |
| 57 | +mkdir -p "$STAGE" | |
| 58 | +trap 'rm -rf "$STAGE"' EXIT | |
| 59 | + | |
| 60 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | |
| 61 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | |
| 62 | + | |
| 63 | +# ---------------------------------------------------------------- 0. preflight | |
| 64 | +say "0/7 preflight" | |
| 65 | + | |
| 66 | +if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 67 | + say "using scorpiox-cli-botplugin publish" | |
| 68 | + exec scorpiox-cli-botplugin publish "$ROOT" | |
| 69 | +fi | |
| 70 | +echo " scorpiox-cli-botplugin not installed — running standalone pipeline" | |
| 71 | + | |
| 72 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | |
| 73 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | |
| 74 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | |
| 75 | +echo " version $VERSION" | |
| 76 | +echo " commit $COMMIT" | |
| 77 | + | |
| 78 | +# ---------------------------------------------------------------- 1. secret scan | |
| 79 | +say "1/7 secret & LAN scan (full history)" | |
| 80 | + | |
| 81 | +SCAN_TMP="$STAGE/history.txt" | |
| 82 | +# Scan every added/removed line of every commit. Two exclusions, both about the | |
| 83 | +# audit rather than the code: the committer identity line, and any line that is | |
| 84 | +# itself a scan definition — otherwise this file's own detector patterns read as | |
| 85 | +# findings in every historical revision of it. | |
| 86 | +git log -p --all 2>/dev/null \ | |
| 87 | + | grep -v '^Author: ' \ | |
| 88 | + | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \ | |
| 89 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | |
| 90 | +HITS=0 | |
| 91 | +scan() { # scan <label> <regex> | |
| 92 | + local out | |
| 93 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | |
| 94 | + if [ -n "$out" ]; then | |
| 95 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | |
| 96 | + printf '%s\n' "$out" | sed 's/^/ /' | |
| 97 | + HITS=$((HITS + 1)) | |
| 98 | + else | |
| 99 | + printf ' ok %s\n' "$1" | |
| 100 | + fi | |
| 101 | +} | |
| 102 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 103 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 104 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 105 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 106 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 107 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 108 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | |
| 109 | +P_ROOT="/codebases" | |
| 110 | +P_PICOBOT="${P_ROOT}/pico""bot" | |
| 111 | +P_WT=".work""trees" | |
| 112 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | |
| 113 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | |
| 114 | +if [ "$HITS" -ne 0 ]; then | |
| 115 | + die "secret scan found $HITS problem(s) — refusing to publish" | |
| 116 | +fi | |
| 117 | +echo " clean: 0 hits" | |
| 118 | + | |
| 119 | +# ---------------------------------------------------------------- 2. build | |
| 120 | +say "2/7 build targets" | |
| 121 | + | |
| 122 | +build_ok() { [ -f "$1" ]; } | |
| 123 | + | |
| 124 | +# linux-x86_64 (glibc, native) | |
| 125 | +if command -v cc >/dev/null 2>&1; then | |
| 126 | + cc -O2 -std=c99 -Wall -Wextra -o "$STAGE/$ID" src/$ID.c || die "native build failed" | |
| 127 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | |
| 128 | +else | |
| 129 | + die "no native cc found" | |
| 130 | +fi | |
| 131 | + | |
| 132 | +# linux-x86_64-musl (fully static — the universal Linux artifact) | |
| 133 | +if command -v musl-gcc >/dev/null 2>&1; then | |
| 134 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.musl" src/$ID.c \ | |
| 135 | + || die "musl build failed" | |
| 136 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | |
| 137 | +else | |
| 138 | + echo " skip linux-x86_64-musl (no musl-gcc)" | |
| 139 | +fi | |
| 140 | + | |
| 141 | +# windows-x86_64 (static PE) | |
| 142 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | |
| 143 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.exe" src/$ID.c \ | |
| 144 | + || die "MinGW build failed" | |
| 145 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | |
| 146 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | |
| 147 | +else | |
| 148 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | |
| 149 | +fi | |
| 150 | + | |
| 151 | +# macOS legs — Mach-O must be produced by Apple clang on a real Mac. | |
| 152 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | |
| 153 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | |
| 154 | + MAC_USER="${MAC_USER:-$(whoami)}" | |
| 155 | + MAC_DIR="/tmp/${ID}-mac-$$" | |
| 156 | + echo " building macOS legs on $MAC_HOST" | |
| 157 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | |
| 158 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | |
| 159 | + if [ -n "${MAC_PASS:-}" ]; then | |
| 160 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | |
| 161 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | |
| 162 | + fi | |
| 163 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | |
| 164 | + if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then | |
| 165 | + # Build straight from the uploaded file — no src/ tree on the remote. | |
| 166 | + for slice in arm64 x86_64; do | |
| 167 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | |
| 168 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -arch $slice -o $ID.$slice $ID.c" \ | |
| 169 | + 2>/dev/null; then | |
| 170 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | |
| 171 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | |
| 172 | + else | |
| 173 | + echo " warn: macos-$slice build failed on $MAC_HOST" | |
| 174 | + fi | |
| 175 | + done | |
| 176 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true | |
| 177 | + else | |
| 178 | + echo " warn: mac scp failed" | |
| 179 | + fi | |
| 180 | + else | |
| 181 | + echo " warn: mac host unreachable" | |
| 182 | + fi | |
| 183 | +else | |
| 184 | + echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)" | |
| 185 | +fi | |
| 186 | + | |
| 187 | +# ---------------------------------------------------------------- 3. package | |
| 188 | +say "3/7 package" | |
| 189 | + | |
| 190 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | |
| 191 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | |
| 192 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | |
| 193 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | |
| 194 | + | |
| 195 | +target_meta() { # target_meta <key> <file> <format> <relpath> <name> | |
| 196 | + local key="$1" file="$2" fmt="$3" rel="$4" name="$5" | |
| 197 | + [ -f "$file" ] || return 0 | |
| 198 | + local sha size | |
| 199 | + sha=$(sha256sum "$file" | awk '{print $1}') | |
| 200 | + size=$(wc -c < "$file" | tr -d ' ') | |
| 201 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | |
| 202 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | |
| 203 | +} | |
| 204 | + | |
| 205 | +{ | |
| 206 | + printf '{\n' | |
| 207 | + printf ' "slug": "%s",\n' "$SLUG" | |
| 208 | + printf ' "id": "%s",\n' "$ID" | |
| 209 | + printf ' "name": "docker",\n' | |
| 210 | + printf ' "desc": "Containers",\n' | |
| 211 | + printf ' "title": "Local Container Dashboard",\n' | |
| 212 | + printf ' "summary": "Zero-dependency local Docker and Podman dashboard: container list with live CPU and memory, 100-line log viewer, and safe start/stop/restart - all served from one C99 binary on your own node.",\n' | |
| 213 | + printf ' "category": "containers",\n' | |
| 214 | + printf ' "version": "%s",\n' "$VERSION" | |
| 215 | + printf ' "license": "MIT",\n' | |
| 216 | + printf ' "trust_notice": "Executes native C code on your node. Invokes the local docker or podman CLI to list containers, read logs and change container state; makes zero outbound network requests.",\n' | |
| 217 | + printf ' "capabilities": ["proc_exec_docker", "container_list", "container_logs", "container_state_change"],\n' | |
| 218 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | |
| 219 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | |
| 220 | + printf ' "git_commit": "%s",\n' "$COMMIT" | |
| 221 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 222 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | |
| 223 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | |
| 224 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | |
| 225 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 226 | + printf ' "targets": {\n' | |
| 227 | + first=1 | |
| 228 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | |
| 229 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID" | |
| 230 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID" | |
| 231 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID" | |
| 232 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID" | |
| 233 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID" | |
| 234 | + printf '\n }\n}\n' | |
| 235 | +} > "$STAGE/manifest.json" | |
| 236 | + | |
| 237 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | |
| 238 | + || die "generated manifest.json is not valid JSON" | |
| 239 | +echo " manifest.json ok" | |
| 240 | + | |
| 241 | +# SHA256SUMS — relative paths, exactly as published | |
| 242 | +( cd "$STAGE" | |
| 243 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | |
| 244 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | |
| 245 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | |
| 246 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | |
| 247 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | |
| 248 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | |
| 249 | + true ) > "$STAGE/SHA256SUMS" | |
| 250 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | |
| 251 | + | |
| 252 | +# ---------------------------------------------------------------- 4. stage | |
| 253 | +say "4/7 stage tree" | |
| 254 | +PKG="$STAGE/pkg" | |
| 255 | +mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/macos-arm64" \ | |
| 256 | + "$PKG/macos-x86_64" "$PKG/windows-x86_64" | |
| 257 | +cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID" | |
| 258 | +[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID" | |
| 259 | +[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID" | |
| 260 | +[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID" | |
| 261 | +[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe" | |
| 262 | +cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | |
| 263 | +chmod +x "$PKG"/*/$ID 2>/dev/null || true | |
| 264 | +find "$PKG" -type f | sed 's/^/ /' | |
| 265 | + | |
| 266 | +if [ "$DRY_RUN" -eq 1 ]; then | |
| 267 | + say "dry run — staged at $STAGE/pkg (kept for inspection)" | |
| 268 | + trap - EXIT | |
| 269 | + exit 0 | |
| 270 | +fi | |
| 271 | + | |
| 272 | +# ---------------------------------------------------------------- 5. upload | |
| 273 | +say "5/7 upload" | |
| 274 | + | |
| 275 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload" | |
| 276 | +SSH=(ssh -o StrictHostKeyChecking=no) | |
| 277 | +SCP=(scp -o StrictHostKeyChecking=no) | |
| 278 | +if [ -n "$DIST_PASS" ]; then | |
| 279 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | |
| 280 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | |
| 281 | +fi | |
| 282 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | |
| 283 | + | |
| 284 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | |
| 285 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | |
| 286 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | |
| 287 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | |
| 288 | +# OpenSSH 9 refuses to scp a bare "." source. | |
| 289 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | |
| 290 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | |
| 291 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | |
| 292 | + || die "remote extract failed" | |
| 293 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | |
| 294 | + | |
| 295 | +# latest.json = copy of this version's manifest | |
| 296 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | |
| 297 | + || die "latest.json update failed" | |
| 298 | +echo " updated bot-plugins/$SLUG/latest.json" | |
| 299 | + | |
| 300 | +# index.json — merge, preserving every sibling <slug>/latest.json | |
| 301 | +say "index.json merge" | |
| 302 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | |
| 303 | +import json, os, sys, glob | |
| 304 | +slug = sys.argv[1] | |
| 305 | +entries = {} | |
| 306 | +for p in sorted(glob.glob('*/latest.json')): | |
| 307 | + s = os.path.dirname(p) | |
| 308 | + try: | |
| 309 | + entries[s] = json.load(open(p)) | |
| 310 | + except Exception: | |
| 311 | + pass | |
| 312 | +index = { | |
| 313 | + 'ok': True, | |
| 314 | + 'service': 'bot-plugins-dist', | |
| 315 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | |
| 316 | + 'count': len(entries), | |
| 317 | + 'slugs': sorted(entries), | |
| 318 | + 'plugins': [entries[k] for k in sorted(entries)], | |
| 319 | +} | |
| 320 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | |
| 321 | +os.replace('index.json.tmp', 'index.json') | |
| 322 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | |
| 323 | +PY" || die "index.json merge failed" | |
| 324 | + | |
| 325 | +# ---------------------------------------------------------------- 6. mirror | |
| 326 | +say "6/7 plugingit mirror" | |
| 327 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | |
| 328 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | |
| 329 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|") | |
| 330 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | |
| 331 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | |
| 332 | + echo " mirrored to $PLUGINGIT_REMOTE" | |
| 333 | +else | |
| 334 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | |
| 335 | +fi | |
| 336 | + | |
| 337 | +# ---------------------------------------------------------------- 7. verify | |
| 338 | +say "7/7 verify" | |
| 339 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | |
| 340 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | |
| 341 | +if [ "$CODE" = "200" ]; then | |
| 342 | + 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"])))' \ | |
| 343 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | |
| 344 | +else | |
| 345 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | |
| 346 | +fi | |
| 347 | + | |
| 348 | +printf '\n\033[1mrelease complete\033[0m\n' | |
| 349 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 350 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | 1 | new file mode 100644 |
| index 0000000..f68942f | ||
| --- /dev/null | ||
| +++ b/src/plugin_docker.c | ||
| @@ -0,0 +1,1067 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_docker — ScorpioX Bot open-source container dashboard plugin | |
| 3 | + * | |
| 4 | + * A single clean-room C99 binary that serves THREE modes: | |
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery | |
| 6 | + * 2. ?action=... | ?format=json -> JSON node API (list / logs / control / info) | |
| 7 | + * 3. GET (default) -> responsive HTML container dashboard | |
| 8 | + * | |
| 9 | + * Local node only. Auto-detects `docker` or `podman` on PATH (or DOCKER_BIN). | |
| 10 | + * Every container identifier is validated against [A-Za-z0-9_.-]{1,128} with a | |
| 11 | + * leading-dash rejection BEFORE it can reach a shell, so neither flag injection | |
| 12 | + * (`cid=--help`) nor command injection (`cid=a;id`) is reachable. | |
| 13 | + * | |
| 14 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | |
| 15 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | |
| 16 | + * scorpiox-server on the node. | |
| 17 | + * | |
| 18 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 19 | + */ | |
| 20 | + | |
| 21 | +#if !defined(_WIN32) | |
| 22 | +# define _POSIX_C_SOURCE 200809L | |
| 23 | +# define _DEFAULT_SOURCE 1 | |
| 24 | +#endif | |
| 25 | + | |
| 26 | +#include <stdio.h> | |
| 27 | +#include <stdlib.h> | |
| 28 | +#include <string.h> | |
| 29 | +#include <time.h> | |
| 30 | +#include <ctype.h> | |
| 31 | +#include <errno.h> | |
| 32 | + | |
| 33 | +#if defined(_WIN32) | |
| 34 | +# define WIN32_LEAN_AND_MEAN | |
| 35 | +# include <windows.h> | |
| 36 | +# include <io.h> | |
| 37 | +# define sx_popen _popen | |
| 38 | +# define sx_pclose _pclose | |
| 39 | +# define sx_access _access | |
| 40 | +# define SX_X_OK 0 | |
| 41 | +# define SX_PATH_SEP ';' | |
| 42 | +#else | |
| 43 | +# include <unistd.h> | |
| 44 | +# include <sys/wait.h> | |
| 45 | +# include <sys/stat.h> | |
| 46 | +# define sx_popen popen | |
| 47 | +# define sx_pclose pclose | |
| 48 | +# define sx_access access | |
| 49 | +# define SX_X_OK X_OK | |
| 50 | +# define SX_PATH_SEP ':' | |
| 51 | +#endif | |
| 52 | + | |
| 53 | +#define PLUGIN_SLUG "docker" | |
| 54 | +#define PLUGIN_ID "plugin_docker" | |
| 55 | +#define PLUGIN_VER "1.0.0" | |
| 56 | + | |
| 57 | +#define MAX_CONTAINERS 256 | |
| 58 | +#define LOG_TAIL 100 | |
| 59 | + | |
| 60 | +/* ------------------------------------------------------------------ */ | |
| 61 | +/* Small utilities */ | |
| 62 | +/* ------------------------------------------------------------------ */ | |
| 63 | + | |
| 64 | + | |
| 65 | +/* Percent-decode in place ('+' becomes space). */ | |
| 66 | +static void url_decode(char *s) | |
| 67 | +{ | |
| 68 | + char *o = s; | |
| 69 | + if (!s) return; | |
| 70 | + while (*s) { | |
| 71 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 72 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 73 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 74 | + *o++ = (char)((hi << 4) | lo); | |
| 75 | + s += 3; | |
| 76 | + } else if (*s == '+') { | |
| 77 | + *o++ = ' '; | |
| 78 | + s++; | |
| 79 | + } else { | |
| 80 | + *o++ = *s++; | |
| 81 | + } | |
| 82 | + } | |
| 83 | + *o = '\0'; | |
| 84 | +} | |
| 85 | + | |
| 86 | +/* Read one parameter (decoded) out of a form/query string. */ | |
| 87 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 88 | +{ | |
| 89 | + size_t klen; | |
| 90 | + const char *p; | |
| 91 | + | |
| 92 | + if (!out || outsz == 0) return 0; | |
| 93 | + out[0] = '\0'; | |
| 94 | + if (!qs || !key) return 0; | |
| 95 | + klen = strlen(key); | |
| 96 | + | |
| 97 | + for (p = qs; *p; ) { | |
| 98 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 99 | + const char *v = p + klen + 1; | |
| 100 | + size_t i = 0; | |
| 101 | + while (*v && *v != '&' && i + 1 < outsz) | |
| 102 | + out[i++] = *v++; | |
| 103 | + out[i] = '\0'; | |
| 104 | + url_decode(out); | |
| 105 | + return 1; | |
| 106 | + } | |
| 107 | + p = strchr(p, '&'); | |
| 108 | + if (!p) break; | |
| 109 | + p++; | |
| 110 | + } | |
| 111 | + return 0; | |
| 112 | +} | |
| 113 | + | |
| 114 | +static void json_str(const char *s) | |
| 115 | +{ | |
| 116 | + putchar('"'); | |
| 117 | + for (; s && *s; s++) { | |
| 118 | + unsigned char c = (unsigned char)*s; | |
| 119 | + switch (c) { | |
| 120 | + case '"': fputs("\\\"", stdout); break; | |
| 121 | + case '\\': fputs("\\\\", stdout); break; | |
| 122 | + case '\n': fputs("\\n", stdout); break; | |
| 123 | + case '\r': fputs("\\r", stdout); break; | |
| 124 | + case '\t': fputs("\\t", stdout); break; | |
| 125 | + default: | |
| 126 | + if (c < 0x20) printf("\\u%04x", (unsigned)c); | |
| 127 | + else putchar((int)c); | |
| 128 | + } | |
| 129 | + } | |
| 130 | + putchar('"'); | |
| 131 | +} | |
| 132 | + | |
| 133 | +static void utc_now(char *buf, size_t sz) | |
| 134 | +{ | |
| 135 | + time_t t = time(NULL); | |
| 136 | + struct tm tmv; | |
| 137 | +#if defined(_WIN32) | |
| 138 | + gmtime_s(&tmv, &t); | |
| 139 | +#else | |
| 140 | + gmtime_r(&t, &tmv); | |
| 141 | +#endif | |
| 142 | + if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) { | |
| 143 | + strncpy(buf, "1970-01-01T00:00:00Z", sz - 1); | |
| 144 | + buf[sz - 1] = '\0'; | |
| 145 | + } | |
| 146 | +} | |
| 147 | + | |
| 148 | +static long node_pid(void) | |
| 149 | +{ | |
| 150 | +#if defined(_WIN32) | |
| 151 | + return (long)GetCurrentProcessId(); | |
| 152 | +#else | |
| 153 | + return (long)getpid(); | |
| 154 | +#endif | |
| 155 | +} | |
| 156 | + | |
| 157 | +/* ------------------------------------------------------------------ */ | |
| 158 | +/* Strict identifier validation */ | |
| 159 | +/* ------------------------------------------------------------------ */ | |
| 160 | + | |
| 161 | +/* | |
| 162 | + * Container identifiers (IDs, names, short IDs) must match | |
| 163 | + * [A-Za-z0-9_.-]{1,128} and must not start with '-' or '.'. | |
| 164 | + * Anything else is refused before it can reach a command line. | |
| 165 | + */ | |
| 166 | +static int valid_cid(const char *s) | |
| 167 | +{ | |
| 168 | + size_t n, i; | |
| 169 | + if (!s || !*s) return 0; | |
| 170 | + n = strlen(s); | |
| 171 | + if (n > 128) return 0; | |
| 172 | + if (s[0] == '-' || s[0] == '.') return 0; | |
| 173 | + for (i = 0; i < n; i++) { | |
| 174 | + unsigned char c = (unsigned char)s[i]; | |
| 175 | + if (isalnum(c) || c == '_' || c == '.' || c == '-') continue; | |
| 176 | + return 0; | |
| 177 | + } | |
| 178 | + return 1; | |
| 179 | +} | |
| 180 | + | |
| 181 | +/* The runtime binary path must not contain quoting hazards. */ | |
| 182 | +static int valid_runtime_path(const char *s) | |
| 183 | +{ | |
| 184 | + if (!s || !*s) return 0; | |
| 185 | + if (strchr(s, '\'') || strchr(s, '\n') || strchr(s, '\r')) return 0; | |
| 186 | + return 1; | |
| 187 | +} | |
| 188 | + | |
| 189 | +static int valid_op(const char *s) | |
| 190 | +{ | |
| 191 | + return s && (strcmp(s, "start") == 0 || strcmp(s, "stop") == 0 || | |
| 192 | + strcmp(s, "restart") == 0); | |
| 193 | +} | |
| 194 | + | |
| 195 | +/* ------------------------------------------------------------------ */ | |
| 196 | +/* Command execution */ | |
| 197 | +/* ------------------------------------------------------------------ */ | |
| 198 | + | |
| 199 | +/* Run a shell command, capture stdout+stderr. Returns malloc'd text. */ | |
| 200 | +static char *run_capture(const char *cmd, int *exit_code) | |
| 201 | +{ | |
| 202 | + FILE *fp; | |
| 203 | + char *buf = NULL; | |
| 204 | + size_t len = 0, cap = 0, chunk; | |
| 205 | + char tmp[4096]; | |
| 206 | + int status = 0; | |
| 207 | + | |
| 208 | + if (exit_code) *exit_code = -1; | |
| 209 | + fp = sx_popen(cmd, "r"); | |
| 210 | + if (!fp) return NULL; | |
| 211 | + | |
| 212 | + while ((chunk = fread(tmp, 1, sizeof(tmp), fp)) > 0) { | |
| 213 | + if (len + chunk + 1 > cap) { | |
| 214 | + size_t ncap = cap ? cap * 2 : 8192; | |
| 215 | + char *nb; | |
| 216 | + while (ncap < len + chunk + 1) ncap *= 2; | |
| 217 | + nb = (char *)realloc(buf, ncap); | |
| 218 | + if (!nb) { free(buf); sx_pclose(fp); return NULL; } | |
| 219 | + buf = nb; | |
| 220 | + cap = ncap; | |
| 221 | + } | |
| 222 | + memcpy(buf + len, tmp, chunk); | |
| 223 | + len += chunk; | |
| 224 | + } | |
| 225 | + if (!buf) { | |
| 226 | + buf = (char *)malloc(1); | |
| 227 | + if (!buf) { sx_pclose(fp); return NULL; } | |
| 228 | + cap = 1; | |
| 229 | + } | |
| 230 | + buf[len] = '\0'; | |
| 231 | + | |
| 232 | + status = sx_pclose(fp); | |
| 233 | +#if defined(_WIN32) | |
| 234 | + if (exit_code) *exit_code = status; | |
| 235 | +#else | |
| 236 | + if (exit_code) { | |
| 237 | + if (WIFEXITED(status)) *exit_code = WEXITSTATUS(status); | |
| 238 | + else *exit_code = -1; | |
| 239 | + } | |
| 240 | +#endif | |
| 241 | + return buf; | |
| 242 | +} | |
| 243 | + | |
| 244 | +/* ------------------------------------------------------------------ */ | |
| 245 | +/* Runtime detection */ | |
| 246 | +/* ------------------------------------------------------------------ */ | |
| 247 | + | |
| 248 | +static int path_has_exec(const char *name) | |
| 249 | +{ | |
| 250 | + const char *env = getenv("PATH"); | |
| 251 | + char candidate[1024]; | |
| 252 | + | |
| 253 | + if (!env) return 0; | |
| 254 | + while (*env) { | |
| 255 | + const char *end = strchr(env, SX_PATH_SEP); | |
| 256 | + size_t dlen = end ? (size_t)(end - env) : strlen(env); | |
| 257 | + if (dlen > 0 && dlen + strlen(name) + 2 < sizeof(candidate)) { | |
| 258 | + memcpy(candidate, env, dlen); | |
| 259 | + candidate[dlen] = '\0'; | |
| 260 | +#if defined(_WIN32) | |
| 261 | + snprintf(candidate + dlen, sizeof(candidate) - dlen, "\\%s.exe", name); | |
| 262 | +#else | |
| 263 | + snprintf(candidate + dlen, sizeof(candidate) - dlen, "/%s", name); | |
| 264 | +#endif | |
| 265 | + if (sx_access(candidate, SX_X_OK) == 0) return 1; | |
| 266 | + } | |
| 267 | + if (!end) break; | |
| 268 | + env = end + 1; | |
| 269 | + } | |
| 270 | + return 0; | |
| 271 | +} | |
| 272 | + | |
| 273 | +/* Resolve the container runtime. Returns 1 when something is usable. */ | |
| 274 | +static int detect_runtime(char *bin, size_t binsz, char *label, size_t labelsz) | |
| 275 | +{ | |
| 276 | + const char *ovr = getenv("DOCKER_BIN"); | |
| 277 | + | |
| 278 | + bin[0] = '\0'; | |
| 279 | + label[0] = '\0'; | |
| 280 | + | |
| 281 | + if (ovr && *ovr) { | |
| 282 | + if (!valid_runtime_path(ovr)) return 0; | |
| 283 | + snprintf(bin, binsz, "%s", ovr); | |
| 284 | + snprintf(label, labelsz, "custom"); | |
| 285 | + return 1; | |
| 286 | + } | |
| 287 | + if (path_has_exec("docker")) { | |
| 288 | + snprintf(bin, binsz, "docker"); | |
| 289 | + snprintf(label, labelsz, "docker"); | |
| 290 | + return 1; | |
| 291 | + } | |
| 292 | + if (path_has_exec("podman")) { | |
| 293 | + snprintf(bin, binsz, "podman"); | |
| 294 | + snprintf(label, labelsz, "podman"); | |
| 295 | + return 1; | |
| 296 | + } | |
| 297 | + return 0; | |
| 298 | +} | |
| 299 | + | |
| 300 | +/* ------------------------------------------------------------------ */ | |
| 301 | +/* Container list */ | |
| 302 | +/* ------------------------------------------------------------------ */ | |
| 303 | + | |
| 304 | +typedef struct { | |
| 305 | + char id[80]; | |
| 306 | + char name[192]; | |
| 307 | + char image[192]; | |
| 308 | + char state[32]; | |
| 309 | + char status[192]; | |
| 310 | + char ports[512]; | |
| 311 | + char cpu[32]; | |
| 312 | + char mem[96]; | |
| 313 | +} container_t; | |
| 314 | + | |
| 315 | +static container_t g_containers[MAX_CONTAINERS]; | |
| 316 | +static int g_container_count; | |
| 317 | + | |
| 318 | +/* Split on '|' in place into up to max fields. */ | |
| 319 | +static int split_pipe(char *line, char **out, int max) | |
| 320 | +{ | |
| 321 | + int n = 0; | |
| 322 | + char *p = line; | |
| 323 | + if (max <= 0) return 0; | |
| 324 | + out[n++] = p; | |
| 325 | + while (*p && n < max) { | |
| 326 | + if (*p == '|') { | |
| 327 | + *p = '\0'; | |
| 328 | + out[n++] = p + 1; | |
| 329 | + } | |
| 330 | + p++; | |
| 331 | + } | |
| 332 | + /* consume the remainder of the last field up to a newline */ | |
| 333 | + if (n > 0) { | |
| 334 | + char *e = out[n - 1]; | |
| 335 | + while (*e && *e != '\n' && *e != '\r') e++; | |
| 336 | + *e = '\0'; | |
| 337 | + } | |
| 338 | + return n; | |
| 339 | +} | |
| 340 | + | |
| 341 | +static void copy_field(char *dst, size_t dstsz, const char *src) | |
| 342 | +{ | |
| 343 | + size_t i = 0; | |
| 344 | + if (!dst || dstsz == 0) return; | |
| 345 | + if (!src) { dst[0] = '\0'; return; } | |
| 346 | + while (src[i] && i + 1 < dstsz) { dst[i] = src[i]; i++; } | |
| 347 | + dst[i] = '\0'; | |
| 348 | +} | |
| 349 | + | |
| 350 | +/* Parse `ps -a` output into g_containers. Returns line count parsed. */ | |
| 351 | +static int parse_ps(const char *text) | |
| 352 | +{ | |
| 353 | + const char *p = text; | |
| 354 | + int count = 0; | |
| 355 | + | |
| 356 | + g_container_count = 0; | |
| 357 | + while (*p && g_container_count < MAX_CONTAINERS) { | |
| 358 | + char line[1600]; | |
| 359 | + size_t i = 0; | |
| 360 | + char *fields[6]; | |
| 361 | + int nf; | |
| 362 | + | |
| 363 | + while (*p && *p != '\n' && i + 1 < sizeof(line)) line[i++] = *p++; | |
| 364 | + line[i] = '\0'; | |
| 365 | + while (*p == '\n' || *p == '\r') p++; | |
| 366 | + | |
| 367 | + if (i == 0) continue; | |
| 368 | + /* skip a header row if the runtime emitted one */ | |
| 369 | + if (strncmp(line, "CONTAINER ID", 12) == 0) continue; | |
| 370 | + | |
| 371 | + nf = split_pipe(line, fields, 6); | |
| 372 | + if (nf < 2) continue; | |
| 373 | + | |
| 374 | + { | |
| 375 | + container_t *c = &g_containers[g_container_count]; | |
| 376 | + memset(c, 0, sizeof(*c)); | |
| 377 | + copy_field(c->id, sizeof(c->id), fields[0]); | |
| 378 | + copy_field(c->name, sizeof(c->name), nf > 1 ? fields[1] : ""); | |
| 379 | + copy_field(c->image, sizeof(c->image), nf > 2 ? fields[2] : ""); | |
| 380 | + copy_field(c->state, sizeof(c->state), nf > 3 ? fields[3] : ""); | |
| 381 | + copy_field(c->status, sizeof(c->status), nf > 4 ? fields[4] : ""); | |
| 382 | + copy_field(c->ports, sizeof(c->ports), nf > 5 ? fields[5] : ""); | |
| 383 | + g_container_count++; | |
| 384 | + count++; | |
| 385 | + } | |
| 386 | + } | |
| 387 | + return count; | |
| 388 | +} | |
| 389 | + | |
| 390 | +/* Merge `stats --no-stream --format {{.ID}}|{{.CPUPerc}}|{{.MemUsage}}`. */ | |
| 391 | +static void merge_stats(const char *text) | |
| 392 | +{ | |
| 393 | + const char *p = text; | |
| 394 | + while (*p) { | |
| 395 | + char line[600]; | |
| 396 | + size_t i = 0; | |
| 397 | + char *fields[3]; | |
| 398 | + int nf, k; | |
| 399 | + | |
| 400 | + while (*p && *p != '\n' && i + 1 < sizeof(line)) line[i++] = *p++; | |
| 401 | + line[i] = '\0'; | |
| 402 | + while (*p == '\n' || *p == '\r') p++; | |
| 403 | + if (i == 0) continue; | |
| 404 | + | |
| 405 | + nf = split_pipe(line, fields, 3); | |
| 406 | + if (nf < 3) continue; | |
| 407 | + | |
| 408 | + for (k = 0; k < g_container_count; k++) { | |
| 409 | + if (strncmp(g_containers[k].id, fields[0], strlen(fields[0])) == 0 || | |
| 410 | + strcmp(g_containers[k].id, fields[0]) == 0) { | |
| 411 | + copy_field(g_containers[k].cpu, sizeof(g_containers[k].cpu), fields[1]); | |
| 412 | + copy_field(g_containers[k].mem, sizeof(g_containers[k].mem), fields[2]); | |
| 413 | + break; | |
| 414 | + } | |
| 415 | + } | |
| 416 | + } | |
| 417 | +} | |
| 418 | + | |
| 419 | +static int container_is(const container_t *c, const char *state) | |
| 420 | +{ | |
| 421 | + return strcmp(c->state, state) == 0; | |
| 422 | +} | |
| 423 | + | |
| 424 | +/* ------------------------------------------------------------------ */ | |
| 425 | +/* Modes */ | |
| 426 | +/* ------------------------------------------------------------------ */ | |
| 427 | + | |
| 428 | +static int mode_meta(void) | |
| 429 | +{ | |
| 430 | + puts("{\"name\":\"docker\",\"desc\":\"Containers\"}"); | |
| 431 | + return 0; | |
| 432 | +} | |
| 433 | + | |
| 434 | +static void json_header(void) | |
| 435 | +{ | |
| 436 | + /* Deliberately no Content-Length — the server owns framing. */ | |
| 437 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 438 | + "Cache-Control: no-store\r\n" | |
| 439 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 440 | +} | |
| 441 | + | |
| 442 | +static void json_header_status(const char *status_line) | |
| 443 | +{ | |
| 444 | + fputs("Status: ", stdout); | |
| 445 | + fputs(status_line, stdout); | |
| 446 | + fputs("\r\n", stdout); | |
| 447 | + json_header(); | |
| 448 | +} | |
| 449 | + | |
| 450 | +/* Emit the runtime block (shared by info + list). */ | |
| 451 | +static void emit_runtime_block(const char *bin, const char *label, int available) | |
| 452 | +{ | |
| 453 | + fputs("\"runtime\":{", stdout); | |
| 454 | + fputs("\"available\":", stdout); | |
| 455 | + fputs(available ? "true" : "false", stdout); | |
| 456 | + fputs(",\"bin\":", stdout); json_str(available ? bin : ""); | |
| 457 | + fputs(",\"label\":", stdout); json_str(available ? label : ""); | |
| 458 | + fputs("}", stdout); | |
| 459 | +} | |
| 460 | + | |
| 461 | +static int mode_json(const char *qs, const char *body, int is_post) | |
| 462 | +{ | |
| 463 | + char action[64]; | |
| 464 | + char cid[192]; | |
| 465 | + char op[32]; | |
| 466 | + char format[32]; | |
| 467 | + | |
| 468 | + char bin[512], label[64]; | |
| 469 | + int available; | |
| 470 | + | |
| 471 | + action[0] = cid[0] = op[0] = format[0] = '\0'; | |
| 472 | + get_query_val(qs, "action", action, sizeof(action)); | |
| 473 | + get_query_val(qs, "cid", cid, sizeof(cid)); | |
| 474 | + get_query_val(qs, "op", op, sizeof(op)); | |
| 475 | + get_query_val(qs, "format", format, sizeof(format)); | |
| 476 | + | |
| 477 | + /* fall back to POST body parameters when the query is empty */ | |
| 478 | + if (body && *body) { | |
| 479 | + if (!action[0]) get_query_val(body, "action", action, sizeof(action)); | |
| 480 | + if (!cid[0]) get_query_val(body, "cid", cid, sizeof(cid)); | |
| 481 | + if (!op[0]) get_query_val(body, "op", op, sizeof(op)); | |
| 482 | + if (!format[0]) get_query_val(body, "format", format, sizeof(format)); | |
| 483 | + } | |
| 484 | + | |
| 485 | + available = detect_runtime(bin, sizeof(bin), label, sizeof(label)); | |
| 486 | + | |
| 487 | + /* ---- control (POST only) ---- */ | |
| 488 | + if (strcmp(action, "control") == 0) { | |
| 489 | + int code = 0; | |
| 490 | + char *out; | |
| 491 | + | |
| 492 | + if (!is_post) { | |
| 493 | + json_header_status("405 Method Not Allowed"); | |
| 494 | + fputs("{\"ok\":false,\"error\":\"control_requires_post\"," | |
| 495 | + "\"hint\":\"POST ?action=control&op=start|stop|restart&cid=<id>\"}\n", stdout); | |
| 496 | + return 0; | |
| 497 | + } | |
| 498 | + if (!available) { | |
| 499 | + json_header_status("503 Service Unavailable"); | |
| 500 | + fputs("{\"ok\":false,\"error\":\"runtime_available\",\"runtime\":{\"available\":false}," | |
| 501 | + "\"message\":\"Neither docker nor podman was found on this node\"}\n", stdout); | |
| 502 | + return 0; | |
| 503 | + } | |
| 504 | + if (!valid_op(op)) { | |
| 505 | + json_header_status("400 Bad Request"); | |
| 506 | + fputs("{\"ok\":false,\"error\":\"invalid_op\"," | |
| 507 | + "\"supported\":[\"start\",\"stop\",\"restart\"]}\n", stdout); | |
| 508 | + return 0; | |
| 509 | + } | |
| 510 | + if (!valid_cid(cid)) { | |
| 511 | + json_header_status("400 Bad Request"); | |
| 512 | + fputs("{\"ok\":false,\"error\":\"invalid_cid\"," | |
| 513 | + "\"message\":\"cid must match [A-Za-z0-9_.-]{1,128} and may not start with - or .\"}\n", | |
| 514 | + stdout); | |
| 515 | + return 0; | |
| 516 | + } | |
| 517 | + { | |
| 518 | + char cmd[1024]; | |
| 519 | + snprintf(cmd, sizeof(cmd), "'%s' %s %s 2>&1", bin, op, cid); | |
| 520 | + out = run_capture(cmd, &code); | |
| 521 | + } | |
| 522 | + { | |
| 523 | + char ts[64]; | |
| 524 | + utc_now(ts, sizeof(ts)); | |
| 525 | + if (code != 0) json_header_status("409 Conflict"); | |
| 526 | + else json_header(); | |
| 527 | + fputs("{\"ok\":", stdout); | |
| 528 | + fputs(code == 0 ? "true" : "false", stdout); | |
| 529 | + fputs(",\"action\":\"control\",\"op\":", stdout); json_str(op); | |
| 530 | + fputs(",\"cid\":", stdout); json_str(cid); | |
| 531 | + printf(",\"exit_code\":%d", code); | |
| 532 | + fputs(",\"output\":", stdout); json_str(out ? out : ""); | |
| 533 | + fputs(",\"utc\":", stdout); json_str(ts); | |
| 534 | + fputs("}\n", stdout); | |
| 535 | + } | |
| 536 | + free(out); | |
| 537 | + return 0; | |
| 538 | + } | |
| 539 | + | |
| 540 | + /* ---- logs ---- */ | |
| 541 | + if (strcmp(action, "logs") == 0) { | |
| 542 | + if (!valid_cid(cid)) { | |
| 543 | + json_header_status("400 Bad Request"); | |
| 544 | + fputs("{\"ok\":false,\"error\":\"invalid_cid\",\"cid\":", stdout); | |
| 545 | + json_str(cid); | |
| 546 | + fputs("}\n", stdout); | |
| 547 | + return 0; | |
| 548 | + } | |
| 549 | + if (!available) { | |
| 550 | + json_header_status("503 Service Unavailable"); | |
| 551 | + fputs("{\"ok\":false,\"error\":\"runtime_available\",\"runtime\":{\"available\":false}," | |
| 552 | + "\"message\":\"Neither docker nor podman was found on this node\"}\n", stdout); | |
| 553 | + return 0; | |
| 554 | + } | |
| 555 | + { | |
| 556 | + char cmd[1024]; | |
| 557 | + char *out; | |
| 558 | + int code = 0; | |
| 559 | + const char *p; | |
| 560 | + | |
| 561 | + snprintf(cmd, sizeof(cmd), "'%s' logs --tail %d %s 2>&1", bin, LOG_TAIL, cid); | |
| 562 | + out = run_capture(cmd, &code); | |
| 563 | + | |
| 564 | + if (code != 0) json_header_status("409 Conflict"); | |
| 565 | + else json_header(); | |
| 566 | + fputs("{\"ok\":", stdout); | |
| 567 | + fputs(code == 0 ? "true" : "false", stdout); | |
| 568 | + fputs(",\"action\":\"logs\",\"cid\":", stdout); json_str(cid); | |
| 569 | + printf(",\"tail\":%d,\"exit_code\":%d", LOG_TAIL, code); | |
| 570 | + fputs(",\"lines\":[", stdout); | |
| 571 | + if (out) { | |
| 572 | + int first = 1; | |
| 573 | + p = out; | |
| 574 | + while (*p) { | |
| 575 | + char line[2048]; | |
| 576 | + size_t i = 0; | |
| 577 | + while (*p && *p != '\n' && i + 1 < sizeof(line)) line[i++] = *p++; | |
| 578 | + line[i] = '\0'; | |
| 579 | + while (*p == '\n' || *p == '\r') p++; | |
| 580 | + if (!first) fputs(",", stdout); | |
| 581 | + first = 0; | |
| 582 | + json_str(line); | |
| 583 | + } | |
| 584 | + } | |
| 585 | + fputs("],\"text\":", stdout); json_str(out ? out : ""); | |
| 586 | + fputs("}\n", stdout); | |
| 587 | + free(out); | |
| 588 | + } | |
| 589 | + return 0; | |
| 590 | + } | |
| 591 | + | |
| 592 | + /* ---- info / list / unknown ---- */ | |
| 593 | + if (action[0] && strcmp(action, "info") != 0 && strcmp(action, "list") != 0) { | |
| 594 | + json_header_status("400 Bad Request"); | |
| 595 | + fputs("{\"ok\":false,\"error\":\"unknown_action\",\"action\":", stdout); | |
| 596 | + json_str(action); | |
| 597 | + fputs(",\"supported\":[\"list\",\"info\",\"logs\",\"control\"]}\n", stdout); | |
| 598 | + return 0; | |
| 599 | + } | |
| 600 | + | |
| 601 | + if (strcmp(action, "info") == 0 && strcmp(format, "list") == 0) { | |
| 602 | + /* not meaningful; treat as list */ | |
| 603 | + } | |
| 604 | + | |
| 605 | + if (strcmp(action, "info") == 0) { | |
| 606 | + char ts[64]; | |
| 607 | + utc_now(ts, sizeof(ts)); | |
| 608 | + json_header(); | |
| 609 | + fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," | |
| 610 | + "\"slug\":\"" PLUGIN_SLUG "\",\"version\":\"" PLUGIN_VER "\",", stdout); | |
| 611 | + emit_runtime_block(bin, label, available); | |
| 612 | + printf(",\"pid\":%ld", node_pid()); | |
| 613 | + fputs(",\"utc\":", stdout); json_str(ts); | |
| 614 | + fputs(",\"supported\":[\"list\",\"info\",\"logs\",\"control\"]," | |
| 615 | + "\"control\":{\"method\":\"POST\",\"ops\":[\"start\",\"stop\",\"restart\"]}}\n", stdout); | |
| 616 | + return 0; | |
| 617 | + } | |
| 618 | + | |
| 619 | + /* list */ | |
| 620 | + { | |
| 621 | + char *psout = NULL; | |
| 622 | + char *statsout = NULL; | |
| 623 | + int pscode = 0, statscode = 0; | |
| 624 | + char ts[64]; | |
| 625 | + int total = 0, running = 0, exited = 0, paused = 0, other = 0; | |
| 626 | + int i; | |
| 627 | + | |
| 628 | + if (available) { | |
| 629 | + char cmd[1024]; | |
| 630 | + snprintf(cmd, sizeof(cmd), | |
| 631 | + "'%s' ps -a --format '{{.ID}}|{{.Names}}|{{.Image}}|{{.State}}|{{.Status}}|{{.Ports}}' 2>&1", | |
| 632 | + bin); | |
| 633 | + psout = run_capture(cmd, &pscode); | |
| 634 | + if (psout && pscode == 0) parse_ps(psout); | |
| 635 | + | |
| 636 | + snprintf(cmd, sizeof(cmd), | |
| 637 | + "'%s' stats --no-stream --format '{{.ID}}|{{.CPUPerc}}|{{.MemUsage}}' 2>&1", | |
| 638 | + bin); | |
| 639 | + statsout = run_capture(cmd, &statscode); | |
| 640 | + if (statsout && statscode == 0 && g_container_count > 0) merge_stats(statsout); | |
| 641 | + } | |
| 642 | + | |
| 643 | + for (i = 0; i < g_container_count; i++) { | |
| 644 | + total++; | |
| 645 | + if (container_is(&g_containers[i], "running")) running++; | |
| 646 | + else if (container_is(&g_containers[i], "exited")) exited++; | |
| 647 | + else if (container_is(&g_containers[i], "paused")) paused++; | |
| 648 | + else other++; | |
| 649 | + } | |
| 650 | + | |
| 651 | + utc_now(ts, sizeof(ts)); | |
| 652 | + json_header(); | |
| 653 | + fputs("{\"ok\":true,\"action\":\"list\",\"plugin\":\"" PLUGIN_ID "\"," | |
| 654 | + "\"slug\":\"" PLUGIN_SLUG "\",\"version\":\"" PLUGIN_VER "\",", stdout); | |
| 655 | + emit_runtime_block(bin, label, available); | |
| 656 | + if (!available) { | |
| 657 | + fputs(",\"message\":\"Neither docker nor podman was found on this node. " | |
| 658 | + "Install a container runtime, or set DOCKER_BIN to an explicit binary path.\"", stdout); | |
| 659 | + } else if (psout && pscode != 0) { | |
| 660 | + fputs(",\"daemon_available\":false,\"error\":", stdout); | |
| 661 | + json_str(psout); | |
| 662 | + } else { | |
| 663 | + fputs(",\"daemon_available\":true", stdout); | |
| 664 | + } | |
| 665 | + fputs(",\"utc\":", stdout); json_str(ts); | |
| 666 | + printf(",\"count\":%d,\"summary\":{\"total\":%d,\"running\":%d,\"exited\":%d," | |
| 667 | + "\"paused\":%d,\"other\":%d}", g_container_count, total, running, exited, paused, other); | |
| 668 | + fputs(",\"containers\":[", stdout); | |
| 669 | + for (i = 0; i < g_container_count; i++) { | |
| 670 | + container_t *c = &g_containers[i]; | |
| 671 | + if (i) fputs(",", stdout); | |
| 672 | + fputs("{", stdout); | |
| 673 | + fputs("\"id\":", stdout); json_str(c->id); | |
| 674 | + fputs(",\"short\":", stdout); json_str(c->id[0] ? c->id : ""); | |
| 675 | + fputs(",\"name\":", stdout); json_str(c->name); | |
| 676 | + fputs(",\"image\":", stdout); json_str(c->image); | |
| 677 | + fputs(",\"state\":", stdout); json_str(c->state); | |
| 678 | + fputs(",\"status\":", stdout);json_str(c->status); | |
| 679 | + fputs(",\"ports\":", stdout); json_str(c->ports); | |
| 680 | + fputs(",\"cpu\":", stdout); json_str(c->cpu); | |
| 681 | + fputs(",\"mem\":", stdout); json_str(c->mem); | |
| 682 | + fputs("}", stdout); | |
| 683 | + } | |
| 684 | + fputs("]}\n", stdout); | |
| 685 | + | |
| 686 | + free(psout); | |
| 687 | + free(statsout); | |
| 688 | + } | |
| 689 | + return 0; | |
| 690 | +} | |
| 691 | + | |
| 692 | +/* ------------------------------------------------------------------ */ | |
| 693 | +/* HTML UI */ | |
| 694 | +/* ------------------------------------------------------------------ */ | |
| 695 | + | |
| 696 | +static int mode_html(int embed) | |
| 697 | +{ | |
| 698 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 699 | + "Cache-Control: no-store\r\n" | |
| 700 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 701 | + | |
| 702 | + fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" | |
| 703 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | |
| 704 | + "<title>docker</title><style>", stdout); | |
| 705 | + | |
| 706 | + fputs( | |
| 707 | +":root{color-scheme:dark light;" | |
| 708 | + "--bg:#0d0d10;--surface:#16161a;--surface2:#1e1e24;--text:#f5f5f7;" | |
| 709 | + "--muted:#8e8e96;--line:rgba(255,255,255,.11);--accent:#0a84ff;" | |
| 710 | + "--accent2:#30d158;--warn:#ffd60a;--danger:#ff453a;" | |
| 711 | + "--mono:ui-monospace,SFMono-Regular,Menlo,monospace}" | |
| 712 | +"html[data-theme=light]{--bg:#f4f4f7;--surface:#ffffff;--surface2:#f0f0f4;" | |
| 713 | + "--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}" | |
| 714 | +"*{box-sizing:border-box}" | |
| 715 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--text);" | |
| 716 | + "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;" | |
| 717 | + "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}" | |
| 718 | +".wrap{max-width:1080px;margin:0 auto}" | |
| 719 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | |
| 720 | +".title{font-size:20px;font-weight:700;margin:0}" | |
| 721 | +".pill{font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;" | |
| 722 | + "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}" | |
| 723 | +".pill.on{color:var(--accent2);border-color:rgba(48,209,88,.4)}" | |
| 724 | +".pill.off{color:var(--danger);border-color:rgba(255,69,58,.4)}" | |
| 725 | +".spacer{flex:1}" | |
| 726 | +".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | |
| 727 | + "padding:16px;margin-bottom:14px}" | |
| 728 | +".card h2{margin:0 0 10px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;" | |
| 729 | + "color:var(--muted);font-weight:600}" | |
| 730 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px}" | |
| 731 | +".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;padding:10px 12px}" | |
| 732 | +".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" | |
| 733 | +".kpi .v{font-size:20px;font-weight:700;font-family:var(--mono);margin-top:2px}" | |
| 734 | +".kpi .v.run{color:var(--accent2)}.kpi .v.exit{color:var(--muted)}" | |
| 735 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;" | |
| 736 | + "padding:7px 14px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | |
| 737 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | |
| 738 | +"button.danger{background:var(--danger)}" | |
| 739 | +"button.sm{padding:4px 10px;font-size:12px}" | |
| 740 | +"button:active{transform:scale(.98)}" | |
| 741 | +"button:disabled{opacity:.45;cursor:not-allowed}" | |
| 742 | +"input,select{background:var(--surface2);border:1px solid var(--line);" | |
| 743 | + "border-radius:10px;padding:8px 12px;color:var(--text);font-size:13px;" | |
| 744 | + "font-family:inherit}" | |
| 745 | +"input{flex:1;min-width:140px;font-family:var(--mono)}" | |
| 746 | +"input:focus,select:focus{outline:2px solid var(--accent);outline-offset:-1px}" | |
| 747 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | |
| 748 | +"table{width:100%;border-collapse:collapse;font-size:13px;margin-top:10px}" | |
| 749 | +"th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;" | |
| 750 | + "color:var(--muted);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);" | |
| 751 | + "white-space:nowrap}" | |
| 752 | +"td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:middle}" | |
| 753 | +"td.mono{font-family:var(--mono);font-size:12px;word-break:break-all}" | |
| 754 | +"tr:last-child td{border-bottom:0}" | |
| 755 | +".state{font-size:11px;font-weight:700;padding:2px 8px;border-radius:999px;" | |
| 756 | + "text-transform:uppercase;letter-spacing:.04em;display:inline-block}" | |
| 757 | +".state.running{background:rgba(48,209,88,.16);color:var(--accent2)}" | |
| 758 | +".state.exited{background:rgba(255,255,255,.08);color:var(--muted)}" | |
| 759 | +".state.paused{background:rgba(255,214,10,.16);color:var(--warn)}" | |
| 760 | +".state.created,.state.restarting,.state.dead{background:rgba(255,69,58,.16);color:var(--danger)}" | |
| 761 | +".acts{display:flex;gap:6px;flex-wrap:wrap}" | |
| 762 | +".tblwrap{overflow-x:auto}" | |
| 763 | +"pre{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | |
| 764 | + "padding:12px;overflow:auto;font-family:var(--mono);font-size:12px;margin:0;" | |
| 765 | + "max-height:380px;white-space:pre-wrap;word-break:break-word}" | |
| 766 | +".muted{color:var(--muted)}" | |
| 767 | +".empty{padding:22px 8px;text-align:center;color:var(--muted)}" | |
| 768 | +".hide{display:none}" | |
| 769 | +"@media(max-width:640px){body{padding:10px}.card{padding:12px}" | |
| 770 | + "th:nth-child(3),td:nth-child(3),th:nth-child(5),td:nth-child(5){display:none}}" | |
| 771 | +"</style></head><body><div class='wrap'>", stdout); | |
| 772 | + | |
| 773 | + if (!embed) | |
| 774 | + fputs("<div class='top'><a href='/' style='color:var(--accent);text-decoration:none;" | |
| 775 | + "font-weight:600'>← Back to Bot</a></div>", stdout); | |
| 776 | + | |
| 777 | + fputs("<div class='top'><h1 class='title'>docker</h1>" | |
| 778 | + "<span class='pill'>" PLUGIN_VER "</span>" | |
| 779 | + "<span class='pill' id='badge'>connecting</span>" | |
| 780 | + "<span class='spacer'></span>" | |
| 781 | + "<button class='ghost' id='themeBtn' type='button'>Theme</button>" | |
| 782 | + "<button class='ghost' id='reloadBtn' type='button'>Refresh</button></div>", stdout); | |
| 783 | + | |
| 784 | + /* KPIs */ | |
| 785 | + fputs("<div class='card'><h2>Containers</h2><div class='grid'>" | |
| 786 | + "<div class='kpi'><div class='k'>total</div><div class='v' id='k-total'>—</div></div>" | |
| 787 | + "<div class='kpi'><div class='k'>running</div><div class='v run' id='k-run'>—</div></div>" | |
| 788 | + "<div class='kpi'><div class='k'>exited</div><div class='v exit' id='k-exit'>—</div></div>" | |
| 789 | + "<div class='kpi'><div class='k'>paused</div><div class='v' id='k-pause'>—</div></div>" | |
| 790 | + "<div class='kpi'><div class='k'>runtime</div><div class='v' id='k-rt'>—</div></div>" | |
| 791 | + "</div>" | |
| 792 | + "<div class='row' style='margin-top:12px'>" | |
| 793 | + "<input id='q' type='text' placeholder='search name, image, id, port'>" | |
| 794 | + "<select id='state'><option value=''>all states</option>" | |
| 795 | + "<option value='running'>running</option><option value='exited'>exited</option>" | |
| 796 | + "<option value='paused'>paused</option><option value='created'>created</option>" | |
| 797 | + "</select>" | |
| 798 | + "<button id='refreshBtn' type='button'>Apply</button></div>" | |
| 799 | + "<div id='note' class='muted' style='margin-top:10px'></div>" | |
| 800 | + "<div class='tblwrap'><table><thead><tr>" | |
| 801 | + "<th>ID</th><th>Name</th><th>Image</th><th>State</th><th>CPU</th><th>Mem</th><th>Actions</th>" | |
| 802 | + "</tr></thead><tbody id='rows'></tbody></table></div>" | |
| 803 | + "<div id='empty' class='empty hide'>No containers to show.</div>" | |
| 804 | + "</div>", stdout); | |
| 805 | + | |
| 806 | + /* log viewer */ | |
| 807 | + fputs("<div class='card hide' id='logCard'><h2 id='logTitle'>Logs</h2>" | |
| 808 | + "<pre id='logBody'>loading…</pre>" | |
| 809 | + "<div class='row' style='margin-top:10px'>" | |
| 810 | + "<button class='ghost sm' id='logReload' type='button'>Reload</button>" | |
| 811 | + "<button class='ghost sm' id='logClose' type='button'>Close</button></div></div>", stdout); | |
| 812 | + | |
| 813 | + /* footer */ | |
| 814 | + fputs("<div class='card'><h2>About this plugin</h2>" | |
| 815 | + "<p class='muted' style='margin:0 0 8px'>Local node only. Reads " | |
| 816 | + "<code>docker</code> or <code>podman</code> on this machine and makes zero " | |
| 817 | + "outbound network requests. Source is MIT licensed.</p>" | |
| 818 | + "<p class='muted' style='margin:0'><code>list</code>, <code>logs</code> and " | |
| 819 | + "<code>control</code> are the only supported actions; container identifiers are " | |
| 820 | + "validated before they ever reach a command line.</p></div>", stdout); | |
| 821 | + | |
| 822 | + /* script */ | |
| 823 | + fputs( | |
| 824 | +"<script>\n" | |
| 825 | +"(function(){\n" | |
| 826 | +" var q = new URLSearchParams(location.search);\n" | |
| 827 | +" var HUB = q.get('plugin') || '';\n" | |
| 828 | +" var node = q.get('node') || '';\n" | |
| 829 | +" var sid = q.get('id') || '';\n" | |
| 830 | +" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | |
| 831 | +" localStorage.getItem('bot_active_pwd') || '';\n" | |
| 832 | +"\n" | |
| 833 | +" function base(){ return HUB ? '/plugins?plugin=' + HUB : '/plugin_docker'; }\n" | |
| 834 | +" function withCtx(u){\n" | |
| 835 | +" if (node) u += '&node=' + encodeURIComponent(node);\n" | |
| 836 | +" if (sid) u += '&id=' + encodeURIComponent(sid);\n" | |
| 837 | +" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" | |
| 838 | +" return u;\n" | |
| 839 | +" }\n" | |
| 840 | +" function headers(extra){\n" | |
| 841 | +" var h = extra || {};\n" | |
| 842 | +" if (pwd) h['X-Bot-Password'] = pwd;\n" | |
| 843 | +" return h;\n" | |
| 844 | +" }\n" | |
| 845 | +" function get(action, extra){\n" | |
| 846 | +" var u = withCtx(base() + '?action=' + encodeURIComponent(action) + (extra || ''));\n" | |
| 847 | +" return fetch(u, { headers: headers() }).then(function(r){ return r.json(); });\n" | |
| 848 | +" }\n" | |
| 849 | +" function post(action, form){\n" | |
| 850 | +" var u = withCtx(base() + '?action=' + encodeURIComponent(action));\n" | |
| 851 | +" return fetch(u, { method:'POST',\n" | |
| 852 | +" headers: headers({'Content-Type':'application/x-www-form-urlencoded'}),\n" | |
| 853 | +" body: form }).then(function(r){ return r.json(); });\n" | |
| 854 | +" }\n" | |
| 855 | +" function $(id){ return document.getElementById(id); }\n" | |
| 856 | +" function txt(id, v){ var e = $(id); if (e) e.textContent = (v === undefined || v === null || v === '') ? '\\u2014' : String(v); }\n" | |
| 857 | +" function el(tag, cls, text){\n" | |
| 858 | +" var e = document.createElement(tag);\n" | |
| 859 | +" if (cls) e.className = cls;\n" | |
| 860 | +" if (text !== undefined && text !== null) e.textContent = String(text);\n" | |
| 861 | +" return e;\n" | |
| 862 | +" }\n" | |
| 863 | +"\n" | |
| 864 | +" var DATA = { containers: [], summary: {} };\n" | |
| 865 | +" var LOG_CID = '', LOG_NAME = '';\n" | |
| 866 | +"\n" | |
| 867 | +" function theme(t){\n" | |
| 868 | +" if (t) { document.documentElement.setAttribute('data-theme', t); localStorage.setItem('bot_theme', t); }\n" | |
| 869 | +" }\n" | |
| 870 | +" theme(localStorage.getItem('bot_theme') || 'dark');\n" | |
| 871 | +" $('themeBtn').addEventListener('click', function(){\n" | |
| 872 | +" theme(document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light');\n" | |
| 873 | +" });\n" | |
| 874 | +"\n" | |
| 875 | +" function badge(ok, text){\n" | |
| 876 | +" var b = $('badge');\n" | |
| 877 | +" b.textContent = text;\n" | |
| 878 | +" b.className = 'pill ' + (ok ? 'on' : 'off');\n" | |
| 879 | +" }\n" | |
| 880 | +"\n" | |
| 881 | +" function matches(c){\n" | |
| 882 | +" var s = ($('state').value || '').toLowerCase();\n" | |
| 883 | +" if (s && (c.state || '').toLowerCase() !== s) return false;\n" | |
| 884 | +" var k = ($('q').value || '').trim().toLowerCase();\n" | |
| 885 | +" if (!k) return true;\n" | |
| 886 | +" var hay = ((c.name||'') + ' ' + (c.image||'') + ' ' + (c.id||'') + ' ' + (c.ports||'')).toLowerCase();\n" | |
| 887 | +" return hay.indexOf(k) >= 0;\n" | |
| 888 | +" }\n" | |
| 889 | +"\n" | |
| 890 | +" function act(c, op){\n" | |
| 891 | +" var label = op + ' ' + (c.name || c.id);\n" | |
| 892 | +" if (op !== 'start' && !window.confirm(label + '?')) return;\n" | |
| 893 | +" post('control', 'op=' + encodeURIComponent(op) + '&cid=' + encodeURIComponent(c.id))\n" | |
| 894 | +" .then(function(d){\n" | |
| 895 | +" if (!d.ok) { $('note').textContent = (d.error || 'failed') + (d.output ? ': ' + d.output : ''); }\n" | |
| 896 | +" else { $('note').textContent = op + ' ' + (c.name || c.id) + ' ok'; }\n" | |
| 897 | +" refresh();\n" | |
| 898 | +" })\n" | |
| 899 | +" .catch(function(e){ $('note').textContent = 'request failed: ' + e; });\n" | |
| 900 | +" }\n" | |
| 901 | +"\n" | |
| 902 | +" function openLogs(c){\n" | |
| 903 | +" LOG_CID = c.id; LOG_NAME = c.name || c.id;\n" | |
| 904 | +" $('logCard').classList.remove('hide');\n" | |
| 905 | +" $('logTitle').textContent = 'Logs \\u2014 ' + LOG_NAME + ' (last 100 lines)';\n" | |
| 906 | +" $('logBody').textContent = 'loading\\u2026';\n" | |
| 907 | +" get('logs', '&cid=' + encodeURIComponent(c.id)).then(function(d){\n" | |
| 908 | +" $('logBody').textContent = d.ok ? (d.text || '(empty)') : ('error: ' + (d.error || 'unknown'));\n" | |
| 909 | +" }).catch(function(e){ $('logBody').textContent = 'request failed: ' + e; });\n" | |
| 910 | +" }\n" | |
| 911 | +"\n" | |
| 912 | +" function render(){\n" | |
| 913 | +" var tb = $('rows');\n" | |
| 914 | +" while (tb.firstChild) tb.removeChild(tb.firstChild);\n" | |
| 915 | +" var shown = 0;\n" | |
| 916 | +" (DATA.containers || []).forEach(function(c){\n" | |
| 917 | +" if (!matches(c)) return;\n" | |
| 918 | +" shown++;\n" | |
| 919 | +" var tr = el('tr');\n" | |
| 920 | +" tr.appendChild(el('td', 'mono', (c.id || '').slice(0, 12)));\n" | |
| 921 | +" tr.appendChild(el('td', '', c.name || ''));\n" | |
| 922 | +" tr.appendChild(el('td', 'mono', c.image || ''));\n" | |
| 923 | +" var tdState = el('td');\n" | |
| 924 | +" tdState.appendChild(el('span', 'state ' + (c.state || '').toLowerCase(), c.state || ''));\n" | |
| 925 | +" tr.appendChild(tdState);\n" | |
| 926 | +" tr.appendChild(el('td', 'mono', c.cpu || '\\u2014'));\n" | |
| 927 | +" tr.appendChild(el('td', 'mono', c.mem || '\\u2014'));\n" | |
| 928 | +" var tdAct = el('td');\n" | |
| 929 | +" var box = el('div', 'acts');\n" | |
| 930 | +" function btn(op, cls){ var b = el('button', 'sm ' + cls, op);\n" | |
| 931 | +" b.type = 'button'; b.addEventListener('click', function(){ act(c, op); }); return b; }\n" | |
| 932 | +" function logBtn(){ var b = el('button', 'sm ghost', 'logs');\n" | |
| 933 | +" b.type = 'button'; b.addEventListener('click', function(){ openLogs(c); }); return b; }\n" | |
| 934 | +" var running = (c.state || '').toLowerCase() === 'running';\n" | |
| 935 | +" if (running) {\n" | |
| 936 | +" box.appendChild(btn('stop', 'danger'));\n" | |
| 937 | +" box.appendChild(btn('restart', 'ghost'));\n" | |
| 938 | +" } else {\n" | |
| 939 | +" box.appendChild(btn('start', ''));\n" | |
| 940 | +" }\n" | |
| 941 | +" box.appendChild(logBtn());\n" | |
| 942 | +" tdAct.appendChild(box);\n" | |
| 943 | +" tr.appendChild(tdAct);\n" | |
| 944 | +" tb.appendChild(tr);\n" | |
| 945 | +" });\n" | |
| 946 | +" $('empty').classList.toggle('hide', shown !== 0);\n" | |
| 947 | +" }\n" | |
| 948 | +"\n" | |
| 949 | +" function refresh(){\n" | |
| 950 | +" get('list').then(function(d){\n" | |
| 951 | +" DATA = d;\n" | |
| 952 | +" var s = d.summary || {};\n" | |
| 953 | +" txt('k-total', s.total);\n" | |
| 954 | +" txt('k-run', s.running);\n" | |
| 955 | +" txt('k-exit', s.exited);\n" | |
| 956 | +" txt('k-pause', s.paused);\n" | |
| 957 | +" var rt = d.runtime || {};\n" | |
| 958 | +" txt('k-rt', rt.available ? (rt.label || 'yes') : 'none');\n" | |
| 959 | +" if (!rt.available) {\n" | |
| 960 | +" badge(false, 'no runtime');\n" | |
| 961 | +" $('note').textContent = d.message || 'neither docker nor podman found on this node';\n" | |
| 962 | +" } else if (d.daemon_available === false) {\n" | |
| 963 | +" badge(false, 'daemon down');\n" | |
| 964 | +" $('note').textContent = d.error || 'runtime daemon is not reachable';\n" | |
| 965 | +" } else {\n" | |
| 966 | +" badge(true, rt.label || 'ready');\n" | |
| 967 | +" $('note').textContent = (s.total || 0) + ' container(s) on this node';\n" | |
| 968 | +" }\n" | |
| 969 | +" render();\n" | |
| 970 | +" }).catch(function(e){\n" | |
| 971 | +" badge(false, 'error');\n" | |
| 972 | +" $('note').textContent = 'request failed: ' + e;\n" | |
| 973 | +" });\n" | |
| 974 | +" }\n" | |
| 975 | +"\n" | |
| 976 | +" $('refreshBtn').addEventListener('click', refresh);\n" | |
| 977 | +" $('reloadBtn').addEventListener('click', refresh);\n" | |
| 978 | +" $('q').addEventListener('input', render);\n" | |
| 979 | +" $('q').addEventListener('keydown', function(e){ if (e.key === 'Enter') refresh(); });\n" | |
| 980 | +" $('state').addEventListener('change', render);\n" | |
| 981 | +" $('logClose').addEventListener('click', function(){ $('logCard').classList.add('hide'); });\n" | |
| 982 | +" $('logReload').addEventListener('click', function(){\n" | |
| 983 | +" if (LOG_CID) get('logs', '&cid=' + encodeURIComponent(LOG_CID)).then(function(d){\n" | |
| 984 | +" $('logBody').textContent = d.ok ? (d.text || '(empty)') : ('error: ' + (d.error || 'unknown'));\n" | |
| 985 | +" });\n" | |
| 986 | +" });\n" | |
| 987 | +"\n" | |
| 988 | +" refresh();\n" | |
| 989 | +"})();\n" | |
| 990 | +"</script></body></html>\n", stdout); | |
| 991 | + return 0; | |
| 992 | +} | |
| 993 | + | |
| 994 | +/* ------------------------------------------------------------------ */ | |
| 995 | +/* POST body */ | |
| 996 | +/* ------------------------------------------------------------------ */ | |
| 997 | + | |
| 998 | +static char *read_post_body(void) | |
| 999 | +{ | |
| 1000 | + const char *cl = getenv("CONTENT_LENGTH"); | |
| 1001 | + long want; | |
| 1002 | + size_t got = 0; | |
| 1003 | + char *buf; | |
| 1004 | + | |
| 1005 | + if (!cl || !*cl) return NULL; | |
| 1006 | + want = strtol(cl, NULL, 10); | |
| 1007 | + if (want <= 0) return NULL; | |
| 1008 | + if (want > 8192) want = 8192; | |
| 1009 | + | |
| 1010 | + buf = (char *)malloc((size_t)want + 1); | |
| 1011 | + if (!buf) return NULL; | |
| 1012 | + while (got < (size_t)want) { | |
| 1013 | + size_t n = fread(buf + got, 1, (size_t)want - got, stdin); | |
| 1014 | + if (n == 0) break; | |
| 1015 | + got += n; | |
| 1016 | + } | |
| 1017 | + buf[got] = '\0'; | |
| 1018 | + return buf; | |
| 1019 | +} | |
| 1020 | + | |
| 1021 | +/* ------------------------------------------------------------------ */ | |
| 1022 | +/* main */ | |
| 1023 | +/* ------------------------------------------------------------------ */ | |
| 1024 | + | |
| 1025 | +static int is_post_request(void) | |
| 1026 | +{ | |
| 1027 | + const char *m = getenv("REQUEST_METHOD"); | |
| 1028 | + return m && strcmp(m, "POST") == 0; | |
| 1029 | +} | |
| 1030 | + | |
| 1031 | +int main(int argc, char **argv) | |
| 1032 | +{ | |
| 1033 | + const char *qs; | |
| 1034 | + char *body = NULL; | |
| 1035 | + | |
| 1036 | + if (argc > 1) { | |
| 1037 | + if (strcmp(argv[1], "--meta") == 0) return mode_meta(); | |
| 1038 | + if (strcmp(argv[1], "--version") == 0) { puts(PLUGIN_VER); return 0; } | |
| 1039 | + if (strcmp(argv[1], "--help") == 0) { | |
| 1040 | + puts("plugin_docker " PLUGIN_VER); | |
| 1041 | + puts("usage: plugin_docker [--meta|--version|--help]"); | |
| 1042 | + puts(" QUERY_STRING='action=list|info|logs&cid=<id>' plugin_docker"); | |
| 1043 | + return 0; | |
| 1044 | + } | |
| 1045 | + } | |
| 1046 | + if (getenv("SX_PLUGIN_META")) return mode_meta(); | |
| 1047 | + | |
| 1048 | + qs = getenv("QUERY_STRING"); | |
| 1049 | + if (!qs) qs = ""; | |
| 1050 | + | |
| 1051 | + if (is_post_request()) body = read_post_body(); | |
| 1052 | + | |
| 1053 | + if (strstr(qs, "action=") || strstr(qs, "format=json") || (body && strstr(body, "action="))) { | |
| 1054 | + int rc = mode_json(qs, body, is_post_request()); | |
| 1055 | + free(body); | |
| 1056 | + return rc; | |
| 1057 | + } | |
| 1058 | + | |
| 1059 | + { | |
| 1060 | + char embedv[16]; | |
| 1061 | + free(body); | |
| 1062 | + embedv[0] = '\0'; | |
| 1063 | + if (get_query_val(qs, "embed", embedv, sizeof(embedv))) | |
| 1064 | + return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); | |
| 1065 | + } | |
| 1066 | + return mode_html(0); | |
| 1067 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..5a757f3 | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,290 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh — 60+ offline checks for plugin_docker across all 3 modes. | |
| 3 | +# | |
| 4 | +# Runs against ./plugin_docker (native build) using a mock DOCKER_BIN script, so | |
| 5 | +# nothing here needs a real container runtime. If a musl static build or a | |
| 6 | +# Windows PE (plugin_docker.exe) is present, they are checked too. The whole git | |
| 7 | +# history is finally audited for secrets, PATs and LAN IPs. | |
| 8 | +# | |
| 9 | +# Exit code 0 = everything passed. | |
| 10 | + | |
| 11 | +set -u | |
| 12 | + | |
| 13 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 14 | +cd "$ROOT" || exit 1 | |
| 15 | + | |
| 16 | +BIN=./plugin_docker | |
| 17 | +PASS=0 | |
| 18 | +FAIL=0 | |
| 19 | + | |
| 20 | +if [ -t 1 ]; then | |
| 21 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 22 | +else | |
| 23 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 24 | +fi | |
| 25 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 26 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 27 | + | |
| 28 | +check() { # check <desc> <expected-substring> <actual> | |
| 29 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 30 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | |
| 31 | + fi | |
| 32 | +} | |
| 33 | + | |
| 34 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 35 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 36 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 37 | + fi | |
| 38 | +} | |
| 39 | + | |
| 40 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 41 | + | |
| 42 | +body() { printf '%s' "$1" | sed '1,/^\r$/d'; } | |
| 43 | + | |
| 44 | +# ---------------------------------------------------------------- setup | |
| 45 | +section "build" | |
| 46 | +if [ ! -x "$BIN" ]; then | |
| 47 | + echo " building native binary..." | |
| 48 | + cc -O2 -std=c99 -Wall -Wextra -o "$BIN" src/plugin_docker.c || { echo " build failed"; exit 1; } | |
| 49 | +fi | |
| 50 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | |
| 51 | + | |
| 52 | +# mock runtime | |
| 53 | +MOCKDIR=$(mktemp -d 2>/dev/null || echo /tmp/pd_mock_$$) | |
| 54 | +mkdir -p "$MOCKDIR" | |
| 55 | +MOCK="$MOCKDIR/mockdocker" | |
| 56 | +cat > "$MOCK" <<'MOCKEOF' | |
| 57 | +#!/bin/sh | |
| 58 | +case "$1" in | |
| 59 | + ps) | |
| 60 | + echo "a1b2c3d4e5f6|web|nginx:1.27|running|Up 3 hours|0.0.0.0:8080->80/tcp" | |
| 61 | + echo "b2c3d4e5f6a1|db|postgres:16|running|Up 3 hours|127.0.0.1:5432->5432/tcp" | |
| 62 | + echo "c3d4e5f6a1b2|old-job|alpine:3.20|exited|Exited (0) 2 days ago|" | |
| 63 | + exit 0 ;; | |
| 64 | + stats) | |
| 65 | + echo "a1b2c3d4e5f6|1.25%|12.5MiB / 1GiB" | |
| 66 | + echo "b2c3d4e5f6a1|0.40%|88.1MiB / 1GiB" | |
| 67 | + exit 0 ;; | |
| 68 | + logs) | |
| 69 | + echo "line one" | |
| 70 | + echo 'line two with "quotes" and a <tab>' | |
| 71 | + printf 'line three\n' | |
| 72 | + exit 0 ;; | |
| 73 | + start|stop|restart) | |
| 74 | + exit 0 ;; | |
| 75 | + *) echo "unknown command: $1" >&2; exit 1 ;; | |
| 76 | +esac | |
| 77 | +MOCKEOF | |
| 78 | +chmod +x "$MOCK" | |
| 79 | + | |
| 80 | +# a "no runtime" path: empty DOCKER_BIN, PATH with no docker/podman | |
| 81 | +# (no runtime helper: assignments are inlined at each call site) | |
| 82 | + | |
| 83 | +# ---------------------------------------------------------------- meta mode | |
| 84 | +section "mode 1 --meta" | |
| 85 | +META=$("$BIN" --meta) | |
| 86 | +check "meta emits name docker" '"name":"docker"' "$META" | |
| 87 | +check "meta emits desc Containers" '"desc":"Containers"' "$META" | |
| 88 | +METAENV=$(SX_PLUGIN_META=1 "$BIN") | |
| 89 | +check "SX_PLUGIN_META=1 yields same meta" '"name":"docker"' "$METAENV" | |
| 90 | +LEN=$(printf '%s' "$META" | wc -c | tr -d ' ') | |
| 91 | +[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)" | |
| 92 | +printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | |
| 93 | + && pass "meta is valid JSON" || fail "meta is not valid JSON" | |
| 94 | +DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/') | |
| 95 | +[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})" | |
| 96 | +NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/') | |
| 97 | +[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces" | |
| 98 | +check "--version prints version" '1.0.0' "$("$BIN" --version)" | |
| 99 | +check "--help is available" 'usage:' "$("$BIN" --help)" | |
| 100 | + | |
| 101 | +# ---------------------------------------------------------------- list mode | |
| 102 | +section "mode 2 JSON list (mock runtime)" | |
| 103 | +export DOCKER_BIN="$MOCK" | |
| 104 | +LIST=$(QUERY_STRING='action=list' "$BIN") | |
| 105 | +LBODY=$(body "$LIST") | |
| 106 | +check "list header content-type" 'Content-Type: application/json; charset=utf-8' "$LIST" | |
| 107 | +check_not "list header has no Content-Length" 'Content-Length' "$LIST" | |
| 108 | +check "list ok:true" '"ok":true' "$LBODY" | |
| 109 | +check "list plugin id" '"plugin":"plugin_docker"' "$LBODY" | |
| 110 | +check "list slug docker" '"slug":"docker"' "$LBODY" | |
| 111 | +check "list version" '"version":"1.0.0"' "$LBODY" | |
| 112 | +check "list runtime available" '"available":true' "$LBODY" | |
| 113 | +check "list daemon available" '"daemon_available":true' "$LBODY" | |
| 114 | +check "list count 3" '"count":3' "$LBODY" | |
| 115 | +check "summary total 3" '"total":3' "$LBODY" | |
| 116 | +check "summary running 2" '"running":2' "$LBODY" | |
| 117 | +check "summary exited 1" '"exited":1' "$LBODY" | |
| 118 | +check "container web present" '"name":"web"' "$LBODY" | |
| 119 | +check "container db present" '"name":"db"' "$LBODY" | |
| 120 | +check "container old-job present" '"name":"old-job"' "$LBODY" | |
| 121 | +check "image field present" '"image":"nginx:1.27"' "$LBODY" | |
| 122 | +check "state running present" '"state":"running"' "$LBODY" | |
| 123 | +check "state exited present" '"state":"exited"' "$LBODY" | |
| 124 | +check "ports field present" '0.0.0.0:8080->80/tcp' "$LBODY" | |
| 125 | +check "cpu stat merged" '"cpu":"1.25%"' "$LBODY" | |
| 126 | +check "mem stat merged" '12.5MiB / 1GiB' "$LBODY" | |
| 127 | +printf '%s' "$LBODY" | python3 -c 'import json,sys; d=json.load(sys.stdin); assert len(d["containers"])==3' 2>/dev/null \ | |
| 128 | + && pass "list body is valid JSON with 3 containers" || fail "list body JSON invalid" | |
| 129 | + | |
| 130 | +section "mode 2 JSON info" | |
| 131 | +INFO=$(QUERY_STRING='action=info' "$BIN") | |
| 132 | +IBODY=$(body "$INFO") | |
| 133 | +check "info ok:true" '"ok":true' "$IBODY" | |
| 134 | +check "info action info" '"action":"info"' "$IBODY" | |
| 135 | +check "info runtime label" '"label":"custom"' "$IBODY" | |
| 136 | +check "info pid present" '"pid":' "$IBODY" | |
| 137 | +check "info utc present" '"utc":"20' "$IBODY" | |
| 138 | +check "info supported list" '"supported":["list","info","logs","control"]' "$IBODY" | |
| 139 | +printf '%s' "$IBODY" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | |
| 140 | + && pass "info body is valid JSON" || fail "info body JSON invalid" | |
| 141 | + | |
| 142 | +section "mode 2 JSON logs" | |
| 143 | +LOGS=$(QUERY_STRING='action=logs&cid=web' "$BIN") | |
| 144 | +LOG_BODY=$(body "$LOGS") | |
| 145 | +check "logs ok:true" '"ok":true' "$LOG_BODY" | |
| 146 | +check "logs cid echoed" '"cid":"web"' "$LOG_BODY" | |
| 147 | +check "logs tail 100" '"tail":100' "$LOG_BODY" | |
| 148 | +check "logs exit_code 0" '"exit_code":0' "$LOG_BODY" | |
| 149 | +check "logs first line" 'line one' "$LOG_BODY" | |
| 150 | +check "logs escapes quotes" 'line two with \"quotes\"' "$LOG_BODY" | |
| 151 | +check_not "logs has no Content-Length" 'Content-Length' "$LOGS" | |
| 152 | +printf '%s' "$LOG_BODY" | python3 -c 'import json,sys; d=json.load(sys.stdin); assert d["lines"][0]=="line one"' 2>/dev/null \ | |
| 153 | + && pass "logs body is valid JSON with parsed lines" || fail "logs body JSON invalid" | |
| 154 | + | |
| 155 | +section "mode 2 unknown action" | |
| 156 | +UNK=$(QUERY_STRING='action=bogus' "$BIN") | |
| 157 | +check "unknown action rejected" 'unknown_action' "$(body "$UNK")" | |
| 158 | +check "unknown action lists supported" '"supported":["list","info","logs","control"]' "$(body "$UNK")" | |
| 159 | + | |
| 160 | +section "mode 2 no runtime" | |
| 161 | +LIST2=$(DOCKER_BIN= PATH=/nonexistent QUERY_STRING='action=list' "$BIN") | |
| 162 | +NRT=$(body "$LIST2") | |
| 163 | +check "no-runtime available false" '"available":false' "$NRT" | |
| 164 | +check "no-runtime graceful message" 'Neither docker nor podman' "$NRT" | |
| 165 | +check "no-runtime count 0" '"count":0' "$NRT" | |
| 166 | +LOGS2=$(DOCKER_BIN= PATH=/nonexistent QUERY_STRING='action=logs&cid=web' "$BIN") | |
| 167 | +check "no-runtime logs explains why" 'runtime_available' "$(body "$LOGS2")" | |
| 168 | + | |
| 169 | +section "injection & validation" | |
| 170 | +INJ1=$(QUERY_STRING='action=logs&cid=a;id' "$BIN") | |
| 171 | +check "semicolon cid rejected" 'invalid_cid' "$(body "$INJ1")" | |
| 172 | +INJ2=$(QUERY_STRING='action=logs&cid=--help' "$BIN") | |
| 173 | +check "leading-dash cid rejected" 'invalid_cid' "$(body "$INJ2")" | |
| 174 | +INJ3=$(QUERY_STRING='action=logs&cid=a%24(id)' "$BIN") | |
| 175 | +check "command-substitution cid rejected" 'invalid_cid' "$(body "$INJ3")" | |
| 176 | +INJ4=$(QUERY_STRING='action=logs&cid=8a7b6c5d4e3f' "$BIN") | |
| 177 | +check "valid hex cid accepted" '"ok":true' "$(body "$INJ4")" | |
| 178 | +INJ5=$(QUERY_STRING='action=logs&cid=my_app.v2-x' "$BIN") | |
| 179 | +check "valid dotted/dashed cid accepted" '"ok":true' "$(body "$INJ5")" | |
| 180 | +INJ6=$(QUERY_STRING="action=logs&cid=$(printf 'a%.0s' $(seq 1 200))" "$BIN") | |
| 181 | +check "over-long cid rejected" 'invalid_cid' "$(body "$INJ6")" | |
| 182 | + | |
| 183 | +section "control (POST-only, op allowlist)" | |
| 184 | +CG=$(QUERY_STRING='action=control&op=start&cid=web' "$BIN") | |
| 185 | +check "control GET refused" 'control_requires_post' "$(body "$CG")" | |
| 186 | +check "control GET status 405" 'Status: 405' "$CG" | |
| 187 | +CP=$(REQUEST_METHOD=POST CONTENT_LENGTH=17 QUERY_STRING='action=control' \ | |
| 188 | + sh -c 'printf "op=start&cid=web" | ./plugin_docker') | |
| 189 | +check "control POST start ok" '"ok":true' "$(body "$CP")" | |
| 190 | +check "control POST op echoed" '"op":"start"' "$(body "$CP")" | |
| 191 | +CP2=$(REQUEST_METHOD=POST CONTENT_LENGTH=17 QUERY_STRING='action=control' \ | |
| 192 | + sh -c 'printf "op=pwn&cid=web " | ./plugin_docker') | |
| 193 | +check "invalid op rejected" 'invalid_op' "$(body "$CP2")" | |
| 194 | +CP3=$(REQUEST_METHOD=POST CONTENT_LENGTH=22 QUERY_STRING='action=control' \ | |
| 195 | + sh -c 'printf "op=stop&cid=a;id " | ./plugin_docker') | |
| 196 | +check "control POST injection rejected" 'invalid_cid' "$(body "$CP3")" | |
| 197 | +CP4=$(printf 'op=start&cid=web' | DOCKER_BIN= PATH=/nonexistent \ | |
| 198 | + REQUEST_METHOD=POST CONTENT_LENGTH=16 QUERY_STRING='action=control' ./plugin_docker) | |
| 199 | +check "control POST without runtime degrades" 'runtime_available' "$(body "$CP4")" | |
| 200 | + | |
| 201 | +section "mode 3 HTML" | |
| 202 | +HTML=$(QUERY_STRING='' "$BIN") | |
| 203 | +check "html content-type" 'Content-Type: text/html; charset=utf-8' "$HTML" | |
| 204 | +check_not "html has no Content-Length" 'Content-Length' "$HTML" | |
| 205 | +check "html has viewport meta" 'width=device-width' "$HTML" | |
| 206 | +check "html title docker" '<title>docker</title>' "$HTML" | |
| 207 | +check "html back-link present" 'Back to Bot' "$HTML" | |
| 208 | +check "html KPI total" "k-total" "$HTML" | |
| 209 | +check "html KPI running" "k-run" "$HTML" | |
| 210 | +check "html table rows host" "id='rows'" "$HTML" | |
| 211 | +check "html log viewer card" "logCard" "$HTML" | |
| 212 | +check "html uses /plugins?plugin= route" "/plugins?plugin=" "$HTML" | |
| 213 | +check "html uses POST for control" "method:'POST'" "$HTML" | |
| 214 | +check "html has theme switch" "bot_theme" "$HTML" | |
| 215 | +check "html closes document" '</html>' "$HTML" | |
| 216 | +EMB=$(QUERY_STRING='embed=1' "$BIN") | |
| 217 | +check_not "embed=1 strips the back-link" 'Back to Bot' "$EMB" | |
| 218 | +check "embed=1 still renders UI" "k-total" "$EMB" | |
| 219 | +ZEROEMOJI=$(printf '%s' "$HTML" | python3 -c ' | |
| 220 | +import sys | |
| 221 | +s = sys.stdin.read() | |
| 222 | +bad = [c for c in s if ord(c) > 0x2600 and ord(c) not in (0x2014, 0x2013, 0x2026)] | |
| 223 | +print(len(bad)) | |
| 224 | +') | |
| 225 | +[ "$ZEROEMOJI" = "0" ] && pass "HTML contains no emoji glyphs" || fail "HTML has $ZEROEMOJI emoji glyph(s)" | |
| 226 | +PK="pico""bot" | |
| 227 | +check_not "html has no internal fleet paths" "$PK" "$HTML" | |
| 228 | +check_not "html has no private IPs" "192.168." "$HTML" | |
| 229 | + | |
| 230 | +section "format=json alias" | |
| 231 | +FJ=$(QUERY_STRING='format=json' "$BIN") | |
| 232 | +check "format=json routes to JSON" 'Content-Type: application/json' "$FJ" | |
| 233 | + | |
| 234 | +# ---------------------------------------------------------------- optional targets | |
| 235 | +section "optional cross builds" | |
| 236 | +if [ -f plugin_docker.musl ]; then | |
| 237 | + M=$(./plugin_docker.musl --meta) | |
| 238 | + check "musl build --meta" '"name":"docker"' "$M" | |
| 239 | +else | |
| 240 | + echo " skip musl (not built)" | |
| 241 | +fi | |
| 242 | +if [ -f plugin_docker.exe ]; then | |
| 243 | + MAGIC=$(head -c 2 plugin_docker.exe) | |
| 244 | + [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ" | |
| 245 | +else | |
| 246 | + echo " skip windows PE (not built)" | |
| 247 | +fi | |
| 248 | + | |
| 249 | +# ---------------------------------------------------------------- history audit | |
| 250 | +section "git history secret & LAN audit" | |
| 251 | +if git rev-parse --git-dir >/dev/null 2>&1; then | |
| 252 | + ALL="$MOCKDIR/history.txt" | |
| 253 | + # Bookkeeping lines of this audit are excluded so the detector cannot flag itself. | |
| 254 | + git log -p --all 2>/dev/null \ | |
| 255 | + | grep -v '^Author: ' \ | |
| 256 | + | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "html has no internal fleet' \ | |
| 257 | + > "$ALL" || : > "$ALL" | |
| 258 | + | |
| 259 | + audit() { # audit <label> <regex> | |
| 260 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | |
| 261 | + if [ -n "$H" ]; then | |
| 262 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | |
| 263 | + else | |
| 264 | + pass "history clean: $1" | |
| 265 | + fi | |
| 266 | + } | |
| 267 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 268 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 269 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 270 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 271 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 272 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 273 | + audit "bare host password" 'Xboxone0909|xboxone' | |
| 274 | + PK="pico""bot"; WT=".work""trees" | |
| 275 | + audit "fleet path" "/codebases/${PK}|${WT}/" | |
| 276 | +else | |
| 277 | + echo " skip history audit (not a git checkout)" | |
| 278 | +fi | |
| 279 | + | |
| 280 | +# ---------------------------------------------------------------- summary | |
| 281 | +rm -rf "$MOCKDIR" | |
| 282 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | |
| 283 | +printf ' passed: %d\n' "$PASS" | |
| 284 | +printf ' failed: %d\n' "$FAIL" | |
| 285 | +if [ "$FAIL" -ne 0 ]; then | |
| 286 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | |
| 287 | + exit 1 | |
| 288 | +fi | |
| 289 | +printf ' %sRESULT: ALL PASSED%s\n' "$C_OK" "$C_0" | |
| 290 | +exit 0 | |
| 0 | 291 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..791c966 | index 0000000..791c966 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,9 @@ | @@ -0,0 +1,9 @@ | ||
| 1 | +/plugin_docker | ||
| 2 | +/plugin_docker.exe | ||
| 3 | +*.o | ||
| 4 | +*.obj | ||
| 5 | +bin/ | ||
| 6 | +*.tmp | ||
| 7 | +*.log | ||
| 8 | +/plugin_docker.musl | ||
| 9 | +/plugin_docker.macos-* |
| 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..cc652e3 | index 0000000..cc652e3 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,56 @@ | @@ -0,0 +1,56 @@ | ||
| 1 | +# plugin_docker — ScorpioX Bot open-source container dashboard plugin | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_docker | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_docker (fully static) | ||
| 6 | +# make win64 MinGW-w64 static -> ./plugin_docker.exe | ||
| 7 | +# make macos Apple clang -> ./plugin_docker (run on macOS) | ||
| 8 | +# make test build + run tests/run.sh | ||
| 9 | +# make clean | ||
| 10 | + | ||
| 11 | +CC ?= cc | ||
| 12 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | ||
| 13 | +MUSL_CC ?= musl-gcc | ||
| 14 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 15 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 16 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 17 | +SRC := src/plugin_docker.c | ||
| 18 | +BIN := plugin_docker | ||
| 19 | +EXE := plugin_docker.exe | ||
| 20 | + | ||
| 21 | +.PHONY: all native musl win64 macos test clean distclean help | ||
| 22 | + | ||
| 23 | +all: native | ||
| 24 | + | ||
| 25 | +native: $(BIN) | ||
| 26 | + | ||
| 27 | +$(BIN): $(SRC) | ||
| 28 | + @echo "==> native build ($(CC))" | ||
| 29 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 30 | + | ||
| 31 | +# Static musl build — the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 32 | +musl: $(SRC) | ||
| 33 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 34 | + $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN) $(SRC) | ||
| 35 | + | ||
| 36 | +# Native Win64 static PE — runs on any Windows 10/11 x64 node | ||
| 37 | +win64: $(SRC) | ||
| 38 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 39 | + $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) | ||
| 40 | + | ||
| 41 | +# Apple clang build (run this on macOS) | ||
| 42 | +macos: $(SRC) | ||
| 43 | + @echo "==> Apple clang build" | ||
| 44 | + $(CC) $(CFLAGS) -o $(BIN) $(SRC) | ||
| 45 | + | ||
| 46 | +test: native | ||
| 47 | + @sh tests/run.sh | ||
| 48 | + | ||
| 49 | +clean: | ||
| 50 | + rm -f $(BIN) $(EXE) | ||
| 51 | + rm -rf bin | ||
| 52 | + | ||
| 53 | +distclean: clean | ||
| 54 | + | ||
| 55 | +help: | ||
| 56 | + @echo "make | make musl | make win64 | make macos | make test | make clean" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..5d2f0ab | index 0000000..5d2f0ab | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,190 @@ | @@ -0,0 +1,190 @@ | ||
| 1 | +# plugin_docker — ScorpioX Bot open-source container dashboard plugin | ||
| 2 | + | ||
| 3 | +A clean-room, MIT-licensed [ScorpioX Bot](https://bot.scorpiox.net) dynamic plugin that shows | ||
| 4 | +the containers running on **your own node**, their live CPU and memory use, their last 100 | ||
| 5 | +log lines, and lets you safely start, stop and restart them. | ||
| 6 | + | ||
| 7 | +One C99 file. No dependencies. No daemon of its own. No outbound network requests. | ||
| 8 | + | ||
| 9 | +``` | ||
| 10 | +plugin_docker --meta | ||
| 11 | +{"name":"docker","desc":"Containers"} | ||
| 12 | +``` | ||
| 13 | + | ||
| 14 | +--- | ||
| 15 | + | ||
| 16 | +## What it does | ||
| 17 | + | ||
| 18 | +| Area | Detail | | ||
| 19 | +|---|---| | ||
| 20 | +| **Runtime detection** | Auto-detects `docker` or `podman` on `PATH`; `DOCKER_BIN` overrides with an explicit path. If neither exists the UI says so instead of failing. | | ||
| 21 | +| **Container list** | `ps -a` gives ID, name, image, state, status and ports; `stats --no-stream` is merged in for CPU and memory. | | ||
| 22 | +| **Log viewer** | `logs --tail 100 <id>`, rendered both as a `lines` array and as raw `text`. | | ||
| 23 | +| **Control** | `start` / `stop` / `restart`, **POST only**, op allowlisted, one container at a time. | | ||
| 24 | +| **Filtering** | Client-side search across name, image, id and ports, plus a state dropdown. | | ||
| 25 | +| **Theme** | Follows the Bot theme (`localStorage.bot_theme`), dark by default, no flash. | | ||
| 26 | +| **Embed mode** | `?embed=1` drops the back-link so it fits the chat floating window. | | ||
| 27 | + | ||
| 28 | +### Why it is safe | ||
| 29 | + | ||
| 30 | +Container identifiers arrive from the browser, so they are the only real attack surface. | ||
| 31 | +Before any identifier can reach a command line it must match: | ||
| 32 | + | ||
| 33 | +``` | ||
| 34 | +[A-Za-z0-9_.-]{1,128} and must not start with '-' or '.' | ||
| 35 | +``` | ||
| 36 | + | ||
| 37 | +That single rule blocks flag injection (`cid=--help`), command injection (`cid=a;id`), | ||
| 38 | +substitution (`cid=a$(id)`) and over-long inputs. A test asserts each of these. | ||
| 39 | + | ||
| 40 | +`action=control` additionally refuses to run unless `REQUEST_METHOD` is POST, and `op` must | ||
| 41 | +be one of `start`, `stop`, `restart`. | ||
| 42 | + | ||
| 43 | +--- | ||
| 44 | + | ||
| 45 | +## Install | ||
| 46 | + | ||
| 47 | +### Pre-built (no compiler needed) | ||
| 48 | + | ||
| 49 | +```sh | ||
| 50 | +# Linux x86_64 — the static musl binary works on Alpine, Debian, Ubuntu, Arch, Omarchy | ||
| 51 | +mkdir -p ~/.scorpiox/plugins | ||
| 52 | +curl -fsSL https://dist.scorpiox.net/bot-plugins/docker/1.0.0/linux-x86_64-musl/plugin_docker \ | ||
| 53 | + -o ~/.scorpiox/plugins/plugin_docker | ||
| 54 | +chmod +x ~/.scorpiox/plugins/plugin_docker | ||
| 55 | +~/.scorpiox/plugins/plugin_docker --meta | ||
| 56 | +``` | ||
| 57 | + | ||
| 58 | +On Windows, put `plugin_docker.exe` in `%LOCALAPPDATA%\scorpiox\plugins\`. | ||
| 59 | +On a BotCloud container, use `/workspace/.scorpiox/plugins/` so it survives restarts. | ||
| 60 | + | ||
| 61 | +No server restart is required — `scorpiox-server` resolves plugin routes live. | ||
| 62 | + | ||
| 63 | +### From source | ||
| 64 | + | ||
| 65 | +```sh | ||
| 66 | +git clone https://plugingit.scorpiox.net/scorpiox-bot-plugin-docker.git | ||
| 67 | +cd scorpiox-bot-plugin-docker | ||
| 68 | +make # native | ||
| 69 | +make musl # fully static Linux — the universal artifact | ||
| 70 | +make win64 # static Windows PE via MinGW-w64 | ||
| 71 | +make test # 90+ offline assertions, no real runtime needed | ||
| 72 | +cp plugin_docker ~/.scorpiox/plugins/ | ||
| 73 | +``` | ||
| 74 | + | ||
| 75 | +### Let your agent do it | ||
| 76 | + | ||
| 77 | +Paste this into ScorpioX Bot Chat: | ||
| 78 | + | ||
| 79 | +> Clone `https://plugingit.scorpiox.net/scorpiox-bot-plugin-docker.git`, audit | ||
| 80 | +> `src/plugin_docker.c` for safety, customize it for my machine, compile it natively, verify | ||
| 81 | +> `--meta`, and install it to `~/.scorpiox/plugins/`. | ||
| 82 | + | ||
| 83 | +The whole plugin is one readable C file, so an audit is a five-minute job, not a promise. | ||
| 84 | + | ||
| 85 | +--- | ||
| 86 | + | ||
| 87 | +## The three-mode contract | ||
| 88 | + | ||
| 89 | +Every ScorpioX Bot node plugin is one executable that switches on how it is invoked. | ||
| 90 | + | ||
| 91 | +### 1. Metadata | ||
| 92 | + | ||
| 93 | +```sh | ||
| 94 | +plugin_docker --meta # or SX_PLUGIN_META=1 plugin_docker | ||
| 95 | +{"name":"docker","desc":"Containers"} | ||
| 96 | +``` | ||
| 97 | + | ||
| 98 | +`name` is one word, `desc` is 10 characters. Both are rendered in the Hub `...` menu, the | ||
| 99 | +session card `:` menu and Settings, so short is not a style preference — long strings break | ||
| 100 | +the layout. | ||
| 101 | + | ||
| 102 | +### 2. JSON API | ||
| 103 | + | ||
| 104 | +```sh | ||
| 105 | +QUERY_STRING='action=list' plugin_docker | ||
| 106 | +QUERY_STRING='action=info' plugin_docker | ||
| 107 | +QUERY_STRING='action=logs&cid=web' plugin_docker | ||
| 108 | +REQUEST_METHOD=POST CONTENT_LENGTH=17 \ | ||
| 109 | + QUERY_STRING='action=control' sh -c 'printf "op=start&cid=web" | plugin_docker' | ||
| 110 | +``` | ||
| 111 | + | ||
| 112 | +All responses are `Content-Type: application/json; charset=utf-8` and, deliberately, | ||
| 113 | +**never** carry `Content-Length` — the server owns framing. | ||
| 114 | + | ||
| 115 | +`action=list`: | ||
| 116 | + | ||
| 117 | +```json | ||
| 118 | +{ | ||
| 119 | + "ok": true, | ||
| 120 | + "action": "list", | ||
| 121 | + "runtime": { "available": true, "bin": "docker", "label": "docker" }, | ||
| 122 | + "daemon_available": true, | ||
| 123 | + "count": 2, | ||
| 124 | + "summary": { "total": 2, "running": 2, "exited": 0, "paused": 0, "other": 0 }, | ||
| 125 | + "containers": [ | ||
| 126 | + { "id": "a1b2c3d4e5f6", "name": "web", "image": "nginx:1.27", | ||
| 127 | + "state": "running", "status": "Up 3 hours", | ||
| 128 | + "ports": "0.0.0.0:8080->80/tcp", "cpu": "1.25%", "mem": "12.5MiB / 1GiB" } | ||
| 129 | + ] | ||
| 130 | +} | ||
| 131 | +``` | ||
| 132 | + | ||
| 133 | +When no runtime exists the same shape comes back with | ||
| 134 | +`"runtime":{"available":false}` and a `message`, so a caller never has to special-case an | ||
| 135 | +error path. | ||
| 136 | + | ||
| 137 | +| Error | HTTP | Meaning | | ||
| 138 | +|---|---|---| | ||
| 139 | +| `invalid_cid` | 400 | identifier failed validation | | ||
| 140 | +| `invalid_op` | 400 | op was not start/stop/restart | | ||
| 141 | +| `unknown_action` | 400 | unknown `action` (response lists supported ones) | | ||
| 142 | +| `control_requires_post` | 405 | `action=control` without POST | | ||
| 143 | +| `runtime_available` | 503 | no docker and no podman on this node | | ||
| 144 | +| (runtime failed) | 409 | the runtime itself returned non-zero | | ||
| 145 | + | ||
| 146 | +### 3. HTML UI | ||
| 147 | + | ||
| 148 | +Plain `GET` returns the dashboard. It uses no framework, no CDN and no build step. | ||
| 149 | + | ||
| 150 | +--- | ||
| 151 | + | ||
| 152 | +## Routing: the one thing everyone gets wrong | ||
| 153 | + | ||
| 154 | +The same HTML is served two different ways, and the JS has to build the right URL for each. | ||
| 155 | + | ||
| 156 | +| Opened as | Fetch must go to | | ||
| 157 | +|---|---| | ||
| 158 | +| `https://bot.scorpiox.net/plugins?plugin=plugin_docker` (hub) | `/plugins?plugin=plugin_docker&action=list&node=...` | | ||
| 159 | +| `https://<node>:8150/plugin_docker` (direct) | `/plugin_docker?action=list` | | ||
| 160 | + | ||
| 161 | +The plugin detects which one it is by looking for `?plugin=` on its own URL. Getting this | ||
| 162 | +backwards produces the classic "works on the node, blank on the hub" bug. | ||
| 163 | + | ||
| 164 | +--- | ||
| 165 | + | ||
| 166 | +## Layout | ||
| 167 | + | ||
| 168 | +``` | ||
| 169 | +src/plugin_docker.c 40 KB, the entire plugin (POSIX + _WIN32, C99) | ||
| 170 | +tests/run.sh offline suite: mock runtime, injection attempts, HTML, history audit | ||
| 171 | +Makefile native / musl / win64 / macos / test / clean | ||
| 172 | +build.ps1 Windows build with an MZ header assertion and a --meta smoke test | ||
| 173 | +release-dist.sh secret scan -> build -> manifest -> dist upload -> plugingit mirror | ||
| 174 | +``` | ||
| 175 | + | ||
| 176 | +## Tests | ||
| 177 | + | ||
| 178 | +```sh | ||
| 179 | +make test | ||
| 180 | +``` | ||
| 181 | + | ||
| 182 | +The suite needs no container runtime: it writes a mock `DOCKER_BIN` shell script and points | ||
| 183 | +`DOCKER_BIN` at it. It then asserts metadata, every JSON shape, both injection classes, | ||
| 184 | +POST-only control, the HTML contract (no `Content-Length`, no emoji, no private IPs, embed | ||
| 185 | +mode) and finally walks the **entire git history** looking for LAN addresses, PATs, tokens | ||
| 186 | +and host passwords. | ||
| 187 | + | ||
| 188 | +## License | ||
| 189 | + | ||
| 190 | +MIT. Copyright (c) 2026 SCORPIOX INC. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..8581f54 | index 0000000..8581f54 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/build.ps1 | +++ b/build.ps1 | ||
| @@ -0,0 +1,53 @@ | @@ -0,0 +1,53 @@ | ||
| 1 | +# build.ps1 — Windows MinGW-w64 static build for plugin_docker | ||
| 2 | +# | ||
| 3 | +# Usage (from the repo root, PowerShell): | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 5 | +# | ||
| 6 | +# Produces .\plugin_docker.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_docker.c" | ||
| 14 | + $Out = Join-Path $ScriptDir "plugin_docker.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 | + Write-Host "==> building plugin_docker.exe with $Cc" | ||
| 31 | + & $Cc -O2 -std=c99 -Wall -Wextra -static -o $Out $Src | ||
| 32 | + if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" } | ||
| 33 | + | ||
| 34 | + if (-not (Test-Path $Out)) { throw "build produced no output" } | ||
| 35 | + | ||
| 36 | + # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not. | ||
| 37 | + $bytes = [System.IO.File]::ReadAllBytes($Out) | ||
| 38 | + if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) { | ||
| 39 | + throw "output is not a PE executable (missing MZ header)" | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + Write-Host "==> metadata check" | ||
| 43 | + & $Out --meta | ||
| 44 | + if ($LASTEXITCODE -ne 0) { throw "--meta failed" } | ||
| 45 | + | ||
| 46 | + $size = (Get-Item $Out).Length | ||
| 47 | + Write-Host "" | ||
| 48 | + Write-Host "Built $Out ($size bytes)" | ||
| 49 | + Write-Host "Install: Copy-Item plugin_docker.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`"" | ||
| 50 | +} | ||
| 51 | +finally { | ||
| 52 | + Pop-Location | ||
| 53 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..a3f9efd | index 0000000..a3f9efd | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,350 @@ | @@ -0,0 +1,350 @@ | ||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# release-dist.sh — build, scan and publish plugin_docker 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 -> plugingit mirror. | ||
| 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 | + | ||
| 27 | +set -euo pipefail | ||
| 28 | + | ||
| 29 | +SLUG="docker" | ||
| 30 | +ID="plugin_docker" | ||
| 31 | +VERSION="1.0.0" | ||
| 32 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | ||
| 33 | + | ||
| 34 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | ||
| 35 | +cd "$ROOT" | ||
| 36 | + | ||
| 37 | +DRY_RUN=0 | ||
| 38 | +DO_MACOS=1 | ||
| 39 | +DO_MIRROR=1 | ||
| 40 | +for arg in "$@"; do | ||
| 41 | + case "$arg" in | ||
| 42 | + --dry-run) DRY_RUN=1 ;; | ||
| 43 | + --no-macos) DO_MACOS=0 ;; | ||
| 44 | + --no-mirror) DO_MIRROR=0 ;; | ||
| 45 | + -h|--help) sed -n '2,30p' "$0"; exit 0 ;; | ||
| 46 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | ||
| 47 | + esac | ||
| 48 | +done | ||
| 49 | + | ||
| 50 | +DIST_HOST="${DIST_HOST:-}" | ||
| 51 | +DIST_PASS="${DIST_PASS:-}" | ||
| 52 | +DIST_PATH="${DIST_PATH:-/data/dist}" | ||
| 53 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | ||
| 54 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | ||
| 55 | + | ||
| 56 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | ||
| 57 | +mkdir -p "$STAGE" | ||
| 58 | +trap 'rm -rf "$STAGE"' EXIT | ||
| 59 | + | ||
| 60 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | ||
| 61 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | ||
| 62 | + | ||
| 63 | +# ---------------------------------------------------------------- 0. preflight | ||
| 64 | +say "0/7 preflight" | ||
| 65 | + | ||
| 66 | +if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 67 | + say "using scorpiox-cli-botplugin publish" | ||
| 68 | + exec scorpiox-cli-botplugin publish "$ROOT" | ||
| 69 | +fi | ||
| 70 | +echo " scorpiox-cli-botplugin not installed — running standalone pipeline" | ||
| 71 | + | ||
| 72 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | ||
| 73 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | ||
| 74 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | ||
| 75 | +echo " version $VERSION" | ||
| 76 | +echo " commit $COMMIT" | ||
| 77 | + | ||
| 78 | +# ---------------------------------------------------------------- 1. secret scan | ||
| 79 | +say "1/7 secret & LAN scan (full history)" | ||
| 80 | + | ||
| 81 | +SCAN_TMP="$STAGE/history.txt" | ||
| 82 | +# Scan every added/removed line of every commit. Two exclusions, both about the | ||
| 83 | +# audit rather than the code: the committer identity line, and any line that is | ||
| 84 | +# itself a scan definition — otherwise this file's own detector patterns read as | ||
| 85 | +# findings in every historical revision of it. | ||
| 86 | +git log -p --all 2>/dev/null \ | ||
| 87 | + | grep -v '^Author: ' \ | ||
| 88 | + | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \ | ||
| 89 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | ||
| 90 | +HITS=0 | ||
| 91 | +scan() { # scan <label> <regex> | ||
| 92 | + local out | ||
| 93 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | ||
| 94 | + if [ -n "$out" ]; then | ||
| 95 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | ||
| 96 | + printf '%s\n' "$out" | sed 's/^/ /' | ||
| 97 | + HITS=$((HITS + 1)) | ||
| 98 | + else | ||
| 99 | + printf ' ok %s\n' "$1" | ||
| 100 | + fi | ||
| 101 | +} | ||
| 102 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 103 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 104 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 105 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 106 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 107 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 108 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | ||
| 109 | +P_ROOT="/codebases" | ||
| 110 | +P_PICOBOT="${P_ROOT}/pico""bot" | ||
| 111 | +P_WT=".work""trees" | ||
| 112 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | ||
| 113 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | ||
| 114 | +if [ "$HITS" -ne 0 ]; then | ||
| 115 | + die "secret scan found $HITS problem(s) — refusing to publish" | ||
| 116 | +fi | ||
| 117 | +echo " clean: 0 hits" | ||
| 118 | + | ||
| 119 | +# ---------------------------------------------------------------- 2. build | ||
| 120 | +say "2/7 build targets" | ||
| 121 | + | ||
| 122 | +build_ok() { [ -f "$1" ]; } | ||
| 123 | + | ||
| 124 | +# linux-x86_64 (glibc, native) | ||
| 125 | +if command -v cc >/dev/null 2>&1; then | ||
| 126 | + cc -O2 -std=c99 -Wall -Wextra -o "$STAGE/$ID" src/$ID.c || die "native build failed" | ||
| 127 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | ||
| 128 | +else | ||
| 129 | + die "no native cc found" | ||
| 130 | +fi | ||
| 131 | + | ||
| 132 | +# linux-x86_64-musl (fully static — the universal Linux artifact) | ||
| 133 | +if command -v musl-gcc >/dev/null 2>&1; then | ||
| 134 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.musl" src/$ID.c \ | ||
| 135 | + || die "musl build failed" | ||
| 136 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | ||
| 137 | +else | ||
| 138 | + echo " skip linux-x86_64-musl (no musl-gcc)" | ||
| 139 | +fi | ||
| 140 | + | ||
| 141 | +# windows-x86_64 (static PE) | ||
| 142 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | ||
| 143 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -o "$STAGE/$ID.exe" src/$ID.c \ | ||
| 144 | + || die "MinGW build failed" | ||
| 145 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | ||
| 146 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | ||
| 147 | +else | ||
| 148 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | ||
| 149 | +fi | ||
| 150 | + | ||
| 151 | +# macOS legs — Mach-O must be produced by Apple clang on a real Mac. | ||
| 152 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | ||
| 153 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | ||
| 154 | + MAC_USER="${MAC_USER:-$(whoami)}" | ||
| 155 | + MAC_DIR="/tmp/${ID}-mac-$$" | ||
| 156 | + echo " building macOS legs on $MAC_HOST" | ||
| 157 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | ||
| 158 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | ||
| 159 | + if [ -n "${MAC_PASS:-}" ]; then | ||
| 160 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | ||
| 161 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | ||
| 162 | + fi | ||
| 163 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | ||
| 164 | + if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then | ||
| 165 | + # Build straight from the uploaded file — no src/ tree on the remote. | ||
| 166 | + for slice in arm64 x86_64; do | ||
| 167 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | ||
| 168 | + "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -arch $slice -o $ID.$slice $ID.c" \ | ||
| 169 | + 2>/dev/null; then | ||
| 170 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | ||
| 171 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | ||
| 172 | + else | ||
| 173 | + echo " warn: macos-$slice build failed on $MAC_HOST" | ||
| 174 | + fi | ||
| 175 | + done | ||
| 176 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true | ||
| 177 | + else | ||
| 178 | + echo " warn: mac scp failed" | ||
| 179 | + fi | ||
| 180 | + else | ||
| 181 | + echo " warn: mac host unreachable" | ||
| 182 | + fi | ||
| 183 | +else | ||
| 184 | + echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)" | ||
| 185 | +fi | ||
| 186 | + | ||
| 187 | +# ---------------------------------------------------------------- 3. package | ||
| 188 | +say "3/7 package" | ||
| 189 | + | ||
| 190 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | ||
| 191 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | ||
| 192 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | ||
| 193 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | ||
| 194 | + | ||
| 195 | +target_meta() { # target_meta <key> <file> <format> <relpath> <name> | ||
| 196 | + local key="$1" file="$2" fmt="$3" rel="$4" name="$5" | ||
| 197 | + [ -f "$file" ] || return 0 | ||
| 198 | + local sha size | ||
| 199 | + sha=$(sha256sum "$file" | awk '{print $1}') | ||
| 200 | + size=$(wc -c < "$file" | tr -d ' ') | ||
| 201 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | ||
| 202 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +{ | ||
| 206 | + printf '{\n' | ||
| 207 | + printf ' "slug": "%s",\n' "$SLUG" | ||
| 208 | + printf ' "id": "%s",\n' "$ID" | ||
| 209 | + printf ' "name": "docker",\n' | ||
| 210 | + printf ' "desc": "Containers",\n' | ||
| 211 | + printf ' "title": "Local Container Dashboard",\n' | ||
| 212 | + printf ' "summary": "Zero-dependency local Docker and Podman dashboard: container list with live CPU and memory, 100-line log viewer, and safe start/stop/restart - all served from one C99 binary on your own node.",\n' | ||
| 213 | + printf ' "category": "containers",\n' | ||
| 214 | + printf ' "version": "%s",\n' "$VERSION" | ||
| 215 | + printf ' "license": "MIT",\n' | ||
| 216 | + printf ' "trust_notice": "Executes native C code on your node. Invokes the local docker or podman CLI to list containers, read logs and change container state; makes zero outbound network requests.",\n' | ||
| 217 | + printf ' "capabilities": ["proc_exec_docker", "container_list", "container_logs", "container_state_change"],\n' | ||
| 218 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | ||
| 219 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | ||
| 220 | + printf ' "git_commit": "%s",\n' "$COMMIT" | ||
| 221 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 222 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | ||
| 223 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID" | ||
| 224 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID" | ||
| 225 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | ||
| 226 | + printf ' "targets": {\n' | ||
| 227 | + first=1 | ||
| 228 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | ||
| 229 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID" | ||
| 230 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID" | ||
| 231 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID" | ||
| 232 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID" | ||
| 233 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID" | ||
| 234 | + printf '\n }\n}\n' | ||
| 235 | +} > "$STAGE/manifest.json" | ||
| 236 | + | ||
| 237 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | ||
| 238 | + || die "generated manifest.json is not valid JSON" | ||
| 239 | +echo " manifest.json ok" | ||
| 240 | + | ||
| 241 | +# SHA256SUMS — relative paths, exactly as published | ||
| 242 | +( cd "$STAGE" | ||
| 243 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | ||
| 244 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | ||
| 245 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | ||
| 246 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | ||
| 247 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | ||
| 248 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | ||
| 249 | + true ) > "$STAGE/SHA256SUMS" | ||
| 250 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | ||
| 251 | + | ||
| 252 | +# ---------------------------------------------------------------- 4. stage | ||
| 253 | +say "4/7 stage tree" | ||
| 254 | +PKG="$STAGE/pkg" | ||
| 255 | +mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/macos-arm64" \ | ||
| 256 | + "$PKG/macos-x86_64" "$PKG/windows-x86_64" | ||
| 257 | +cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID" | ||
| 258 | +[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID" | ||
| 259 | +[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID" | ||
| 260 | +[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID" | ||
| 261 | +[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe" | ||
| 262 | +cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | ||
| 263 | +chmod +x "$PKG"/*/$ID 2>/dev/null || true | ||
| 264 | +find "$PKG" -type f | sed 's/^/ /' | ||
| 265 | + | ||
| 266 | +if [ "$DRY_RUN" -eq 1 ]; then | ||
| 267 | + say "dry run — staged at $STAGE/pkg (kept for inspection)" | ||
| 268 | + trap - EXIT | ||
| 269 | + exit 0 | ||
| 270 | +fi | ||
| 271 | + | ||
| 272 | +# ---------------------------------------------------------------- 5. upload | ||
| 273 | +say "5/7 upload" | ||
| 274 | + | ||
| 275 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload" | ||
| 276 | +SSH=(ssh -o StrictHostKeyChecking=no) | ||
| 277 | +SCP=(scp -o StrictHostKeyChecking=no) | ||
| 278 | +if [ -n "$DIST_PASS" ]; then | ||
| 279 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | ||
| 280 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | ||
| 281 | +fi | ||
| 282 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | ||
| 283 | + | ||
| 284 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | ||
| 285 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | ||
| 286 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | ||
| 287 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | ||
| 288 | +# OpenSSH 9 refuses to scp a bare "." source. | ||
| 289 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | ||
| 290 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | ||
| 291 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | ||
| 292 | + || die "remote extract failed" | ||
| 293 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | ||
| 294 | + | ||
| 295 | +# latest.json = copy of this version's manifest | ||
| 296 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | ||
| 297 | + || die "latest.json update failed" | ||
| 298 | +echo " updated bot-plugins/$SLUG/latest.json" | ||
| 299 | + | ||
| 300 | +# index.json — merge, preserving every sibling <slug>/latest.json | ||
| 301 | +say "index.json merge" | ||
| 302 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | ||
| 303 | +import json, os, sys, glob | ||
| 304 | +slug = sys.argv[1] | ||
| 305 | +entries = {} | ||
| 306 | +for p in sorted(glob.glob('*/latest.json')): | ||
| 307 | + s = os.path.dirname(p) | ||
| 308 | + try: | ||
| 309 | + entries[s] = json.load(open(p)) | ||
| 310 | + except Exception: | ||
| 311 | + pass | ||
| 312 | +index = { | ||
| 313 | + 'ok': True, | ||
| 314 | + 'service': 'bot-plugins-dist', | ||
| 315 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | ||
| 316 | + 'count': len(entries), | ||
| 317 | + 'slugs': sorted(entries), | ||
| 318 | + 'plugins': [entries[k] for k in sorted(entries)], | ||
| 319 | +} | ||
| 320 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | ||
| 321 | +os.replace('index.json.tmp', 'index.json') | ||
| 322 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | ||
| 323 | +PY" || die "index.json merge failed" | ||
| 324 | + | ||
| 325 | +# ---------------------------------------------------------------- 6. mirror | ||
| 326 | +say "6/7 plugingit mirror" | ||
| 327 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | ||
| 328 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | ||
| 329 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|") | ||
| 330 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | ||
| 331 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | ||
| 332 | + echo " mirrored to $PLUGINGIT_REMOTE" | ||
| 333 | +else | ||
| 334 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | ||
| 335 | +fi | ||
| 336 | + | ||
| 337 | +# ---------------------------------------------------------------- 7. verify | ||
| 338 | +say "7/7 verify" | ||
| 339 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | ||
| 340 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | ||
| 341 | +if [ "$CODE" = "200" ]; then | ||
| 342 | + 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"])))' \ | ||
| 343 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | ||
| 344 | +else | ||
| 345 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | ||
| 346 | +fi | ||
| 347 | + | ||
| 348 | +printf '\n\033[1mrelease complete\033[0m\n' | ||
| 349 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 350 | +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..f68942f | index 0000000..f68942f | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_docker.c | +++ b/src/plugin_docker.c | ||
| @@ -0,0 +1,1067 @@ | @@ -0,0 +1,1067 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_docker — ScorpioX Bot open-source container dashboard plugin | ||
| 3 | + * | ||
| 4 | + * A single clean-room C99 binary that serves THREE modes: | ||
| 5 | + * 1. --meta / SX_PLUGIN_META=1 -> JSON metadata for discovery | ||
| 6 | + * 2. ?action=... | ?format=json -> JSON node API (list / logs / control / info) | ||
| 7 | + * 3. GET (default) -> responsive HTML container dashboard | ||
| 8 | + * | ||
| 9 | + * Local node only. Auto-detects `docker` or `podman` on PATH (or DOCKER_BIN). | ||
| 10 | + * Every container identifier is validated against [A-Za-z0-9_.-]{1,128} with a | ||
| 11 | + * leading-dash rejection BEFORE it can reach a shell, so neither flag injection | ||
| 12 | + * (`cid=--help`) nor command injection (`cid=a;id`) is reachable. | ||
| 13 | + * | ||
| 14 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | ||
| 15 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | ||
| 16 | + * scorpiox-server on the node. | ||
| 17 | + * | ||
| 18 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 19 | + */ | ||
| 20 | + | ||
| 21 | +#if !defined(_WIN32) | ||
| 22 | +# define _POSIX_C_SOURCE 200809L | ||
| 23 | +# define _DEFAULT_SOURCE 1 | ||
| 24 | +#endif | ||
| 25 | + | ||
| 26 | +#include <stdio.h> | ||
| 27 | +#include <stdlib.h> | ||
| 28 | +#include <string.h> | ||
| 29 | +#include <time.h> | ||
| 30 | +#include <ctype.h> | ||
| 31 | +#include <errno.h> | ||
| 32 | + | ||
| 33 | +#if defined(_WIN32) | ||
| 34 | +# define WIN32_LEAN_AND_MEAN | ||
| 35 | +# include <windows.h> | ||
| 36 | +# include <io.h> | ||
| 37 | +# define sx_popen _popen | ||
| 38 | +# define sx_pclose _pclose | ||
| 39 | +# define sx_access _access | ||
| 40 | +# define SX_X_OK 0 | ||
| 41 | +# define SX_PATH_SEP ';' | ||
| 42 | +#else | ||
| 43 | +# include <unistd.h> | ||
| 44 | +# include <sys/wait.h> | ||
| 45 | +# include <sys/stat.h> | ||
| 46 | +# define sx_popen popen | ||
| 47 | +# define sx_pclose pclose | ||
| 48 | +# define sx_access access | ||
| 49 | +# define SX_X_OK X_OK | ||
| 50 | +# define SX_PATH_SEP ':' | ||
| 51 | +#endif | ||
| 52 | + | ||
| 53 | +#define PLUGIN_SLUG "docker" | ||
| 54 | +#define PLUGIN_ID "plugin_docker" | ||
| 55 | +#define PLUGIN_VER "1.0.0" | ||
| 56 | + | ||
| 57 | +#define MAX_CONTAINERS 256 | ||
| 58 | +#define LOG_TAIL 100 | ||
| 59 | + | ||
| 60 | +/* ------------------------------------------------------------------ */ | ||
| 61 | +/* Small utilities */ | ||
| 62 | +/* ------------------------------------------------------------------ */ | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +/* Percent-decode in place ('+' becomes space). */ | ||
| 66 | +static void url_decode(char *s) | ||
| 67 | +{ | ||
| 68 | + char *o = s; | ||
| 69 | + if (!s) return; | ||
| 70 | + while (*s) { | ||
| 71 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 72 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 73 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 74 | + *o++ = (char)((hi << 4) | lo); | ||
| 75 | + s += 3; | ||
| 76 | + } else if (*s == '+') { | ||
| 77 | + *o++ = ' '; | ||
| 78 | + s++; | ||
| 79 | + } else { | ||
| 80 | + *o++ = *s++; | ||
| 81 | + } | ||
| 82 | + } | ||
| 83 | + *o = '\0'; | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +/* Read one parameter (decoded) out of a form/query string. */ | ||
| 87 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 88 | +{ | ||
| 89 | + size_t klen; | ||
| 90 | + const char *p; | ||
| 91 | + | ||
| 92 | + if (!out || outsz == 0) return 0; | ||
| 93 | + out[0] = '\0'; | ||
| 94 | + if (!qs || !key) return 0; | ||
| 95 | + klen = strlen(key); | ||
| 96 | + | ||
| 97 | + for (p = qs; *p; ) { | ||
| 98 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 99 | + const char *v = p + klen + 1; | ||
| 100 | + size_t i = 0; | ||
| 101 | + while (*v && *v != '&' && i + 1 < outsz) | ||
| 102 | + out[i++] = *v++; | ||
| 103 | + out[i] = '\0'; | ||
| 104 | + url_decode(out); | ||
| 105 | + return 1; | ||
| 106 | + } | ||
| 107 | + p = strchr(p, '&'); | ||
| 108 | + if (!p) break; | ||
| 109 | + p++; | ||
| 110 | + } | ||
| 111 | + return 0; | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +static void json_str(const char *s) | ||
| 115 | +{ | ||
| 116 | + putchar('"'); | ||
| 117 | + for (; s && *s; s++) { | ||
| 118 | + unsigned char c = (unsigned char)*s; | ||
| 119 | + switch (c) { | ||
| 120 | + case '"': fputs("\\\"", stdout); break; | ||
| 121 | + case '\\': fputs("\\\\", stdout); break; | ||
| 122 | + case '\n': fputs("\\n", stdout); break; | ||
| 123 | + case '\r': fputs("\\r", stdout); break; | ||
| 124 | + case '\t': fputs("\\t", stdout); break; | ||
| 125 | + default: | ||
| 126 | + if (c < 0x20) printf("\\u%04x", (unsigned)c); | ||
| 127 | + else putchar((int)c); | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + putchar('"'); | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +static void utc_now(char *buf, size_t sz) | ||
| 134 | +{ | ||
| 135 | + time_t t = time(NULL); | ||
| 136 | + struct tm tmv; | ||
| 137 | +#if defined(_WIN32) | ||
| 138 | + gmtime_s(&tmv, &t); | ||
| 139 | +#else | ||
| 140 | + gmtime_r(&t, &tmv); | ||
| 141 | +#endif | ||
| 142 | + if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) { | ||
| 143 | + strncpy(buf, "1970-01-01T00:00:00Z", sz - 1); | ||
| 144 | + buf[sz - 1] = '\0'; | ||
| 145 | + } | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +static long node_pid(void) | ||
| 149 | +{ | ||
| 150 | +#if defined(_WIN32) | ||
| 151 | + return (long)GetCurrentProcessId(); | ||
| 152 | +#else | ||
| 153 | + return (long)getpid(); | ||
| 154 | +#endif | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +/* ------------------------------------------------------------------ */ | ||
| 158 | +/* Strict identifier validation */ | ||
| 159 | +/* ------------------------------------------------------------------ */ | ||
| 160 | + | ||
| 161 | +/* | ||
| 162 | + * Container identifiers (IDs, names, short IDs) must match | ||
| 163 | + * [A-Za-z0-9_.-]{1,128} and must not start with '-' or '.'. | ||
| 164 | + * Anything else is refused before it can reach a command line. | ||
| 165 | + */ | ||
| 166 | +static int valid_cid(const char *s) | ||
| 167 | +{ | ||
| 168 | + size_t n, i; | ||
| 169 | + if (!s || !*s) return 0; | ||
| 170 | + n = strlen(s); | ||
| 171 | + if (n > 128) return 0; | ||
| 172 | + if (s[0] == '-' || s[0] == '.') return 0; | ||
| 173 | + for (i = 0; i < n; i++) { | ||
| 174 | + unsigned char c = (unsigned char)s[i]; | ||
| 175 | + if (isalnum(c) || c == '_' || c == '.' || c == '-') continue; | ||
| 176 | + return 0; | ||
| 177 | + } | ||
| 178 | + return 1; | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +/* The runtime binary path must not contain quoting hazards. */ | ||
| 182 | +static int valid_runtime_path(const char *s) | ||
| 183 | +{ | ||
| 184 | + if (!s || !*s) return 0; | ||
| 185 | + if (strchr(s, '\'') || strchr(s, '\n') || strchr(s, '\r')) return 0; | ||
| 186 | + return 1; | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +static int valid_op(const char *s) | ||
| 190 | +{ | ||
| 191 | + return s && (strcmp(s, "start") == 0 || strcmp(s, "stop") == 0 || | ||
| 192 | + strcmp(s, "restart") == 0); | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +/* ------------------------------------------------------------------ */ | ||
| 196 | +/* Command execution */ | ||
| 197 | +/* ------------------------------------------------------------------ */ | ||
| 198 | + | ||
| 199 | +/* Run a shell command, capture stdout+stderr. Returns malloc'd text. */ | ||
| 200 | +static char *run_capture(const char *cmd, int *exit_code) | ||
| 201 | +{ | ||
| 202 | + FILE *fp; | ||
| 203 | + char *buf = NULL; | ||
| 204 | + size_t len = 0, cap = 0, chunk; | ||
| 205 | + char tmp[4096]; | ||
| 206 | + int status = 0; | ||
| 207 | + | ||
| 208 | + if (exit_code) *exit_code = -1; | ||
| 209 | + fp = sx_popen(cmd, "r"); | ||
| 210 | + if (!fp) return NULL; | ||
| 211 | + | ||
| 212 | + while ((chunk = fread(tmp, 1, sizeof(tmp), fp)) > 0) { | ||
| 213 | + if (len + chunk + 1 > cap) { | ||
| 214 | + size_t ncap = cap ? cap * 2 : 8192; | ||
| 215 | + char *nb; | ||
| 216 | + while (ncap < len + chunk + 1) ncap *= 2; | ||
| 217 | + nb = (char *)realloc(buf, ncap); | ||
| 218 | + if (!nb) { free(buf); sx_pclose(fp); return NULL; } | ||
| 219 | + buf = nb; | ||
| 220 | + cap = ncap; | ||
| 221 | + } | ||
| 222 | + memcpy(buf + len, tmp, chunk); | ||
| 223 | + len += chunk; | ||
| 224 | + } | ||
| 225 | + if (!buf) { | ||
| 226 | + buf = (char *)malloc(1); | ||
| 227 | + if (!buf) { sx_pclose(fp); return NULL; } | ||
| 228 | + cap = 1; | ||
| 229 | + } | ||
| 230 | + buf[len] = '\0'; | ||
| 231 | + | ||
| 232 | + status = sx_pclose(fp); | ||
| 233 | +#if defined(_WIN32) | ||
| 234 | + if (exit_code) *exit_code = status; | ||
| 235 | +#else | ||
| 236 | + if (exit_code) { | ||
| 237 | + if (WIFEXITED(status)) *exit_code = WEXITSTATUS(status); | ||
| 238 | + else *exit_code = -1; | ||
| 239 | + } | ||
| 240 | +#endif | ||
| 241 | + return buf; | ||
| 242 | +} | ||
| 243 | + | ||
| 244 | +/* ------------------------------------------------------------------ */ | ||
| 245 | +/* Runtime detection */ | ||
| 246 | +/* ------------------------------------------------------------------ */ | ||
| 247 | + | ||
| 248 | +static int path_has_exec(const char *name) | ||
| 249 | +{ | ||
| 250 | + const char *env = getenv("PATH"); | ||
| 251 | + char candidate[1024]; | ||
| 252 | + | ||
| 253 | + if (!env) return 0; | ||
| 254 | + while (*env) { | ||
| 255 | + const char *end = strchr(env, SX_PATH_SEP); | ||
| 256 | + size_t dlen = end ? (size_t)(end - env) : strlen(env); | ||
| 257 | + if (dlen > 0 && dlen + strlen(name) + 2 < sizeof(candidate)) { | ||
| 258 | + memcpy(candidate, env, dlen); | ||
| 259 | + candidate[dlen] = '\0'; | ||
| 260 | +#if defined(_WIN32) | ||
| 261 | + snprintf(candidate + dlen, sizeof(candidate) - dlen, "\\%s.exe", name); | ||
| 262 | +#else | ||
| 263 | + snprintf(candidate + dlen, sizeof(candidate) - dlen, "/%s", name); | ||
| 264 | +#endif | ||
| 265 | + if (sx_access(candidate, SX_X_OK) == 0) return 1; | ||
| 266 | + } | ||
| 267 | + if (!end) break; | ||
| 268 | + env = end + 1; | ||
| 269 | + } | ||
| 270 | + return 0; | ||
| 271 | +} | ||
| 272 | + | ||
| 273 | +/* Resolve the container runtime. Returns 1 when something is usable. */ | ||
| 274 | +static int detect_runtime(char *bin, size_t binsz, char *label, size_t labelsz) | ||
| 275 | +{ | ||
| 276 | + const char *ovr = getenv("DOCKER_BIN"); | ||
| 277 | + | ||
| 278 | + bin[0] = '\0'; | ||
| 279 | + label[0] = '\0'; | ||
| 280 | + | ||
| 281 | + if (ovr && *ovr) { | ||
| 282 | + if (!valid_runtime_path(ovr)) return 0; | ||
| 283 | + snprintf(bin, binsz, "%s", ovr); | ||
| 284 | + snprintf(label, labelsz, "custom"); | ||
| 285 | + return 1; | ||
| 286 | + } | ||
| 287 | + if (path_has_exec("docker")) { | ||
| 288 | + snprintf(bin, binsz, "docker"); | ||
| 289 | + snprintf(label, labelsz, "docker"); | ||
| 290 | + return 1; | ||
| 291 | + } | ||
| 292 | + if (path_has_exec("podman")) { | ||
| 293 | + snprintf(bin, binsz, "podman"); | ||
| 294 | + snprintf(label, labelsz, "podman"); | ||
| 295 | + return 1; | ||
| 296 | + } | ||
| 297 | + return 0; | ||
| 298 | +} | ||
| 299 | + | ||
| 300 | +/* ------------------------------------------------------------------ */ | ||
| 301 | +/* Container list */ | ||
| 302 | +/* ------------------------------------------------------------------ */ | ||
| 303 | + | ||
| 304 | +typedef struct { | ||
| 305 | + char id[80]; | ||
| 306 | + char name[192]; | ||
| 307 | + char image[192]; | ||
| 308 | + char state[32]; | ||
| 309 | + char status[192]; | ||
| 310 | + char ports[512]; | ||
| 311 | + char cpu[32]; | ||
| 312 | + char mem[96]; | ||
| 313 | +} container_t; | ||
| 314 | + | ||
| 315 | +static container_t g_containers[MAX_CONTAINERS]; | ||
| 316 | +static int g_container_count; | ||
| 317 | + | ||
| 318 | +/* Split on '|' in place into up to max fields. */ | ||
| 319 | +static int split_pipe(char *line, char **out, int max) | ||
| 320 | +{ | ||
| 321 | + int n = 0; | ||
| 322 | + char *p = line; | ||
| 323 | + if (max <= 0) return 0; | ||
| 324 | + out[n++] = p; | ||
| 325 | + while (*p && n < max) { | ||
| 326 | + if (*p == '|') { | ||
| 327 | + *p = '\0'; | ||
| 328 | + out[n++] = p + 1; | ||
| 329 | + } | ||
| 330 | + p++; | ||
| 331 | + } | ||
| 332 | + /* consume the remainder of the last field up to a newline */ | ||
| 333 | + if (n > 0) { | ||
| 334 | + char *e = out[n - 1]; | ||
| 335 | + while (*e && *e != '\n' && *e != '\r') e++; | ||
| 336 | + *e = '\0'; | ||
| 337 | + } | ||
| 338 | + return n; | ||
| 339 | +} | ||
| 340 | + | ||
| 341 | +static void copy_field(char *dst, size_t dstsz, const char *src) | ||
| 342 | +{ | ||
| 343 | + size_t i = 0; | ||
| 344 | + if (!dst || dstsz == 0) return; | ||
| 345 | + if (!src) { dst[0] = '\0'; return; } | ||
| 346 | + while (src[i] && i + 1 < dstsz) { dst[i] = src[i]; i++; } | ||
| 347 | + dst[i] = '\0'; | ||
| 348 | +} | ||
| 349 | + | ||
| 350 | +/* Parse `ps -a` output into g_containers. Returns line count parsed. */ | ||
| 351 | +static int parse_ps(const char *text) | ||
| 352 | +{ | ||
| 353 | + const char *p = text; | ||
| 354 | + int count = 0; | ||
| 355 | + | ||
| 356 | + g_container_count = 0; | ||
| 357 | + while (*p && g_container_count < MAX_CONTAINERS) { | ||
| 358 | + char line[1600]; | ||
| 359 | + size_t i = 0; | ||
| 360 | + char *fields[6]; | ||
| 361 | + int nf; | ||
| 362 | + | ||
| 363 | + while (*p && *p != '\n' && i + 1 < sizeof(line)) line[i++] = *p++; | ||
| 364 | + line[i] = '\0'; | ||
| 365 | + while (*p == '\n' || *p == '\r') p++; | ||
| 366 | + | ||
| 367 | + if (i == 0) continue; | ||
| 368 | + /* skip a header row if the runtime emitted one */ | ||
| 369 | + if (strncmp(line, "CONTAINER ID", 12) == 0) continue; | ||
| 370 | + | ||
| 371 | + nf = split_pipe(line, fields, 6); | ||
| 372 | + if (nf < 2) continue; | ||
| 373 | + | ||
| 374 | + { | ||
| 375 | + container_t *c = &g_containers[g_container_count]; | ||
| 376 | + memset(c, 0, sizeof(*c)); | ||
| 377 | + copy_field(c->id, sizeof(c->id), fields[0]); | ||
| 378 | + copy_field(c->name, sizeof(c->name), nf > 1 ? fields[1] : ""); | ||
| 379 | + copy_field(c->image, sizeof(c->image), nf > 2 ? fields[2] : ""); | ||
| 380 | + copy_field(c->state, sizeof(c->state), nf > 3 ? fields[3] : ""); | ||
| 381 | + copy_field(c->status, sizeof(c->status), nf > 4 ? fields[4] : ""); | ||
| 382 | + copy_field(c->ports, sizeof(c->ports), nf > 5 ? fields[5] : ""); | ||
| 383 | + g_container_count++; | ||
| 384 | + count++; | ||
| 385 | + } | ||
| 386 | + } | ||
| 387 | + return count; | ||
| 388 | +} | ||
| 389 | + | ||
| 390 | +/* Merge `stats --no-stream --format {{.ID}}|{{.CPUPerc}}|{{.MemUsage}}`. */ | ||
| 391 | +static void merge_stats(const char *text) | ||
| 392 | +{ | ||
| 393 | + const char *p = text; | ||
| 394 | + while (*p) { | ||
| 395 | + char line[600]; | ||
| 396 | + size_t i = 0; | ||
| 397 | + char *fields[3]; | ||
| 398 | + int nf, k; | ||
| 399 | + | ||
| 400 | + while (*p && *p != '\n' && i + 1 < sizeof(line)) line[i++] = *p++; | ||
| 401 | + line[i] = '\0'; | ||
| 402 | + while (*p == '\n' || *p == '\r') p++; | ||
| 403 | + if (i == 0) continue; | ||
| 404 | + | ||
| 405 | + nf = split_pipe(line, fields, 3); | ||
| 406 | + if (nf < 3) continue; | ||
| 407 | + | ||
| 408 | + for (k = 0; k < g_container_count; k++) { | ||
| 409 | + if (strncmp(g_containers[k].id, fields[0], strlen(fields[0])) == 0 || | ||
| 410 | + strcmp(g_containers[k].id, fields[0]) == 0) { | ||
| 411 | + copy_field(g_containers[k].cpu, sizeof(g_containers[k].cpu), fields[1]); | ||
| 412 | + copy_field(g_containers[k].mem, sizeof(g_containers[k].mem), fields[2]); | ||
| 413 | + break; | ||
| 414 | + } | ||
| 415 | + } | ||
| 416 | + } | ||
| 417 | +} | ||
| 418 | + | ||
| 419 | +static int container_is(const container_t *c, const char *state) | ||
| 420 | +{ | ||
| 421 | + return strcmp(c->state, state) == 0; | ||
| 422 | +} | ||
| 423 | + | ||
| 424 | +/* ------------------------------------------------------------------ */ | ||
| 425 | +/* Modes */ | ||
| 426 | +/* ------------------------------------------------------------------ */ | ||
| 427 | + | ||
| 428 | +static int mode_meta(void) | ||
| 429 | +{ | ||
| 430 | + puts("{\"name\":\"docker\",\"desc\":\"Containers\"}"); | ||
| 431 | + return 0; | ||
| 432 | +} | ||
| 433 | + | ||
| 434 | +static void json_header(void) | ||
| 435 | +{ | ||
| 436 | + /* Deliberately no Content-Length — the server owns framing. */ | ||
| 437 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 438 | + "Cache-Control: no-store\r\n" | ||
| 439 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 440 | +} | ||
| 441 | + | ||
| 442 | +static void json_header_status(const char *status_line) | ||
| 443 | +{ | ||
| 444 | + fputs("Status: ", stdout); | ||
| 445 | + fputs(status_line, stdout); | ||
| 446 | + fputs("\r\n", stdout); | ||
| 447 | + json_header(); | ||
| 448 | +} | ||
| 449 | + | ||
| 450 | +/* Emit the runtime block (shared by info + list). */ | ||
| 451 | +static void emit_runtime_block(const char *bin, const char *label, int available) | ||
| 452 | +{ | ||
| 453 | + fputs("\"runtime\":{", stdout); | ||
| 454 | + fputs("\"available\":", stdout); | ||
| 455 | + fputs(available ? "true" : "false", stdout); | ||
| 456 | + fputs(",\"bin\":", stdout); json_str(available ? bin : ""); | ||
| 457 | + fputs(",\"label\":", stdout); json_str(available ? label : ""); | ||
| 458 | + fputs("}", stdout); | ||
| 459 | +} | ||
| 460 | + | ||
| 461 | +static int mode_json(const char *qs, const char *body, int is_post) | ||
| 462 | +{ | ||
| 463 | + char action[64]; | ||
| 464 | + char cid[192]; | ||
| 465 | + char op[32]; | ||
| 466 | + char format[32]; | ||
| 467 | + | ||
| 468 | + char bin[512], label[64]; | ||
| 469 | + int available; | ||
| 470 | + | ||
| 471 | + action[0] = cid[0] = op[0] = format[0] = '\0'; | ||
| 472 | + get_query_val(qs, "action", action, sizeof(action)); | ||
| 473 | + get_query_val(qs, "cid", cid, sizeof(cid)); | ||
| 474 | + get_query_val(qs, "op", op, sizeof(op)); | ||
| 475 | + get_query_val(qs, "format", format, sizeof(format)); | ||
| 476 | + | ||
| 477 | + /* fall back to POST body parameters when the query is empty */ | ||
| 478 | + if (body && *body) { | ||
| 479 | + if (!action[0]) get_query_val(body, "action", action, sizeof(action)); | ||
| 480 | + if (!cid[0]) get_query_val(body, "cid", cid, sizeof(cid)); | ||
| 481 | + if (!op[0]) get_query_val(body, "op", op, sizeof(op)); | ||
| 482 | + if (!format[0]) get_query_val(body, "format", format, sizeof(format)); | ||
| 483 | + } | ||
| 484 | + | ||
| 485 | + available = detect_runtime(bin, sizeof(bin), label, sizeof(label)); | ||
| 486 | + | ||
| 487 | + /* ---- control (POST only) ---- */ | ||
| 488 | + if (strcmp(action, "control") == 0) { | ||
| 489 | + int code = 0; | ||
| 490 | + char *out; | ||
| 491 | + | ||
| 492 | + if (!is_post) { | ||
| 493 | + json_header_status("405 Method Not Allowed"); | ||
| 494 | + fputs("{\"ok\":false,\"error\":\"control_requires_post\"," | ||
| 495 | + "\"hint\":\"POST ?action=control&op=start|stop|restart&cid=<id>\"}\n", stdout); | ||
| 496 | + return 0; | ||
| 497 | + } | ||
| 498 | + if (!available) { | ||
| 499 | + json_header_status("503 Service Unavailable"); | ||
| 500 | + fputs("{\"ok\":false,\"error\":\"runtime_available\",\"runtime\":{\"available\":false}," | ||
| 501 | + "\"message\":\"Neither docker nor podman was found on this node\"}\n", stdout); | ||
| 502 | + return 0; | ||
| 503 | + } | ||
| 504 | + if (!valid_op(op)) { | ||
| 505 | + json_header_status("400 Bad Request"); | ||
| 506 | + fputs("{\"ok\":false,\"error\":\"invalid_op\"," | ||
| 507 | + "\"supported\":[\"start\",\"stop\",\"restart\"]}\n", stdout); | ||
| 508 | + return 0; | ||
| 509 | + } | ||
| 510 | + if (!valid_cid(cid)) { | ||
| 511 | + json_header_status("400 Bad Request"); | ||
| 512 | + fputs("{\"ok\":false,\"error\":\"invalid_cid\"," | ||
| 513 | + "\"message\":\"cid must match [A-Za-z0-9_.-]{1,128} and may not start with - or .\"}\n", | ||
| 514 | + stdout); | ||
| 515 | + return 0; | ||
| 516 | + } | ||
| 517 | + { | ||
| 518 | + char cmd[1024]; | ||
| 519 | + snprintf(cmd, sizeof(cmd), "'%s' %s %s 2>&1", bin, op, cid); | ||
| 520 | + out = run_capture(cmd, &code); | ||
| 521 | + } | ||
| 522 | + { | ||
| 523 | + char ts[64]; | ||
| 524 | + utc_now(ts, sizeof(ts)); | ||
| 525 | + if (code != 0) json_header_status("409 Conflict"); | ||
| 526 | + else json_header(); | ||
| 527 | + fputs("{\"ok\":", stdout); | ||
| 528 | + fputs(code == 0 ? "true" : "false", stdout); | ||
| 529 | + fputs(",\"action\":\"control\",\"op\":", stdout); json_str(op); | ||
| 530 | + fputs(",\"cid\":", stdout); json_str(cid); | ||
| 531 | + printf(",\"exit_code\":%d", code); | ||
| 532 | + fputs(",\"output\":", stdout); json_str(out ? out : ""); | ||
| 533 | + fputs(",\"utc\":", stdout); json_str(ts); | ||
| 534 | + fputs("}\n", stdout); | ||
| 535 | + } | ||
| 536 | + free(out); | ||
| 537 | + return 0; | ||
| 538 | + } | ||
| 539 | + | ||
| 540 | + /* ---- logs ---- */ | ||
| 541 | + if (strcmp(action, "logs") == 0) { | ||
| 542 | + if (!valid_cid(cid)) { | ||
| 543 | + json_header_status("400 Bad Request"); | ||
| 544 | + fputs("{\"ok\":false,\"error\":\"invalid_cid\",\"cid\":", stdout); | ||
| 545 | + json_str(cid); | ||
| 546 | + fputs("}\n", stdout); | ||
| 547 | + return 0; | ||
| 548 | + } | ||
| 549 | + if (!available) { | ||
| 550 | + json_header_status("503 Service Unavailable"); | ||
| 551 | + fputs("{\"ok\":false,\"error\":\"runtime_available\",\"runtime\":{\"available\":false}," | ||
| 552 | + "\"message\":\"Neither docker nor podman was found on this node\"}\n", stdout); | ||
| 553 | + return 0; | ||
| 554 | + } | ||
| 555 | + { | ||
| 556 | + char cmd[1024]; | ||
| 557 | + char *out; | ||
| 558 | + int code = 0; | ||
| 559 | + const char *p; | ||
| 560 | + | ||
| 561 | + snprintf(cmd, sizeof(cmd), "'%s' logs --tail %d %s 2>&1", bin, LOG_TAIL, cid); | ||
| 562 | + out = run_capture(cmd, &code); | ||
| 563 | + | ||
| 564 | + if (code != 0) json_header_status("409 Conflict"); | ||
| 565 | + else json_header(); | ||
| 566 | + fputs("{\"ok\":", stdout); | ||
| 567 | + fputs(code == 0 ? "true" : "false", stdout); | ||
| 568 | + fputs(",\"action\":\"logs\",\"cid\":", stdout); json_str(cid); | ||
| 569 | + printf(",\"tail\":%d,\"exit_code\":%d", LOG_TAIL, code); | ||
| 570 | + fputs(",\"lines\":[", stdout); | ||
| 571 | + if (out) { | ||
| 572 | + int first = 1; | ||
| 573 | + p = out; | ||
| 574 | + while (*p) { | ||
| 575 | + char line[2048]; | ||
| 576 | + size_t i = 0; | ||
| 577 | + while (*p && *p != '\n' && i + 1 < sizeof(line)) line[i++] = *p++; | ||
| 578 | + line[i] = '\0'; | ||
| 579 | + while (*p == '\n' || *p == '\r') p++; | ||
| 580 | + if (!first) fputs(",", stdout); | ||
| 581 | + first = 0; | ||
| 582 | + json_str(line); | ||
| 583 | + } | ||
| 584 | + } | ||
| 585 | + fputs("],\"text\":", stdout); json_str(out ? out : ""); | ||
| 586 | + fputs("}\n", stdout); | ||
| 587 | + free(out); | ||
| 588 | + } | ||
| 589 | + return 0; | ||
| 590 | + } | ||
| 591 | + | ||
| 592 | + /* ---- info / list / unknown ---- */ | ||
| 593 | + if (action[0] && strcmp(action, "info") != 0 && strcmp(action, "list") != 0) { | ||
| 594 | + json_header_status("400 Bad Request"); | ||
| 595 | + fputs("{\"ok\":false,\"error\":\"unknown_action\",\"action\":", stdout); | ||
| 596 | + json_str(action); | ||
| 597 | + fputs(",\"supported\":[\"list\",\"info\",\"logs\",\"control\"]}\n", stdout); | ||
| 598 | + return 0; | ||
| 599 | + } | ||
| 600 | + | ||
| 601 | + if (strcmp(action, "info") == 0 && strcmp(format, "list") == 0) { | ||
| 602 | + /* not meaningful; treat as list */ | ||
| 603 | + } | ||
| 604 | + | ||
| 605 | + if (strcmp(action, "info") == 0) { | ||
| 606 | + char ts[64]; | ||
| 607 | + utc_now(ts, sizeof(ts)); | ||
| 608 | + json_header(); | ||
| 609 | + fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\"," | ||
| 610 | + "\"slug\":\"" PLUGIN_SLUG "\",\"version\":\"" PLUGIN_VER "\",", stdout); | ||
| 611 | + emit_runtime_block(bin, label, available); | ||
| 612 | + printf(",\"pid\":%ld", node_pid()); | ||
| 613 | + fputs(",\"utc\":", stdout); json_str(ts); | ||
| 614 | + fputs(",\"supported\":[\"list\",\"info\",\"logs\",\"control\"]," | ||
| 615 | + "\"control\":{\"method\":\"POST\",\"ops\":[\"start\",\"stop\",\"restart\"]}}\n", stdout); | ||
| 616 | + return 0; | ||
| 617 | + } | ||
| 618 | + | ||
| 619 | + /* list */ | ||
| 620 | + { | ||
| 621 | + char *psout = NULL; | ||
| 622 | + char *statsout = NULL; | ||
| 623 | + int pscode = 0, statscode = 0; | ||
| 624 | + char ts[64]; | ||
| 625 | + int total = 0, running = 0, exited = 0, paused = 0, other = 0; | ||
| 626 | + int i; | ||
| 627 | + | ||
| 628 | + if (available) { | ||
| 629 | + char cmd[1024]; | ||
| 630 | + snprintf(cmd, sizeof(cmd), | ||
| 631 | + "'%s' ps -a --format '{{.ID}}|{{.Names}}|{{.Image}}|{{.State}}|{{.Status}}|{{.Ports}}' 2>&1", | ||
| 632 | + bin); | ||
| 633 | + psout = run_capture(cmd, &pscode); | ||
| 634 | + if (psout && pscode == 0) parse_ps(psout); | ||
| 635 | + | ||
| 636 | + snprintf(cmd, sizeof(cmd), | ||
| 637 | + "'%s' stats --no-stream --format '{{.ID}}|{{.CPUPerc}}|{{.MemUsage}}' 2>&1", | ||
| 638 | + bin); | ||
| 639 | + statsout = run_capture(cmd, &statscode); | ||
| 640 | + if (statsout && statscode == 0 && g_container_count > 0) merge_stats(statsout); | ||
| 641 | + } | ||
| 642 | + | ||
| 643 | + for (i = 0; i < g_container_count; i++) { | ||
| 644 | + total++; | ||
| 645 | + if (container_is(&g_containers[i], "running")) running++; | ||
| 646 | + else if (container_is(&g_containers[i], "exited")) exited++; | ||
| 647 | + else if (container_is(&g_containers[i], "paused")) paused++; | ||
| 648 | + else other++; | ||
| 649 | + } | ||
| 650 | + | ||
| 651 | + utc_now(ts, sizeof(ts)); | ||
| 652 | + json_header(); | ||
| 653 | + fputs("{\"ok\":true,\"action\":\"list\",\"plugin\":\"" PLUGIN_ID "\"," | ||
| 654 | + "\"slug\":\"" PLUGIN_SLUG "\",\"version\":\"" PLUGIN_VER "\",", stdout); | ||
| 655 | + emit_runtime_block(bin, label, available); | ||
| 656 | + if (!available) { | ||
| 657 | + fputs(",\"message\":\"Neither docker nor podman was found on this node. " | ||
| 658 | + "Install a container runtime, or set DOCKER_BIN to an explicit binary path.\"", stdout); | ||
| 659 | + } else if (psout && pscode != 0) { | ||
| 660 | + fputs(",\"daemon_available\":false,\"error\":", stdout); | ||
| 661 | + json_str(psout); | ||
| 662 | + } else { | ||
| 663 | + fputs(",\"daemon_available\":true", stdout); | ||
| 664 | + } | ||
| 665 | + fputs(",\"utc\":", stdout); json_str(ts); | ||
| 666 | + printf(",\"count\":%d,\"summary\":{\"total\":%d,\"running\":%d,\"exited\":%d," | ||
| 667 | + "\"paused\":%d,\"other\":%d}", g_container_count, total, running, exited, paused, other); | ||
| 668 | + fputs(",\"containers\":[", stdout); | ||
| 669 | + for (i = 0; i < g_container_count; i++) { | ||
| 670 | + container_t *c = &g_containers[i]; | ||
| 671 | + if (i) fputs(",", stdout); | ||
| 672 | + fputs("{", stdout); | ||
| 673 | + fputs("\"id\":", stdout); json_str(c->id); | ||
| 674 | + fputs(",\"short\":", stdout); json_str(c->id[0] ? c->id : ""); | ||
| 675 | + fputs(",\"name\":", stdout); json_str(c->name); | ||
| 676 | + fputs(",\"image\":", stdout); json_str(c->image); | ||
| 677 | + fputs(",\"state\":", stdout); json_str(c->state); | ||
| 678 | + fputs(",\"status\":", stdout);json_str(c->status); | ||
| 679 | + fputs(",\"ports\":", stdout); json_str(c->ports); | ||
| 680 | + fputs(",\"cpu\":", stdout); json_str(c->cpu); | ||
| 681 | + fputs(",\"mem\":", stdout); json_str(c->mem); | ||
| 682 | + fputs("}", stdout); | ||
| 683 | + } | ||
| 684 | + fputs("]}\n", stdout); | ||
| 685 | + | ||
| 686 | + free(psout); | ||
| 687 | + free(statsout); | ||
| 688 | + } | ||
| 689 | + return 0; | ||
| 690 | +} | ||
| 691 | + | ||
| 692 | +/* ------------------------------------------------------------------ */ | ||
| 693 | +/* HTML UI */ | ||
| 694 | +/* ------------------------------------------------------------------ */ | ||
| 695 | + | ||
| 696 | +static int mode_html(int embed) | ||
| 697 | +{ | ||
| 698 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 699 | + "Cache-Control: no-store\r\n" | ||
| 700 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 701 | + | ||
| 702 | + fputs("<!DOCTYPE html>\n<html lang='en'><head><meta charset='utf-8'>" | ||
| 703 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | ||
| 704 | + "<title>docker</title><style>", stdout); | ||
| 705 | + | ||
| 706 | + fputs( | ||
| 707 | +":root{color-scheme:dark light;" | ||
| 708 | + "--bg:#0d0d10;--surface:#16161a;--surface2:#1e1e24;--text:#f5f5f7;" | ||
| 709 | + "--muted:#8e8e96;--line:rgba(255,255,255,.11);--accent:#0a84ff;" | ||
| 710 | + "--accent2:#30d158;--warn:#ffd60a;--danger:#ff453a;" | ||
| 711 | + "--mono:ui-monospace,SFMono-Regular,Menlo,monospace}" | ||
| 712 | +"html[data-theme=light]{--bg:#f4f4f7;--surface:#ffffff;--surface2:#f0f0f4;" | ||
| 713 | + "--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}" | ||
| 714 | +"*{box-sizing:border-box}" | ||
| 715 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--text);" | ||
| 716 | + "font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;" | ||
| 717 | + "font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}" | ||
| 718 | +".wrap{max-width:1080px;margin:0 auto}" | ||
| 719 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | ||
| 720 | +".title{font-size:20px;font-weight:700;margin:0}" | ||
| 721 | +".pill{font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;" | ||
| 722 | + "background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}" | ||
| 723 | +".pill.on{color:var(--accent2);border-color:rgba(48,209,88,.4)}" | ||
| 724 | +".pill.off{color:var(--danger);border-color:rgba(255,69,58,.4)}" | ||
| 725 | +".spacer{flex:1}" | ||
| 726 | +".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | ||
| 727 | + "padding:16px;margin-bottom:14px}" | ||
| 728 | +".card h2{margin:0 0 10px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;" | ||
| 729 | + "color:var(--muted);font-weight:600}" | ||
| 730 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px}" | ||
| 731 | +".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;padding:10px 12px}" | ||
| 732 | +".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" | ||
| 733 | +".kpi .v{font-size:20px;font-weight:700;font-family:var(--mono);margin-top:2px}" | ||
| 734 | +".kpi .v.run{color:var(--accent2)}.kpi .v.exit{color:var(--muted)}" | ||
| 735 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;" | ||
| 736 | + "padding:7px 14px;font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | ||
| 737 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | ||
| 738 | +"button.danger{background:var(--danger)}" | ||
| 739 | +"button.sm{padding:4px 10px;font-size:12px}" | ||
| 740 | +"button:active{transform:scale(.98)}" | ||
| 741 | +"button:disabled{opacity:.45;cursor:not-allowed}" | ||
| 742 | +"input,select{background:var(--surface2);border:1px solid var(--line);" | ||
| 743 | + "border-radius:10px;padding:8px 12px;color:var(--text);font-size:13px;" | ||
| 744 | + "font-family:inherit}" | ||
| 745 | +"input{flex:1;min-width:140px;font-family:var(--mono)}" | ||
| 746 | +"input:focus,select:focus{outline:2px solid var(--accent);outline-offset:-1px}" | ||
| 747 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | ||
| 748 | +"table{width:100%;border-collapse:collapse;font-size:13px;margin-top:10px}" | ||
| 749 | +"th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;" | ||
| 750 | + "color:var(--muted);font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);" | ||
| 751 | + "white-space:nowrap}" | ||
| 752 | +"td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:middle}" | ||
| 753 | +"td.mono{font-family:var(--mono);font-size:12px;word-break:break-all}" | ||
| 754 | +"tr:last-child td{border-bottom:0}" | ||
| 755 | +".state{font-size:11px;font-weight:700;padding:2px 8px;border-radius:999px;" | ||
| 756 | + "text-transform:uppercase;letter-spacing:.04em;display:inline-block}" | ||
| 757 | +".state.running{background:rgba(48,209,88,.16);color:var(--accent2)}" | ||
| 758 | +".state.exited{background:rgba(255,255,255,.08);color:var(--muted)}" | ||
| 759 | +".state.paused{background:rgba(255,214,10,.16);color:var(--warn)}" | ||
| 760 | +".state.created,.state.restarting,.state.dead{background:rgba(255,69,58,.16);color:var(--danger)}" | ||
| 761 | +".acts{display:flex;gap:6px;flex-wrap:wrap}" | ||
| 762 | +".tblwrap{overflow-x:auto}" | ||
| 763 | +"pre{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | ||
| 764 | + "padding:12px;overflow:auto;font-family:var(--mono);font-size:12px;margin:0;" | ||
| 765 | + "max-height:380px;white-space:pre-wrap;word-break:break-word}" | ||
| 766 | +".muted{color:var(--muted)}" | ||
| 767 | +".empty{padding:22px 8px;text-align:center;color:var(--muted)}" | ||
| 768 | +".hide{display:none}" | ||
| 769 | +"@media(max-width:640px){body{padding:10px}.card{padding:12px}" | ||
| 770 | + "th:nth-child(3),td:nth-child(3),th:nth-child(5),td:nth-child(5){display:none}}" | ||
| 771 | +"</style></head><body><div class='wrap'>", stdout); | ||
| 772 | + | ||
| 773 | + if (!embed) | ||
| 774 | + fputs("<div class='top'><a href='/' style='color:var(--accent);text-decoration:none;" | ||
| 775 | + "font-weight:600'>← Back to Bot</a></div>", stdout); | ||
| 776 | + | ||
| 777 | + fputs("<div class='top'><h1 class='title'>docker</h1>" | ||
| 778 | + "<span class='pill'>" PLUGIN_VER "</span>" | ||
| 779 | + "<span class='pill' id='badge'>connecting</span>" | ||
| 780 | + "<span class='spacer'></span>" | ||
| 781 | + "<button class='ghost' id='themeBtn' type='button'>Theme</button>" | ||
| 782 | + "<button class='ghost' id='reloadBtn' type='button'>Refresh</button></div>", stdout); | ||
| 783 | + | ||
| 784 | + /* KPIs */ | ||
| 785 | + fputs("<div class='card'><h2>Containers</h2><div class='grid'>" | ||
| 786 | + "<div class='kpi'><div class='k'>total</div><div class='v' id='k-total'>—</div></div>" | ||
| 787 | + "<div class='kpi'><div class='k'>running</div><div class='v run' id='k-run'>—</div></div>" | ||
| 788 | + "<div class='kpi'><div class='k'>exited</div><div class='v exit' id='k-exit'>—</div></div>" | ||
| 789 | + "<div class='kpi'><div class='k'>paused</div><div class='v' id='k-pause'>—</div></div>" | ||
| 790 | + "<div class='kpi'><div class='k'>runtime</div><div class='v' id='k-rt'>—</div></div>" | ||
| 791 | + "</div>" | ||
| 792 | + "<div class='row' style='margin-top:12px'>" | ||
| 793 | + "<input id='q' type='text' placeholder='search name, image, id, port'>" | ||
| 794 | + "<select id='state'><option value=''>all states</option>" | ||
| 795 | + "<option value='running'>running</option><option value='exited'>exited</option>" | ||
| 796 | + "<option value='paused'>paused</option><option value='created'>created</option>" | ||
| 797 | + "</select>" | ||
| 798 | + "<button id='refreshBtn' type='button'>Apply</button></div>" | ||
| 799 | + "<div id='note' class='muted' style='margin-top:10px'></div>" | ||
| 800 | + "<div class='tblwrap'><table><thead><tr>" | ||
| 801 | + "<th>ID</th><th>Name</th><th>Image</th><th>State</th><th>CPU</th><th>Mem</th><th>Actions</th>" | ||
| 802 | + "</tr></thead><tbody id='rows'></tbody></table></div>" | ||
| 803 | + "<div id='empty' class='empty hide'>No containers to show.</div>" | ||
| 804 | + "</div>", stdout); | ||
| 805 | + | ||
| 806 | + /* log viewer */ | ||
| 807 | + fputs("<div class='card hide' id='logCard'><h2 id='logTitle'>Logs</h2>" | ||
| 808 | + "<pre id='logBody'>loading…</pre>" | ||
| 809 | + "<div class='row' style='margin-top:10px'>" | ||
| 810 | + "<button class='ghost sm' id='logReload' type='button'>Reload</button>" | ||
| 811 | + "<button class='ghost sm' id='logClose' type='button'>Close</button></div></div>", stdout); | ||
| 812 | + | ||
| 813 | + /* footer */ | ||
| 814 | + fputs("<div class='card'><h2>About this plugin</h2>" | ||
| 815 | + "<p class='muted' style='margin:0 0 8px'>Local node only. Reads " | ||
| 816 | + "<code>docker</code> or <code>podman</code> on this machine and makes zero " | ||
| 817 | + "outbound network requests. Source is MIT licensed.</p>" | ||
| 818 | + "<p class='muted' style='margin:0'><code>list</code>, <code>logs</code> and " | ||
| 819 | + "<code>control</code> are the only supported actions; container identifiers are " | ||
| 820 | + "validated before they ever reach a command line.</p></div>", stdout); | ||
| 821 | + | ||
| 822 | + /* script */ | ||
| 823 | + fputs( | ||
| 824 | +"<script>\n" | ||
| 825 | +"(function(){\n" | ||
| 826 | +" var q = new URLSearchParams(location.search);\n" | ||
| 827 | +" var HUB = q.get('plugin') || '';\n" | ||
| 828 | +" var node = q.get('node') || '';\n" | ||
| 829 | +" var sid = q.get('id') || '';\n" | ||
| 830 | +" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | ||
| 831 | +" localStorage.getItem('bot_active_pwd') || '';\n" | ||
| 832 | +"\n" | ||
| 833 | +" function base(){ return HUB ? '/plugins?plugin=' + HUB : '/plugin_docker'; }\n" | ||
| 834 | +" function withCtx(u){\n" | ||
| 835 | +" if (node) u += '&node=' + encodeURIComponent(node);\n" | ||
| 836 | +" if (sid) u += '&id=' + encodeURIComponent(sid);\n" | ||
| 837 | +" if (pwd) u += '&pwd=' + encodeURIComponent(pwd);\n" | ||
| 838 | +" return u;\n" | ||
| 839 | +" }\n" | ||
| 840 | +" function headers(extra){\n" | ||
| 841 | +" var h = extra || {};\n" | ||
| 842 | +" if (pwd) h['X-Bot-Password'] = pwd;\n" | ||
| 843 | +" return h;\n" | ||
| 844 | +" }\n" | ||
| 845 | +" function get(action, extra){\n" | ||
| 846 | +" var u = withCtx(base() + '?action=' + encodeURIComponent(action) + (extra || ''));\n" | ||
| 847 | +" return fetch(u, { headers: headers() }).then(function(r){ return r.json(); });\n" | ||
| 848 | +" }\n" | ||
| 849 | +" function post(action, form){\n" | ||
| 850 | +" var u = withCtx(base() + '?action=' + encodeURIComponent(action));\n" | ||
| 851 | +" return fetch(u, { method:'POST',\n" | ||
| 852 | +" headers: headers({'Content-Type':'application/x-www-form-urlencoded'}),\n" | ||
| 853 | +" body: form }).then(function(r){ return r.json(); });\n" | ||
| 854 | +" }\n" | ||
| 855 | +" function $(id){ return document.getElementById(id); }\n" | ||
| 856 | +" function txt(id, v){ var e = $(id); if (e) e.textContent = (v === undefined || v === null || v === '') ? '\\u2014' : String(v); }\n" | ||
| 857 | +" function el(tag, cls, text){\n" | ||
| 858 | +" var e = document.createElement(tag);\n" | ||
| 859 | +" if (cls) e.className = cls;\n" | ||
| 860 | +" if (text !== undefined && text !== null) e.textContent = String(text);\n" | ||
| 861 | +" return e;\n" | ||
| 862 | +" }\n" | ||
| 863 | +"\n" | ||
| 864 | +" var DATA = { containers: [], summary: {} };\n" | ||
| 865 | +" var LOG_CID = '', LOG_NAME = '';\n" | ||
| 866 | +"\n" | ||
| 867 | +" function theme(t){\n" | ||
| 868 | +" if (t) { document.documentElement.setAttribute('data-theme', t); localStorage.setItem('bot_theme', t); }\n" | ||
| 869 | +" }\n" | ||
| 870 | +" theme(localStorage.getItem('bot_theme') || 'dark');\n" | ||
| 871 | +" $('themeBtn').addEventListener('click', function(){\n" | ||
| 872 | +" theme(document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light');\n" | ||
| 873 | +" });\n" | ||
| 874 | +"\n" | ||
| 875 | +" function badge(ok, text){\n" | ||
| 876 | +" var b = $('badge');\n" | ||
| 877 | +" b.textContent = text;\n" | ||
| 878 | +" b.className = 'pill ' + (ok ? 'on' : 'off');\n" | ||
| 879 | +" }\n" | ||
| 880 | +"\n" | ||
| 881 | +" function matches(c){\n" | ||
| 882 | +" var s = ($('state').value || '').toLowerCase();\n" | ||
| 883 | +" if (s && (c.state || '').toLowerCase() !== s) return false;\n" | ||
| 884 | +" var k = ($('q').value || '').trim().toLowerCase();\n" | ||
| 885 | +" if (!k) return true;\n" | ||
| 886 | +" var hay = ((c.name||'') + ' ' + (c.image||'') + ' ' + (c.id||'') + ' ' + (c.ports||'')).toLowerCase();\n" | ||
| 887 | +" return hay.indexOf(k) >= 0;\n" | ||
| 888 | +" }\n" | ||
| 889 | +"\n" | ||
| 890 | +" function act(c, op){\n" | ||
| 891 | +" var label = op + ' ' + (c.name || c.id);\n" | ||
| 892 | +" if (op !== 'start' && !window.confirm(label + '?')) return;\n" | ||
| 893 | +" post('control', 'op=' + encodeURIComponent(op) + '&cid=' + encodeURIComponent(c.id))\n" | ||
| 894 | +" .then(function(d){\n" | ||
| 895 | +" if (!d.ok) { $('note').textContent = (d.error || 'failed') + (d.output ? ': ' + d.output : ''); }\n" | ||
| 896 | +" else { $('note').textContent = op + ' ' + (c.name || c.id) + ' ok'; }\n" | ||
| 897 | +" refresh();\n" | ||
| 898 | +" })\n" | ||
| 899 | +" .catch(function(e){ $('note').textContent = 'request failed: ' + e; });\n" | ||
| 900 | +" }\n" | ||
| 901 | +"\n" | ||
| 902 | +" function openLogs(c){\n" | ||
| 903 | +" LOG_CID = c.id; LOG_NAME = c.name || c.id;\n" | ||
| 904 | +" $('logCard').classList.remove('hide');\n" | ||
| 905 | +" $('logTitle').textContent = 'Logs \\u2014 ' + LOG_NAME + ' (last 100 lines)';\n" | ||
| 906 | +" $('logBody').textContent = 'loading\\u2026';\n" | ||
| 907 | +" get('logs', '&cid=' + encodeURIComponent(c.id)).then(function(d){\n" | ||
| 908 | +" $('logBody').textContent = d.ok ? (d.text || '(empty)') : ('error: ' + (d.error || 'unknown'));\n" | ||
| 909 | +" }).catch(function(e){ $('logBody').textContent = 'request failed: ' + e; });\n" | ||
| 910 | +" }\n" | ||
| 911 | +"\n" | ||
| 912 | +" function render(){\n" | ||
| 913 | +" var tb = $('rows');\n" | ||
| 914 | +" while (tb.firstChild) tb.removeChild(tb.firstChild);\n" | ||
| 915 | +" var shown = 0;\n" | ||
| 916 | +" (DATA.containers || []).forEach(function(c){\n" | ||
| 917 | +" if (!matches(c)) return;\n" | ||
| 918 | +" shown++;\n" | ||
| 919 | +" var tr = el('tr');\n" | ||
| 920 | +" tr.appendChild(el('td', 'mono', (c.id || '').slice(0, 12)));\n" | ||
| 921 | +" tr.appendChild(el('td', '', c.name || ''));\n" | ||
| 922 | +" tr.appendChild(el('td', 'mono', c.image || ''));\n" | ||
| 923 | +" var tdState = el('td');\n" | ||
| 924 | +" tdState.appendChild(el('span', 'state ' + (c.state || '').toLowerCase(), c.state || ''));\n" | ||
| 925 | +" tr.appendChild(tdState);\n" | ||
| 926 | +" tr.appendChild(el('td', 'mono', c.cpu || '\\u2014'));\n" | ||
| 927 | +" tr.appendChild(el('td', 'mono', c.mem || '\\u2014'));\n" | ||
| 928 | +" var tdAct = el('td');\n" | ||
| 929 | +" var box = el('div', 'acts');\n" | ||
| 930 | +" function btn(op, cls){ var b = el('button', 'sm ' + cls, op);\n" | ||
| 931 | +" b.type = 'button'; b.addEventListener('click', function(){ act(c, op); }); return b; }\n" | ||
| 932 | +" function logBtn(){ var b = el('button', 'sm ghost', 'logs');\n" | ||
| 933 | +" b.type = 'button'; b.addEventListener('click', function(){ openLogs(c); }); return b; }\n" | ||
| 934 | +" var running = (c.state || '').toLowerCase() === 'running';\n" | ||
| 935 | +" if (running) {\n" | ||
| 936 | +" box.appendChild(btn('stop', 'danger'));\n" | ||
| 937 | +" box.appendChild(btn('restart', 'ghost'));\n" | ||
| 938 | +" } else {\n" | ||
| 939 | +" box.appendChild(btn('start', ''));\n" | ||
| 940 | +" }\n" | ||
| 941 | +" box.appendChild(logBtn());\n" | ||
| 942 | +" tdAct.appendChild(box);\n" | ||
| 943 | +" tr.appendChild(tdAct);\n" | ||
| 944 | +" tb.appendChild(tr);\n" | ||
| 945 | +" });\n" | ||
| 946 | +" $('empty').classList.toggle('hide', shown !== 0);\n" | ||
| 947 | +" }\n" | ||
| 948 | +"\n" | ||
| 949 | +" function refresh(){\n" | ||
| 950 | +" get('list').then(function(d){\n" | ||
| 951 | +" DATA = d;\n" | ||
| 952 | +" var s = d.summary || {};\n" | ||
| 953 | +" txt('k-total', s.total);\n" | ||
| 954 | +" txt('k-run', s.running);\n" | ||
| 955 | +" txt('k-exit', s.exited);\n" | ||
| 956 | +" txt('k-pause', s.paused);\n" | ||
| 957 | +" var rt = d.runtime || {};\n" | ||
| 958 | +" txt('k-rt', rt.available ? (rt.label || 'yes') : 'none');\n" | ||
| 959 | +" if (!rt.available) {\n" | ||
| 960 | +" badge(false, 'no runtime');\n" | ||
| 961 | +" $('note').textContent = d.message || 'neither docker nor podman found on this node';\n" | ||
| 962 | +" } else if (d.daemon_available === false) {\n" | ||
| 963 | +" badge(false, 'daemon down');\n" | ||
| 964 | +" $('note').textContent = d.error || 'runtime daemon is not reachable';\n" | ||
| 965 | +" } else {\n" | ||
| 966 | +" badge(true, rt.label || 'ready');\n" | ||
| 967 | +" $('note').textContent = (s.total || 0) + ' container(s) on this node';\n" | ||
| 968 | +" }\n" | ||
| 969 | +" render();\n" | ||
| 970 | +" }).catch(function(e){\n" | ||
| 971 | +" badge(false, 'error');\n" | ||
| 972 | +" $('note').textContent = 'request failed: ' + e;\n" | ||
| 973 | +" });\n" | ||
| 974 | +" }\n" | ||
| 975 | +"\n" | ||
| 976 | +" $('refreshBtn').addEventListener('click', refresh);\n" | ||
| 977 | +" $('reloadBtn').addEventListener('click', refresh);\n" | ||
| 978 | +" $('q').addEventListener('input', render);\n" | ||
| 979 | +" $('q').addEventListener('keydown', function(e){ if (e.key === 'Enter') refresh(); });\n" | ||
| 980 | +" $('state').addEventListener('change', render);\n" | ||
| 981 | +" $('logClose').addEventListener('click', function(){ $('logCard').classList.add('hide'); });\n" | ||
| 982 | +" $('logReload').addEventListener('click', function(){\n" | ||
| 983 | +" if (LOG_CID) get('logs', '&cid=' + encodeURIComponent(LOG_CID)).then(function(d){\n" | ||
| 984 | +" $('logBody').textContent = d.ok ? (d.text || '(empty)') : ('error: ' + (d.error || 'unknown'));\n" | ||
| 985 | +" });\n" | ||
| 986 | +" });\n" | ||
| 987 | +"\n" | ||
| 988 | +" refresh();\n" | ||
| 989 | +"})();\n" | ||
| 990 | +"</script></body></html>\n", stdout); | ||
| 991 | + return 0; | ||
| 992 | +} | ||
| 993 | + | ||
| 994 | +/* ------------------------------------------------------------------ */ | ||
| 995 | +/* POST body */ | ||
| 996 | +/* ------------------------------------------------------------------ */ | ||
| 997 | + | ||
| 998 | +static char *read_post_body(void) | ||
| 999 | +{ | ||
| 1000 | + const char *cl = getenv("CONTENT_LENGTH"); | ||
| 1001 | + long want; | ||
| 1002 | + size_t got = 0; | ||
| 1003 | + char *buf; | ||
| 1004 | + | ||
| 1005 | + if (!cl || !*cl) return NULL; | ||
| 1006 | + want = strtol(cl, NULL, 10); | ||
| 1007 | + if (want <= 0) return NULL; | ||
| 1008 | + if (want > 8192) want = 8192; | ||
| 1009 | + | ||
| 1010 | + buf = (char *)malloc((size_t)want + 1); | ||
| 1011 | + if (!buf) return NULL; | ||
| 1012 | + while (got < (size_t)want) { | ||
| 1013 | + size_t n = fread(buf + got, 1, (size_t)want - got, stdin); | ||
| 1014 | + if (n == 0) break; | ||
| 1015 | + got += n; | ||
| 1016 | + } | ||
| 1017 | + buf[got] = '\0'; | ||
| 1018 | + return buf; | ||
| 1019 | +} | ||
| 1020 | + | ||
| 1021 | +/* ------------------------------------------------------------------ */ | ||
| 1022 | +/* main */ | ||
| 1023 | +/* ------------------------------------------------------------------ */ | ||
| 1024 | + | ||
| 1025 | +static int is_post_request(void) | ||
| 1026 | +{ | ||
| 1027 | + const char *m = getenv("REQUEST_METHOD"); | ||
| 1028 | + return m && strcmp(m, "POST") == 0; | ||
| 1029 | +} | ||
| 1030 | + | ||
| 1031 | +int main(int argc, char **argv) | ||
| 1032 | +{ | ||
| 1033 | + const char *qs; | ||
| 1034 | + char *body = NULL; | ||
| 1035 | + | ||
| 1036 | + if (argc > 1) { | ||
| 1037 | + if (strcmp(argv[1], "--meta") == 0) return mode_meta(); | ||
| 1038 | + if (strcmp(argv[1], "--version") == 0) { puts(PLUGIN_VER); return 0; } | ||
| 1039 | + if (strcmp(argv[1], "--help") == 0) { | ||
| 1040 | + puts("plugin_docker " PLUGIN_VER); | ||
| 1041 | + puts("usage: plugin_docker [--meta|--version|--help]"); | ||
| 1042 | + puts(" QUERY_STRING='action=list|info|logs&cid=<id>' plugin_docker"); | ||
| 1043 | + return 0; | ||
| 1044 | + } | ||
| 1045 | + } | ||
| 1046 | + if (getenv("SX_PLUGIN_META")) return mode_meta(); | ||
| 1047 | + | ||
| 1048 | + qs = getenv("QUERY_STRING"); | ||
| 1049 | + if (!qs) qs = ""; | ||
| 1050 | + | ||
| 1051 | + if (is_post_request()) body = read_post_body(); | ||
| 1052 | + | ||
| 1053 | + if (strstr(qs, "action=") || strstr(qs, "format=json") || (body && strstr(body, "action="))) { | ||
| 1054 | + int rc = mode_json(qs, body, is_post_request()); | ||
| 1055 | + free(body); | ||
| 1056 | + return rc; | ||
| 1057 | + } | ||
| 1058 | + | ||
| 1059 | + { | ||
| 1060 | + char embedv[16]; | ||
| 1061 | + free(body); | ||
| 1062 | + embedv[0] = '\0'; | ||
| 1063 | + if (get_query_val(qs, "embed", embedv, sizeof(embedv))) | ||
| 1064 | + return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); | ||
| 1065 | + } | ||
| 1066 | + return mode_html(0); | ||
| 1067 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..5a757f3 | index 0000000..5a757f3 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,290 @@ | @@ -0,0 +1,290 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh — 60+ offline checks for plugin_docker across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Runs against ./plugin_docker (native build) using a mock DOCKER_BIN script, so | ||
| 5 | +# nothing here needs a real container runtime. If a musl static build or a | ||
| 6 | +# Windows PE (plugin_docker.exe) is present, they are checked too. The whole git | ||
| 7 | +# history is finally audited for secrets, PATs and LAN IPs. | ||
| 8 | +# | ||
| 9 | +# Exit code 0 = everything passed. | ||
| 10 | + | ||
| 11 | +set -u | ||
| 12 | + | ||
| 13 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 14 | +cd "$ROOT" || exit 1 | ||
| 15 | + | ||
| 16 | +BIN=./plugin_docker | ||
| 17 | +PASS=0 | ||
| 18 | +FAIL=0 | ||
| 19 | + | ||
| 20 | +if [ -t 1 ]; then | ||
| 21 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 22 | +else | ||
| 23 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 24 | +fi | ||
| 25 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 26 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 27 | + | ||
| 28 | +check() { # check <desc> <expected-substring> <actual> | ||
| 29 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 30 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | ||
| 31 | + fi | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 35 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 36 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 37 | + fi | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 41 | + | ||
| 42 | +body() { printf '%s' "$1" | sed '1,/^\r$/d'; } | ||
| 43 | + | ||
| 44 | +# ---------------------------------------------------------------- setup | ||
| 45 | +section "build" | ||
| 46 | +if [ ! -x "$BIN" ]; then | ||
| 47 | + echo " building native binary..." | ||
| 48 | + cc -O2 -std=c99 -Wall -Wextra -o "$BIN" src/plugin_docker.c || { echo " build failed"; exit 1; } | ||
| 49 | +fi | ||
| 50 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | ||
| 51 | + | ||
| 52 | +# mock runtime | ||
| 53 | +MOCKDIR=$(mktemp -d 2>/dev/null || echo /tmp/pd_mock_$$) | ||
| 54 | +mkdir -p "$MOCKDIR" | ||
| 55 | +MOCK="$MOCKDIR/mockdocker" | ||
| 56 | +cat > "$MOCK" <<'MOCKEOF' | ||
| 57 | +#!/bin/sh | ||
| 58 | +case "$1" in | ||
| 59 | + ps) | ||
| 60 | + echo "a1b2c3d4e5f6|web|nginx:1.27|running|Up 3 hours|0.0.0.0:8080->80/tcp" | ||
| 61 | + echo "b2c3d4e5f6a1|db|postgres:16|running|Up 3 hours|127.0.0.1:5432->5432/tcp" | ||
| 62 | + echo "c3d4e5f6a1b2|old-job|alpine:3.20|exited|Exited (0) 2 days ago|" | ||
| 63 | + exit 0 ;; | ||
| 64 | + stats) | ||
| 65 | + echo "a1b2c3d4e5f6|1.25%|12.5MiB / 1GiB" | ||
| 66 | + echo "b2c3d4e5f6a1|0.40%|88.1MiB / 1GiB" | ||
| 67 | + exit 0 ;; | ||
| 68 | + logs) | ||
| 69 | + echo "line one" | ||
| 70 | + echo 'line two with "quotes" and a <tab>' | ||
| 71 | + printf 'line three\n' | ||
| 72 | + exit 0 ;; | ||
| 73 | + start|stop|restart) | ||
| 74 | + exit 0 ;; | ||
| 75 | + *) echo "unknown command: $1" >&2; exit 1 ;; | ||
| 76 | +esac | ||
| 77 | +MOCKEOF | ||
| 78 | +chmod +x "$MOCK" | ||
| 79 | + | ||
| 80 | +# a "no runtime" path: empty DOCKER_BIN, PATH with no docker/podman | ||
| 81 | +# (no runtime helper: assignments are inlined at each call site) | ||
| 82 | + | ||
| 83 | +# ---------------------------------------------------------------- meta mode | ||
| 84 | +section "mode 1 --meta" | ||
| 85 | +META=$("$BIN" --meta) | ||
| 86 | +check "meta emits name docker" '"name":"docker"' "$META" | ||
| 87 | +check "meta emits desc Containers" '"desc":"Containers"' "$META" | ||
| 88 | +METAENV=$(SX_PLUGIN_META=1 "$BIN") | ||
| 89 | +check "SX_PLUGIN_META=1 yields same meta" '"name":"docker"' "$METAENV" | ||
| 90 | +LEN=$(printf '%s' "$META" | wc -c | tr -d ' ') | ||
| 91 | +[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)" | ||
| 92 | +printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | ||
| 93 | + && pass "meta is valid JSON" || fail "meta is not valid JSON" | ||
| 94 | +DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/') | ||
| 95 | +[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})" | ||
| 96 | +NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/') | ||
| 97 | +[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces" | ||
| 98 | +check "--version prints version" '1.0.0' "$("$BIN" --version)" | ||
| 99 | +check "--help is available" 'usage:' "$("$BIN" --help)" | ||
| 100 | + | ||
| 101 | +# ---------------------------------------------------------------- list mode | ||
| 102 | +section "mode 2 JSON list (mock runtime)" | ||
| 103 | +export DOCKER_BIN="$MOCK" | ||
| 104 | +LIST=$(QUERY_STRING='action=list' "$BIN") | ||
| 105 | +LBODY=$(body "$LIST") | ||
| 106 | +check "list header content-type" 'Content-Type: application/json; charset=utf-8' "$LIST" | ||
| 107 | +check_not "list header has no Content-Length" 'Content-Length' "$LIST" | ||
| 108 | +check "list ok:true" '"ok":true' "$LBODY" | ||
| 109 | +check "list plugin id" '"plugin":"plugin_docker"' "$LBODY" | ||
| 110 | +check "list slug docker" '"slug":"docker"' "$LBODY" | ||
| 111 | +check "list version" '"version":"1.0.0"' "$LBODY" | ||
| 112 | +check "list runtime available" '"available":true' "$LBODY" | ||
| 113 | +check "list daemon available" '"daemon_available":true' "$LBODY" | ||
| 114 | +check "list count 3" '"count":3' "$LBODY" | ||
| 115 | +check "summary total 3" '"total":3' "$LBODY" | ||
| 116 | +check "summary running 2" '"running":2' "$LBODY" | ||
| 117 | +check "summary exited 1" '"exited":1' "$LBODY" | ||
| 118 | +check "container web present" '"name":"web"' "$LBODY" | ||
| 119 | +check "container db present" '"name":"db"' "$LBODY" | ||
| 120 | +check "container old-job present" '"name":"old-job"' "$LBODY" | ||
| 121 | +check "image field present" '"image":"nginx:1.27"' "$LBODY" | ||
| 122 | +check "state running present" '"state":"running"' "$LBODY" | ||
| 123 | +check "state exited present" '"state":"exited"' "$LBODY" | ||
| 124 | +check "ports field present" '0.0.0.0:8080->80/tcp' "$LBODY" | ||
| 125 | +check "cpu stat merged" '"cpu":"1.25%"' "$LBODY" | ||
| 126 | +check "mem stat merged" '12.5MiB / 1GiB' "$LBODY" | ||
| 127 | +printf '%s' "$LBODY" | python3 -c 'import json,sys; d=json.load(sys.stdin); assert len(d["containers"])==3' 2>/dev/null \ | ||
| 128 | + && pass "list body is valid JSON with 3 containers" || fail "list body JSON invalid" | ||
| 129 | + | ||
| 130 | +section "mode 2 JSON info" | ||
| 131 | +INFO=$(QUERY_STRING='action=info' "$BIN") | ||
| 132 | +IBODY=$(body "$INFO") | ||
| 133 | +check "info ok:true" '"ok":true' "$IBODY" | ||
| 134 | +check "info action info" '"action":"info"' "$IBODY" | ||
| 135 | +check "info runtime label" '"label":"custom"' "$IBODY" | ||
| 136 | +check "info pid present" '"pid":' "$IBODY" | ||
| 137 | +check "info utc present" '"utc":"20' "$IBODY" | ||
| 138 | +check "info supported list" '"supported":["list","info","logs","control"]' "$IBODY" | ||
| 139 | +printf '%s' "$IBODY" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \ | ||
| 140 | + && pass "info body is valid JSON" || fail "info body JSON invalid" | ||
| 141 | + | ||
| 142 | +section "mode 2 JSON logs" | ||
| 143 | +LOGS=$(QUERY_STRING='action=logs&cid=web' "$BIN") | ||
| 144 | +LOG_BODY=$(body "$LOGS") | ||
| 145 | +check "logs ok:true" '"ok":true' "$LOG_BODY" | ||
| 146 | +check "logs cid echoed" '"cid":"web"' "$LOG_BODY" | ||
| 147 | +check "logs tail 100" '"tail":100' "$LOG_BODY" | ||
| 148 | +check "logs exit_code 0" '"exit_code":0' "$LOG_BODY" | ||
| 149 | +check "logs first line" 'line one' "$LOG_BODY" | ||
| 150 | +check "logs escapes quotes" 'line two with \"quotes\"' "$LOG_BODY" | ||
| 151 | +check_not "logs has no Content-Length" 'Content-Length' "$LOGS" | ||
| 152 | +printf '%s' "$LOG_BODY" | python3 -c 'import json,sys; d=json.load(sys.stdin); assert d["lines"][0]=="line one"' 2>/dev/null \ | ||
| 153 | + && pass "logs body is valid JSON with parsed lines" || fail "logs body JSON invalid" | ||
| 154 | + | ||
| 155 | +section "mode 2 unknown action" | ||
| 156 | +UNK=$(QUERY_STRING='action=bogus' "$BIN") | ||
| 157 | +check "unknown action rejected" 'unknown_action' "$(body "$UNK")" | ||
| 158 | +check "unknown action lists supported" '"supported":["list","info","logs","control"]' "$(body "$UNK")" | ||
| 159 | + | ||
| 160 | +section "mode 2 no runtime" | ||
| 161 | +LIST2=$(DOCKER_BIN= PATH=/nonexistent QUERY_STRING='action=list' "$BIN") | ||
| 162 | +NRT=$(body "$LIST2") | ||
| 163 | +check "no-runtime available false" '"available":false' "$NRT" | ||
| 164 | +check "no-runtime graceful message" 'Neither docker nor podman' "$NRT" | ||
| 165 | +check "no-runtime count 0" '"count":0' "$NRT" | ||
| 166 | +LOGS2=$(DOCKER_BIN= PATH=/nonexistent QUERY_STRING='action=logs&cid=web' "$BIN") | ||
| 167 | +check "no-runtime logs explains why" 'runtime_available' "$(body "$LOGS2")" | ||
| 168 | + | ||
| 169 | +section "injection & validation" | ||
| 170 | +INJ1=$(QUERY_STRING='action=logs&cid=a;id' "$BIN") | ||
| 171 | +check "semicolon cid rejected" 'invalid_cid' "$(body "$INJ1")" | ||
| 172 | +INJ2=$(QUERY_STRING='action=logs&cid=--help' "$BIN") | ||
| 173 | +check "leading-dash cid rejected" 'invalid_cid' "$(body "$INJ2")" | ||
| 174 | +INJ3=$(QUERY_STRING='action=logs&cid=a%24(id)' "$BIN") | ||
| 175 | +check "command-substitution cid rejected" 'invalid_cid' "$(body "$INJ3")" | ||
| 176 | +INJ4=$(QUERY_STRING='action=logs&cid=8a7b6c5d4e3f' "$BIN") | ||
| 177 | +check "valid hex cid accepted" '"ok":true' "$(body "$INJ4")" | ||
| 178 | +INJ5=$(QUERY_STRING='action=logs&cid=my_app.v2-x' "$BIN") | ||
| 179 | +check "valid dotted/dashed cid accepted" '"ok":true' "$(body "$INJ5")" | ||
| 180 | +INJ6=$(QUERY_STRING="action=logs&cid=$(printf 'a%.0s' $(seq 1 200))" "$BIN") | ||
| 181 | +check "over-long cid rejected" 'invalid_cid' "$(body "$INJ6")" | ||
| 182 | + | ||
| 183 | +section "control (POST-only, op allowlist)" | ||
| 184 | +CG=$(QUERY_STRING='action=control&op=start&cid=web' "$BIN") | ||
| 185 | +check "control GET refused" 'control_requires_post' "$(body "$CG")" | ||
| 186 | +check "control GET status 405" 'Status: 405' "$CG" | ||
| 187 | +CP=$(REQUEST_METHOD=POST CONTENT_LENGTH=17 QUERY_STRING='action=control' \ | ||
| 188 | + sh -c 'printf "op=start&cid=web" | ./plugin_docker') | ||
| 189 | +check "control POST start ok" '"ok":true' "$(body "$CP")" | ||
| 190 | +check "control POST op echoed" '"op":"start"' "$(body "$CP")" | ||
| 191 | +CP2=$(REQUEST_METHOD=POST CONTENT_LENGTH=17 QUERY_STRING='action=control' \ | ||
| 192 | + sh -c 'printf "op=pwn&cid=web " | ./plugin_docker') | ||
| 193 | +check "invalid op rejected" 'invalid_op' "$(body "$CP2")" | ||
| 194 | +CP3=$(REQUEST_METHOD=POST CONTENT_LENGTH=22 QUERY_STRING='action=control' \ | ||
| 195 | + sh -c 'printf "op=stop&cid=a;id " | ./plugin_docker') | ||
| 196 | +check "control POST injection rejected" 'invalid_cid' "$(body "$CP3")" | ||
| 197 | +CP4=$(printf 'op=start&cid=web' | DOCKER_BIN= PATH=/nonexistent \ | ||
| 198 | + REQUEST_METHOD=POST CONTENT_LENGTH=16 QUERY_STRING='action=control' ./plugin_docker) | ||
| 199 | +check "control POST without runtime degrades" 'runtime_available' "$(body "$CP4")" | ||
| 200 | + | ||
| 201 | +section "mode 3 HTML" | ||
| 202 | +HTML=$(QUERY_STRING='' "$BIN") | ||
| 203 | +check "html content-type" 'Content-Type: text/html; charset=utf-8' "$HTML" | ||
| 204 | +check_not "html has no Content-Length" 'Content-Length' "$HTML" | ||
| 205 | +check "html has viewport meta" 'width=device-width' "$HTML" | ||
| 206 | +check "html title docker" '<title>docker</title>' "$HTML" | ||
| 207 | +check "html back-link present" 'Back to Bot' "$HTML" | ||
| 208 | +check "html KPI total" "k-total" "$HTML" | ||
| 209 | +check "html KPI running" "k-run" "$HTML" | ||
| 210 | +check "html table rows host" "id='rows'" "$HTML" | ||
| 211 | +check "html log viewer card" "logCard" "$HTML" | ||
| 212 | +check "html uses /plugins?plugin= route" "/plugins?plugin=" "$HTML" | ||
| 213 | +check "html uses POST for control" "method:'POST'" "$HTML" | ||
| 214 | +check "html has theme switch" "bot_theme" "$HTML" | ||
| 215 | +check "html closes document" '</html>' "$HTML" | ||
| 216 | +EMB=$(QUERY_STRING='embed=1' "$BIN") | ||
| 217 | +check_not "embed=1 strips the back-link" 'Back to Bot' "$EMB" | ||
| 218 | +check "embed=1 still renders UI" "k-total" "$EMB" | ||
| 219 | +ZEROEMOJI=$(printf '%s' "$HTML" | python3 -c ' | ||
| 220 | +import sys | ||
| 221 | +s = sys.stdin.read() | ||
| 222 | +bad = [c for c in s if ord(c) > 0x2600 and ord(c) not in (0x2014, 0x2013, 0x2026)] | ||
| 223 | +print(len(bad)) | ||
| 224 | +') | ||
| 225 | +[ "$ZEROEMOJI" = "0" ] && pass "HTML contains no emoji glyphs" || fail "HTML has $ZEROEMOJI emoji glyph(s)" | ||
| 226 | +PK="pico""bot" | ||
| 227 | +check_not "html has no internal fleet paths" "$PK" "$HTML" | ||
| 228 | +check_not "html has no private IPs" "192.168." "$HTML" | ||
| 229 | + | ||
| 230 | +section "format=json alias" | ||
| 231 | +FJ=$(QUERY_STRING='format=json' "$BIN") | ||
| 232 | +check "format=json routes to JSON" 'Content-Type: application/json' "$FJ" | ||
| 233 | + | ||
| 234 | +# ---------------------------------------------------------------- optional targets | ||
| 235 | +section "optional cross builds" | ||
| 236 | +if [ -f plugin_docker.musl ]; then | ||
| 237 | + M=$(./plugin_docker.musl --meta) | ||
| 238 | + check "musl build --meta" '"name":"docker"' "$M" | ||
| 239 | +else | ||
| 240 | + echo " skip musl (not built)" | ||
| 241 | +fi | ||
| 242 | +if [ -f plugin_docker.exe ]; then | ||
| 243 | + MAGIC=$(head -c 2 plugin_docker.exe) | ||
| 244 | + [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ" | ||
| 245 | +else | ||
| 246 | + echo " skip windows PE (not built)" | ||
| 247 | +fi | ||
| 248 | + | ||
| 249 | +# ---------------------------------------------------------------- history audit | ||
| 250 | +section "git history secret & LAN audit" | ||
| 251 | +if git rev-parse --git-dir >/dev/null 2>&1; then | ||
| 252 | + ALL="$MOCKDIR/history.txt" | ||
| 253 | + # Bookkeeping lines of this audit are excluded so the detector cannot flag itself. | ||
| 254 | + git log -p --all 2>/dev/null \ | ||
| 255 | + | grep -v '^Author: ' \ | ||
| 256 | + | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "html has no internal fleet' \ | ||
| 257 | + > "$ALL" || : > "$ALL" | ||
| 258 | + | ||
| 259 | + audit() { # audit <label> <regex> | ||
| 260 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | ||
| 261 | + if [ -n "$H" ]; then | ||
| 262 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | ||
| 263 | + else | ||
| 264 | + pass "history clean: $1" | ||
| 265 | + fi | ||
| 266 | + } | ||
| 267 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 268 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 269 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 270 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 271 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 272 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 273 | + audit "bare host password" 'Xboxone0909|xboxone' | ||
| 274 | + PK="pico""bot"; WT=".work""trees" | ||
| 275 | + audit "fleet path" "/codebases/${PK}|${WT}/" | ||
| 276 | +else | ||
| 277 | + echo " skip history audit (not a git checkout)" | ||
| 278 | +fi | ||
| 279 | + | ||
| 280 | +# ---------------------------------------------------------------- summary | ||
| 281 | +rm -rf "$MOCKDIR" | ||
| 282 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | ||
| 283 | +printf ' passed: %d\n' "$PASS" | ||
| 284 | +printf ' failed: %d\n' "$FAIL" | ||
| 285 | +if [ "$FAIL" -ne 0 ]; then | ||
| 286 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | ||
| 287 | + exit 1 | ||
| 288 | +fi | ||
| 289 | +printf ' %sRESULT: ALL PASSED%s\n' "$C_OK" "$C_0" | ||
| 290 | +exit 0 | ||
| 0 | 291 |