| 1 | 1 | new file mode 100644 |
| index 0000000..6382725 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,8 @@ | ||
| 1 | +/plugin_crontab | |
| 2 | +/plugin_crontab.musl | |
| 3 | +/plugin_crontab.exe | |
| 4 | +/plugin_crontab.macos-arm64 | |
| 5 | +/plugin_crontab.macos-x86_64 | |
| 6 | +*.o | |
| 7 | +*.tmp | |
| 8 | +*.dSYM |
| 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..24be400 | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,56 @@ | ||
| 1 | +# plugin_crontab — ScorpioX Bot open-source cron schedule inspector | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_crontab | |
| 5 | +# make musl static musl x86_64 -> ./plugin_crontab (fully static) | |
| 6 | +# make win64 MinGW-w64 static -> ./plugin_crontab.exe | |
| 7 | +# make macos Apple clang -> ./plugin_crontab (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 -Wno-overlength-strings | |
| 15 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 16 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | |
| 17 | +SRC := src/plugin_crontab.c | |
| 18 | +BIN := plugin_crontab | |
| 19 | +EXE := plugin_crontab.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).musl $(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) $(BIN).musl $(EXE) $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 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..eb4c10d | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,192 @@ | ||
| 1 | +# plugin_crontab — ScorpioX Bot open-source cron schedule inspector | |
| 2 | + | |
| 3 | +A clean-room, MIT-licensed [ScorpioX Bot](https://bot.scorpiox.net) dynamic plugin that | |
| 4 | +shows the scheduled entries on **your own node**, explains what each cron expression | |
| 5 | +means in plain English, and computes the exact next five firing times — in UTC and in | |
| 6 | +your local time. It also ships an interactive cron playground that works on any machine, | |
| 7 | +even one with zero cron jobs installed. | |
| 8 | + | |
| 9 | +One C99 file. No dependencies. No daemon of its own. No outbound network requests. | |
| 10 | + | |
| 11 | +``` | |
| 12 | +plugin_crontab --meta | |
| 13 | +{"name":"crontab","desc":"Cron jobs"} | |
| 14 | +``` | |
| 15 | + | |
| 16 | +--- | |
| 17 | + | |
| 18 | +## What it does | |
| 19 | + | |
| 20 | +| Area | Detail | | |
| 21 | +|---|---| | |
| 22 | +| **Job listing** | Reads `crontab -l`, `/etc/crontab` and every file in `/etc/cron.d` on Linux and macOS. On Windows it reads `schtasks /Query /FO CSV /NH`. | | |
| 23 | +| **Schedule parsing** | Full five-field syntax: `*`, `N`, `a-b`, `*/step`, `a-b/step` and comma lists, plus month and weekday names (`JAN`, `mon-fri`, ...). `0` and `7` both mean Sunday. | | |
| 24 | +| **Keywords** | `@reboot`, `@hourly`, `@daily`, `@midnight`, `@weekly`, `@monthly`, `@yearly`, `@annually`. | | |
| 25 | +| **Plain English** | Every expression is described: `Every 15 minutes, between 09:00 and 17:59, on Monday, Tuesday, Wednesday, Thursday, Friday`. | | |
| 26 | +| **Next runs** | The next five firing times, as ISO-8601 UTC and as local `YYYY-MM-DD HH:MM`, with a second-by-second countdown in the UI. | | |
| 27 | +| **Playground** | Type any expression and get live validation plus its next five runs. Works with no crontab present. | | |
| 28 | +| **Day semantics** | Honours the classic cron rule: when both day-of-month and day-of-week are restricted, a day matches if **either** field matches. | | |
| 29 | +| **Theme** | Follows the Bot theme (`localStorage.bot_theme`), dark by default, no flash. | | |
| 30 | +| **Embed mode** | `?embed=1` drops the back-link so it fits the chat floating window. | | |
| 31 | + | |
| 32 | +### Why it is safe | |
| 33 | + | |
| 34 | +**1. Strictly read-only.** There is no code path that writes a crontab, installs a | |
| 35 | +scheduled task, or executes a scheduled command. The only external programs invoked are | |
| 36 | +`crontab -l` (POSIX, list) and `schtasks /Query` (Windows, query). Both are read-only and | |
| 37 | +both are hard-coded — no user-supplied value ever reaches a command line, so there is no | |
| 38 | +injection surface at all. | |
| 39 | + | |
| 40 | +**2. Node authentication.** The node API (`:8150`) is reachable from the LAN, so the plugin | |
| 41 | +refuses any request that does not carry the node password. Accepted forms match the rest of | |
| 42 | +the node API: `X-Bot-Password: <pwd>` (what `bot-web` proxies with), `Authorization: Bearer | |
| 43 | +<pwd>`, or `?pwd=<pwd>` (what the plugin iframe appends). If `BOT_PASSWORD` is unset the node | |
| 44 | +is in explicitly open mode and the check is a no-op, exactly like `terminal_tmux.c`. | |
| 45 | + | |
| 46 | +**3. Deterministic fixture mode.** `CRONTAB_FILE=/path/to/file` makes the parser read that | |
| 47 | +file instead of the live machine. That is what the test suite uses, and it means the whole | |
| 48 | +scheduler model can be audited offline without touching a real crontab. | |
| 49 | + | |
| 50 | +**4. No network egress.** The binary contains no `http://`, no `https://` and no socket | |
| 51 | +call. All it does is read local files and print. | |
| 52 | + | |
| 53 | +--- | |
| 54 | + | |
| 55 | +## Install | |
| 56 | + | |
| 57 | +### Pre-built (no compiler needed) | |
| 58 | + | |
| 59 | +```sh | |
| 60 | +# Linux x86_64 — the static musl binary works on Alpine, Debian, Ubuntu, Arch, Omarchy | |
| 61 | +mkdir -p ~/.scorpiox/plugins | |
| 62 | +curl -fsSL https://dist.scorpiox.net/bot-plugins/crontab/1.0.0/linux-x86_64-musl/plugin_crontab \ | |
| 63 | + -o ~/.scorpiox/plugins/plugin_crontab | |
| 64 | +chmod +x ~/.scorpiox/plugins/plugin_crontab | |
| 65 | +~/.scorpiox/plugins/plugin_crontab --meta | |
| 66 | +``` | |
| 67 | + | |
| 68 | +On Windows, put `plugin_crontab.exe` in `%LOCALAPPDATA%\scorpiox\plugins\`. | |
| 69 | +On a BotCloud container, use `/workspace/.scorpiox/plugins/` so it survives restarts. | |
| 70 | + | |
| 71 | +No server restart is required — `scorpiox-server` resolves plugin routes live. | |
| 72 | + | |
| 73 | +### From source | |
| 74 | + | |
| 75 | +```sh | |
| 76 | +git clone https://plugingit.scorpiox.net/scorpiox-bot-plugin-crontab.git | |
| 77 | +cd scorpiox-bot-plugin-crontab | |
| 78 | +make # native build -> ./plugin_crontab | |
| 79 | +make musl # fully static Linux -> ./plugin_crontab.musl | |
| 80 | +make win64 # static Windows PE -> ./plugin_crontab.exe | |
| 81 | +make test # 80+ offline assertions | |
| 82 | +``` | |
| 83 | + | |
| 84 | +### Agent-assisted build | |
| 85 | + | |
| 86 | +Paste this into ScorpioX Bot Chat: | |
| 87 | + | |
| 88 | +> Clone `https://plugingit.scorpiox.net/scorpiox-bot-plugin-crontab.git`, audit | |
| 89 | +> `src/plugin_crontab.c` for safety, customise it for my setup, compile it natively on this | |
| 90 | +> machine, verify `--meta`, and install it to `~/.scorpiox/plugins/`. | |
| 91 | + | |
| 92 | +Because the plugin is a single dependency-free C99 file, that takes seconds. | |
| 93 | + | |
| 94 | +--- | |
| 95 | + | |
| 96 | +## HTTP API | |
| 97 | + | |
| 98 | +All JSON responses are `Content-Type: application/json; charset=utf-8` with | |
| 99 | +`Cache-Control: no-store`. | |
| 100 | + | |
| 101 | +### `?action=jobs` (alias `list`, or `?format=json`) | |
| 102 | + | |
| 103 | +```json | |
| 104 | +{ | |
| 105 | + "ok": true, | |
| 106 | + "action": "jobs", | |
| 107 | + "plugin": "plugin_crontab", | |
| 108 | + "version": "1.0.0", | |
| 109 | + "now_utc": "2026-11-11T04:49:22Z", | |
| 110 | + "now_local": "2026-11-11 04:49", | |
| 111 | + "count": 7, | |
| 112 | + "truncated": false, | |
| 113 | + "sources": ["user", "/etc/crontab"], | |
| 114 | + "jobs": [ | |
| 115 | + { | |
| 116 | + "source": "user", | |
| 117 | + "kind": "cron", | |
| 118 | + "expr": "*/5 * * * *", | |
| 119 | + "command": "/usr/bin/backup.sh --flag", | |
| 120 | + "user": "", | |
| 121 | + "valid": true, | |
| 122 | + "description": "Every 5 minutes, every day", | |
| 123 | + "next": [ | |
| 124 | + {"utc": "2026-11-11T04:50:00Z", "local": "2026-11-11 04:50", "in_seconds": 38} | |
| 125 | + ] | |
| 126 | + } | |
| 127 | + ] | |
| 128 | +} | |
| 129 | +``` | |
| 130 | + | |
| 131 | +`count` is the number of scheduled entries found. `truncated` is set when the node has more | |
| 132 | +than 512 entries. Lines that fail to parse are still listed with `valid: false` and an | |
| 133 | +`error` string, rather than being silently dropped. | |
| 134 | + | |
| 135 | +### `?action=explain&expr=<expression>` | |
| 136 | + | |
| 137 | +```json | |
| 138 | +{ | |
| 139 | + "ok": true, | |
| 140 | + "action": "explain", | |
| 141 | + "expr": "*/15 9-17 * * 1-5", | |
| 142 | + "valid": true, | |
| 143 | + "keyword": "", | |
| 144 | + "description": "Every 15 minutes, between 09:00 and 17:59, on Monday, Tuesday, Wednesday, Thursday, Friday", | |
| 145 | + "normalized": "*/15 9-17 * * 1-5", | |
| 146 | + "fields": {"minute": "*/15", "hour": "9-17", "day_of_month": "*", "month": "*", "day_of_week": "1-5"}, | |
| 147 | + "boot_only": false, | |
| 148 | + "now_utc": "2026-11-11T04:47:32Z", | |
| 149 | + "now_local": "2026-11-11 04:47", | |
| 150 | + "next": [ | |
| 151 | + {"utc": "2026-11-11T09:00:00Z", "local": "2026-11-11 09:00", "in_seconds": 15148} | |
| 152 | + ] | |
| 153 | +} | |
| 154 | +``` | |
| 155 | + | |
| 156 | +Invalid expressions return `"valid": false` with a specific `error` | |
| 157 | +(`minute out of range 0-59`, `expected 5 fields`, `unknown @keyword`, ...). | |
| 158 | + | |
| 159 | +`@reboot` returns `"boot_only": true` and an empty `next` array — it has no clock times. | |
| 160 | + | |
| 161 | +Explanations are always available, on any machine, whether or not a crontab exists. | |
| 162 | + | |
| 163 | +### `?action=info` | |
| 164 | + | |
| 165 | +Plugin identity, version, supported actions, capabilities and the trust notice. | |
| 166 | + | |
| 167 | +--- | |
| 168 | + | |
| 169 | +## Scope boundaries | |
| 170 | + | |
| 171 | +- **Read-only.** No crontab writes, no task creation, no command execution. | |
| 172 | +- **No network.** No sockets, no HTTP client, no telemetry. | |
| 173 | +- **Two external programs, both query-only:** `crontab -l` and `schtasks /Query`. | |
| 174 | +- **No user input reaches a shell.** Fixture paths come from the environment, not the query. | |
| 175 | +- **Next-run horizon** is four years, which covers every expression including | |
| 176 | + `0 0 29 2 *` (29 February) and `0 0 1 1 *` (1 January). | |
| 177 | + | |
| 178 | +--- | |
| 179 | + | |
| 180 | +## Layout | |
| 181 | + | |
| 182 | +``` | |
| 183 | +src/plugin_crontab.c the whole plugin: cron parser, next-run engine, JSON API, HTML UI | |
| 184 | +tests/run.sh 80+ offline assertions, all against fixtures | |
| 185 | +Makefile all / musl / win64 / macos / test / clean | |
| 186 | +build.ps1 Windows PowerShell build with an MZ sanity check | |
| 187 | +release-dist.sh secret scan -> multi-target build -> dist upload -> plugingit mirror | |
| 188 | +``` | |
| 189 | + | |
| 190 | +## Licence | |
| 191 | + | |
| 192 | +MIT. See `LICENSE`. |
| 1 | 1 | new file mode 100644 |
| index 0000000..799bff1 | ||
| --- /dev/null | ||
| +++ b/build.ps1 | ||
| @@ -0,0 +1,53 @@ | ||
| 1 | +# build.ps1 — Windows MinGW-w64 static build for plugin_crontab | |
| 2 | +# | |
| 3 | +# Usage (from the repo root, PowerShell): | |
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | |
| 5 | +# | |
| 6 | +# Produces .\plugin_crontab.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_crontab.c" | |
| 14 | + $Out = Join-Path $ScriptDir "plugin_crontab.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_crontab.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_crontab.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`"" | |
| 50 | +} | |
| 51 | +finally { | |
| 52 | + Pop-Location | |
| 53 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..a39a843 | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,350 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh — build, scan and publish plugin_crontab 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="crontab" | |
| 30 | +ID="plugin_crontab" | |
| 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": "crontab",\n' | |
| 210 | + printf ' "desc": "Cron jobs",\n' | |
| 211 | + printf ' "title": "Local Cron Schedule Inspector",\n' | |
| 212 | + printf ' "summary": "Zero-dependency local cron inspector: lists the scheduled jobs on your node, explains each expression in plain English, and computes the exact next five firing times in UTC and local time. Includes an interactive cron expression playground that works even with no crontab installed.",\n' | |
| 213 | + printf ' "category": "devtools",\n' | |
| 214 | + printf ' "version": "%s",\n' "$VERSION" | |
| 215 | + printf ' "license": "MIT",\n' | |
| 216 | + printf ' "trust_notice": "Executes native C code on your node. Strictly read-only: reads crontab listings and Windows task lists to describe schedules, never writes a schedule and never executes a scheduled command. Makes zero outbound network requests.",\n' | |
| 217 | + printf ' "capabilities": ["crontab_read", "cron_parse", "cron_next_run"],\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..7524065 | ||
| --- /dev/null | ||
| +++ b/src/plugin_crontab.c | ||
| @@ -0,0 +1,1663 @@ | ||
| 1 | +/* | |
| 2 | + * plugin_crontab — ScorpioX Bot open-source cron schedule inspector | |
| 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=jobs | ?action=explain&expr=... | ?format=json -> JSON node API | |
| 7 | + * 3. GET (default) -> responsive HTML schedule inspector | |
| 8 | + * | |
| 9 | + * Strictly READ-ONLY. It never writes a crontab, never installs a task and | |
| 10 | + * never executes a scheduled command. On POSIX it reads the user's | |
| 11 | + * `crontab -l` output plus /etc/crontab and the files in /etc/cron.d; on Windows it reads | |
| 12 | + * `schtasks /Query /FO CSV`. Setting CRONTAB_FILE to a fixture path bypasses | |
| 13 | + * all of that, which is what the offline tests use. | |
| 14 | + * | |
| 15 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | |
| 16 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | |
| 17 | + * scorpiox-server on the node. | |
| 18 | + * | |
| 19 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 20 | + */ | |
| 21 | + | |
| 22 | +#if !defined(_WIN32) | |
| 23 | +# define _POSIX_C_SOURCE 200809L | |
| 24 | +# define _DEFAULT_SOURCE 1 | |
| 25 | +#endif | |
| 26 | + | |
| 27 | +#include <stdio.h> | |
| 28 | +#include <stdlib.h> | |
| 29 | +#include <string.h> | |
| 30 | +#include <time.h> | |
| 31 | +#include <ctype.h> | |
| 32 | + | |
| 33 | +#if defined(_WIN32) | |
| 34 | +# define WIN32_LEAN_AND_MEAN | |
| 35 | +# include <windows.h> | |
| 36 | +# define sx_popen _popen | |
| 37 | +# define sx_pclose _pclose | |
| 38 | +#else | |
| 39 | +# include <unistd.h> | |
| 40 | +# include <dirent.h> | |
| 41 | +# define sx_popen popen | |
| 42 | +# define sx_pclose pclose | |
| 43 | +#endif | |
| 44 | + | |
| 45 | +#define PLUGIN_SLUG "crontab" | |
| 46 | +#define PLUGIN_ID "plugin_crontab" | |
| 47 | +#define PLUGIN_VER "1.0.0" | |
| 48 | + | |
| 49 | +#define MAX_JOBS 512 | |
| 50 | +#define MAX_EXPR 128 | |
| 51 | +#define MAX_DESC 224 | |
| 52 | +#define MAX_CMD 512 | |
| 53 | +#define MAX_SRC 64 | |
| 54 | +#define MAX_RUNS 5 | |
| 55 | +#define HORIZON_DAYS 1461 | |
| 56 | +#define READ_LINE 2048 | |
| 57 | + | |
| 58 | +/* ------------------------------------------------------------------ */ | |
| 59 | +/* Small utilities */ | |
| 60 | +/* ------------------------------------------------------------------ */ | |
| 61 | + | |
| 62 | +static void url_decode(char *s) | |
| 63 | +{ | |
| 64 | + char *o = s; | |
| 65 | + if (!s) return; | |
| 66 | + while (*s) { | |
| 67 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | |
| 68 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | |
| 69 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | |
| 70 | + *o++ = (char)((hi << 4) | lo); | |
| 71 | + s += 3; | |
| 72 | + } else if (*s == '+') { | |
| 73 | + *o++ = ' '; | |
| 74 | + s++; | |
| 75 | + } else { | |
| 76 | + *o++ = *s++; | |
| 77 | + } | |
| 78 | + } | |
| 79 | + *o = '\0'; | |
| 80 | +} | |
| 81 | + | |
| 82 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 83 | +{ | |
| 84 | + size_t klen; | |
| 85 | + const char *p; | |
| 86 | + | |
| 87 | + if (!out || outsz == 0) return 0; | |
| 88 | + out[0] = '\0'; | |
| 89 | + if (!qs || !key) return 0; | |
| 90 | + klen = strlen(key); | |
| 91 | + | |
| 92 | + for (p = qs; *p; ) { | |
| 93 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 94 | + const char *v = p + klen + 1; | |
| 95 | + size_t i = 0; | |
| 96 | + while (*v && *v != '&' && i + 1 < outsz) | |
| 97 | + out[i++] = *v++; | |
| 98 | + out[i] = '\0'; | |
| 99 | + url_decode(out); | |
| 100 | + return 1; | |
| 101 | + } | |
| 102 | + p = strchr(p, '&'); | |
| 103 | + if (!p) break; | |
| 104 | + p++; | |
| 105 | + } | |
| 106 | + return 0; | |
| 107 | +} | |
| 108 | + | |
| 109 | +static void json_str(const char *s) | |
| 110 | +{ | |
| 111 | + putchar('"'); | |
| 112 | + for (; s && *s; s++) { | |
| 113 | + unsigned char c = (unsigned char)*s; | |
| 114 | + switch (c) { | |
| 115 | + case '"': fputs("\\\"", stdout); break; | |
| 116 | + case '\\': fputs("\\\\", stdout); break; | |
| 117 | + case '\n': fputs("\\n", stdout); break; | |
| 118 | + case '\r': fputs("\\r", stdout); break; | |
| 119 | + case '\t': fputs("\\t", stdout); break; | |
| 120 | + default: | |
| 121 | + if (c < 0x20) printf("\\u%04x", c); | |
| 122 | + else putchar(c); | |
| 123 | + } | |
| 124 | + } | |
| 125 | + putchar('"'); | |
| 126 | +} | |
| 127 | + | |
| 128 | +static void str_copy(char *dst, size_t sz, const char *src) | |
| 129 | +{ | |
| 130 | + size_t n; | |
| 131 | + if (!dst || sz == 0) return; | |
| 132 | + if (!src) { dst[0] = '\0'; return; } | |
| 133 | + n = strlen(src); | |
| 134 | + if (n >= sz) n = sz - 1; | |
| 135 | + memcpy(dst, src, n); | |
| 136 | + dst[n] = '\0'; | |
| 137 | +} | |
| 138 | + | |
| 139 | +static void str_trim(char *s) | |
| 140 | +{ | |
| 141 | + size_t n; | |
| 142 | + char *p; | |
| 143 | + | |
| 144 | + if (!s) return; | |
| 145 | + p = s; | |
| 146 | + while (*p && isspace((unsigned char)*p)) p++; | |
| 147 | + if (p != s) memmove(s, p, strlen(p) + 1); | |
| 148 | + n = strlen(s); | |
| 149 | + while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; | |
| 150 | +} | |
| 151 | + | |
| 152 | +static void utc_stamp(time_t t, char *buf, size_t sz) | |
| 153 | +{ | |
| 154 | + struct tm tmv; | |
| 155 | +#if defined(_WIN32) | |
| 156 | + gmtime_s(&tmv, &t); | |
| 157 | +#else | |
| 158 | + gmtime_r(&t, &tmv); | |
| 159 | +#endif | |
| 160 | + if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) | |
| 161 | + str_copy(buf, sz, "1970-01-01T00:00:00Z"); | |
| 162 | +} | |
| 163 | + | |
| 164 | +static void local_stamp(time_t t, char *buf, size_t sz) | |
| 165 | +{ | |
| 166 | + struct tm tmv; | |
| 167 | +#if defined(_WIN32) | |
| 168 | + localtime_s(&tmv, &t); | |
| 169 | +#else | |
| 170 | + localtime_r(&t, &tmv); | |
| 171 | +#endif | |
| 172 | + if (strftime(buf, sz, "%Y-%m-%d %H:%M", &tmv) == 0) | |
| 173 | + str_copy(buf, sz, "1970-01-01 00:00"); | |
| 174 | +} | |
| 175 | + | |
| 176 | +/* ------------------------------------------------------------------ */ | |
| 177 | +/* Cron model */ | |
| 178 | +/* ------------------------------------------------------------------ */ | |
| 179 | + | |
| 180 | +typedef struct { | |
| 181 | + int valid; | |
| 182 | + char error[96]; | |
| 183 | + char raw[MAX_EXPR]; | |
| 184 | + char keyword[16]; /* "@daily" etc; empty for 5-field syntax */ | |
| 185 | + char f[5][40]; /* original field texts */ | |
| 186 | + unsigned char min[60]; | |
| 187 | + unsigned char hour[24]; | |
| 188 | + unsigned char dom[32]; /* index 1..31 used */ | |
| 189 | + unsigned char mon[13]; /* index 1..12 used */ | |
| 190 | + unsigned char dow[7]; /* index 0 == Sunday */ | |
| 191 | + int dom_restricted; | |
| 192 | + int dow_restricted; | |
| 193 | + int boot_only; /* @reboot — no computable fire times */ | |
| 194 | + char desc[MAX_DESC]; | |
| 195 | +} cron_t; | |
| 196 | + | |
| 197 | +static const char *const k_mon_names[12] = { | |
| 198 | + "jan", "feb", "mar", "apr", "may", "jun", | |
| 199 | + "jul", "aug", "sep", "oct", "nov", "dec" | |
| 200 | +}; | |
| 201 | +static const char *const k_dow_names[7] = { "sun", "mon", "tue", "wed", "thu", "fri", "sat" }; | |
| 202 | +static const char *const k_mon_long[12] = { | |
| 203 | + "January", "February", "March", "April", "May", "June", | |
| 204 | + "July", "August", "September", "October", "November", "December" | |
| 205 | +}; | |
| 206 | +static const char *const k_dow_long[7] = { | |
| 207 | + "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" | |
| 208 | +}; | |
| 209 | + | |
| 210 | +static void cron_clear(cron_t *c) | |
| 211 | +{ | |
| 212 | + memset(c, 0, sizeof(*c)); | |
| 213 | +} | |
| 214 | + | |
| 215 | +static int name_index(const char *tok, int len, const char *const *names, int count) | |
| 216 | +{ | |
| 217 | + int i; | |
| 218 | + char buf[16]; | |
| 219 | + if (len <= 0 || len >= (int)sizeof(buf)) return -1; | |
| 220 | + for (i = 0; i < len; i++) buf[i] = (char)tolower((unsigned char)tok[i]); | |
| 221 | + buf[len] = '\0'; | |
| 222 | + for (i = 0; i < count; i++) | |
| 223 | + if (strcmp(buf, names[i]) == 0) return i; | |
| 224 | + return -1; | |
| 225 | +} | |
| 226 | + | |
| 227 | +/* Plain number or 3-letter name -> value. Returns 1 on success. */ | |
| 228 | +static int parse_value(const char *tok, int len, const char *const *names, | |
| 229 | + int namecount, int name_offset, int *out) | |
| 230 | +{ | |
| 231 | + int i; | |
| 232 | + int v = 0; | |
| 233 | + int named; | |
| 234 | + | |
| 235 | + if (len <= 0) return 0; | |
| 236 | + named = name_index(tok, len, names, namecount); | |
| 237 | + if (named >= 0) { *out = named + name_offset; return 1; } | |
| 238 | + for (i = 0; i < len; i++) { | |
| 239 | + if (!isdigit((unsigned char)tok[i])) return 0; | |
| 240 | + v = v * 10 + (tok[i] - '0'); | |
| 241 | + if (v > 100000) return 0; | |
| 242 | + } | |
| 243 | + *out = v; | |
| 244 | + return 1; | |
| 245 | +} | |
| 246 | + | |
| 247 | +/* | |
| 248 | + * Parse one cron field into a flag array (indices lo..hi). | |
| 249 | + * Accepts "*", "N", "a-b", "*/step", "a-b/step" and comma lists. | |
| 250 | + * Returns 1 on success, 0 on syntax error, -1 on out-of-range value. | |
| 251 | + */ | |
| 252 | +static int parse_field(const char *text, int lo, int hi, | |
| 253 | + const char *const *names, int namecount, int name_offset, | |
| 254 | + unsigned char *flags) | |
| 255 | +{ | |
| 256 | + char work[256]; | |
| 257 | + char *item; | |
| 258 | + | |
| 259 | + memset(flags, 0, (size_t)(hi + 1)); | |
| 260 | + if (!text || !*text) return 0; | |
| 261 | + if (strlen(text) >= sizeof(work)) return 0; | |
| 262 | + str_copy(work, sizeof(work), text); | |
| 263 | + | |
| 264 | + item = work; | |
| 265 | + while (item && *item) { | |
| 266 | + char *comma = strchr(item, ','); | |
| 267 | + char rng[128]; | |
| 268 | + const char *slash; | |
| 269 | + int step = 1; | |
| 270 | + int start = lo; | |
| 271 | + int end = hi; | |
| 272 | + int v; | |
| 273 | + | |
| 274 | + if (comma) *comma = '\0'; | |
| 275 | + str_trim(item); | |
| 276 | + if (!*item) return 0; | |
| 277 | + | |
| 278 | + slash = strchr(item, '/'); | |
| 279 | + if (slash) { | |
| 280 | + size_t off = (size_t)(slash - item); | |
| 281 | + if (off >= sizeof(rng)) return 0; | |
| 282 | + memcpy(rng, item, off); | |
| 283 | + rng[off] = '\0'; | |
| 284 | + if (!parse_value(slash + 1, (int)strlen(slash + 1), NULL, 0, 0, &step)) return 0; | |
| 285 | + if (step <= 0) return 0; | |
| 286 | + if (step > hi - lo + 1) step = hi - lo + 1; | |
| 287 | + } else { | |
| 288 | + str_copy(rng, sizeof(rng), item); | |
| 289 | + } | |
| 290 | + | |
| 291 | + if (strcmp(rng, "*") == 0) { | |
| 292 | + start = lo; | |
| 293 | + end = hi; | |
| 294 | + } else { | |
| 295 | + const char *dash = strchr(rng, '-'); | |
| 296 | + if (dash) { | |
| 297 | + if (!parse_value(rng, (int)(dash - rng), names, namecount, name_offset, &start)) return 0; | |
| 298 | + if (!parse_value(dash + 1, (int)strlen(dash + 1), names, namecount, name_offset, &end)) return 0; | |
| 299 | + } else { | |
| 300 | + if (!parse_value(rng, (int)strlen(rng), names, namecount, name_offset, &start)) return 0; | |
| 301 | + end = slash ? hi : start; | |
| 302 | + } | |
| 303 | + } | |
| 304 | + | |
| 305 | + if (start < lo || start > hi || end < lo || end > hi) return -1; | |
| 306 | + if (end < start) return -1; | |
| 307 | + for (v = start; v <= end; v += step) flags[v] = 1; | |
| 308 | + | |
| 309 | + if (!comma) break; | |
| 310 | + item = comma + 1; | |
| 311 | + } | |
| 312 | + return 1; | |
| 313 | +} | |
| 314 | + | |
| 315 | +/* True when every value in lo..hi is selected. */ | |
| 316 | +static int field_is_full(const unsigned char *flags, int lo, int hi) | |
| 317 | +{ | |
| 318 | + int i; | |
| 319 | + for (i = lo; i <= hi; i++) | |
| 320 | + if (!flags[i]) return 0; | |
| 321 | + return 1; | |
| 322 | +} | |
| 323 | + | |
| 324 | +static int count_set(const unsigned char *flags, int lo, int hi) | |
| 325 | +{ | |
| 326 | + int i, n = 0; | |
| 327 | + for (i = lo; i <= hi; i++) if (flags[i]) n++; | |
| 328 | + return n; | |
| 329 | +} | |
| 330 | + | |
| 331 | +/* ---------------------------------------------------------------- */ | |
| 332 | +/* Portable UTC mktime */ | |
| 333 | +/* ---------------------------------------------------------------- */ | |
| 334 | + | |
| 335 | +static time_t timegm_portable(struct tm *tmv) | |
| 336 | +{ | |
| 337 | +#if defined(_WIN32) | |
| 338 | + return _mkgmtime(tmv); | |
| 339 | +#else | |
| 340 | + return timegm(tmv); | |
| 341 | +#endif | |
| 342 | +} | |
| 343 | +/* ---------------------------------------------------------------- */ | |
| 344 | +/* Human readable description of a parsed schedule */ | |
| 345 | +/* ---------------------------------------------------------------- */ | |
| 346 | + | |
| 347 | +/* Append with bounds. */ | |
| 348 | +static void sapp(char *dst, size_t sz, const char *src) | |
| 349 | +{ | |
| 350 | + size_t have; | |
| 351 | + if (!dst || sz == 0 || !src) return; | |
| 352 | + have = strlen(dst); | |
| 353 | + if (have + 1 >= sz) return; | |
| 354 | + strncat(dst, src, sz - have - 1); | |
| 355 | +} | |
| 356 | + | |
| 357 | +/* First selected index in [lo,hi], or lo when none. */ | |
| 358 | +static int first_set(const unsigned char *flags, int lo, int hi) | |
| 359 | +{ | |
| 360 | + int i; | |
| 361 | + for (i = lo; i <= hi; i++) if (flags[i]) return i; | |
| 362 | + return lo; | |
| 363 | +} | |
| 364 | + | |
| 365 | +static void cron_describe_time(const cron_t *c, char *out, size_t sz) | |
| 366 | +{ | |
| 367 | + int nm, nh; | |
| 368 | + | |
| 369 | + out[0] = '\0'; | |
| 370 | + | |
| 371 | + if (field_is_full(c->min, 0, 59) && field_is_full(c->hour, 0, 23)) { | |
| 372 | + str_copy(out, sz, "Every minute"); | |
| 373 | + return; | |
| 374 | + } | |
| 375 | + if (c->f[0][0] == '*' && c->f[0][1] == '/' && field_is_full(c->hour, 0, 23) | |
| 376 | + && !strchr(c->f[0], ',')) { | |
| 377 | + int step = atoi(c->f[0] + 2); | |
| 378 | + if (step == 1) str_copy(out, sz, "Every minute"); | |
| 379 | + else snprintf(out, sz, "Every %d minutes", step); | |
| 380 | + return; | |
| 381 | + } | |
| 382 | + if (field_is_full(c->hour, 0, 23) && c->f[1][0] == '*') { | |
| 383 | + int n = count_set(c->min, 0, 59); | |
| 384 | + if (c->f[0][0] == '*' && c->f[0][1] == '\0') { | |
| 385 | + str_copy(out, sz, "Every minute"); | |
| 386 | + } else if (n <= 6) { | |
| 387 | + int m, first = 1; | |
| 388 | + sapp(out, sz, "Every hour at minute "); | |
| 389 | + for (m = 0; m < 60; m++) { | |
| 390 | + char t[8]; | |
| 391 | + if (!c->min[m]) continue; | |
| 392 | + snprintf(t, sizeof(t), "%s%d", first ? "" : " and ", m); | |
| 393 | + sapp(out, sz, t); | |
| 394 | + first = 0; | |
| 395 | + } | |
| 396 | + } else { | |
| 397 | + snprintf(out, sz, "Every hour at %d selected minutes", n); | |
| 398 | + } | |
| 399 | + return; | |
| 400 | + } | |
| 401 | + if (c->f[1][0] == '*' && c->f[1][1] == '/' && c->min[0] == 0 | |
| 402 | + && count_set(c->min, 0, 59) == 1 && !c->dom_restricted && !c->dow_restricted) { | |
| 403 | + int step = atoi(c->f[1] + 2); | |
| 404 | + snprintf(out, sz, "Every %d hours at minute %d", step, first_set(c->min, 0, 59)); | |
| 405 | + return; | |
| 406 | + } | |
| 407 | + | |
| 408 | + nm = count_set(c->min, 0, 59); | |
| 409 | + nh = count_set(c->hour, 0, 23); | |
| 410 | + | |
| 411 | + /* uniform minute step inside a restricted hour window */ | |
| 412 | + if (c->f[0][0] == '*' && c->f[0][1] == '/' && !strchr(c->f[0], ',')) { | |
| 413 | + int step = atoi(c->f[0] + 2); | |
| 414 | + int hlo = first_set(c->hour, 0, 23); | |
| 415 | + int hhi = hlo; | |
| 416 | + int h; | |
| 417 | + for (h = 23; h >= 0; h--) if (c->hour[h]) { hhi = h; break; } | |
| 418 | + if (step > 0 && nh > 1) { | |
| 419 | + snprintf(out, sz, "Every %d minutes, between %02d:00 and %02d:59", | |
| 420 | + step, hlo, hhi); | |
| 421 | + return; | |
| 422 | + } | |
| 423 | + } | |
| 424 | + | |
| 425 | + if (nm == 1 && nh == 1) { | |
| 426 | + snprintf(out, sz, "At %02d:%02d", first_set(c->hour, 0, 23), first_set(c->min, 0, 59)); | |
| 427 | + return; | |
| 428 | + } | |
| 429 | + if (nm * nh <= 6) { | |
| 430 | + int h, m, first = 1; | |
| 431 | + sapp(out, sz, "At "); | |
| 432 | + for (h = 0; h < 24; h++) { | |
| 433 | + if (!c->hour[h]) continue; | |
| 434 | + for (m = 0; m < 60; m++) { | |
| 435 | + char t[8]; | |
| 436 | + if (!c->min[m]) continue; | |
| 437 | + snprintf(t, sizeof(t), "%s%02d:%02d", first ? "" : ", ", h, m); | |
| 438 | + sapp(out, sz, t); | |
| 439 | + first = 0; | |
| 440 | + } | |
| 441 | + } | |
| 442 | + return; | |
| 443 | + } | |
| 444 | + if (nm == 1 && nh < 24) { | |
| 445 | + int h, first = 1; | |
| 446 | + char buf[256]; | |
| 447 | + snprintf(buf, sizeof(buf), "At minute %d past hour%s ", | |
| 448 | + first_set(c->min, 0, 59), nh == 1 ? "" : "s"); | |
| 449 | + for (h = 0; h < 24; h++) { | |
| 450 | + char t[8]; | |
| 451 | + if (!c->hour[h]) continue; | |
| 452 | + snprintf(t, sizeof(t), "%s%d", first ? "" : ", ", h); | |
| 453 | + sapp(buf, sizeof(buf), t); | |
| 454 | + first = 0; | |
| 455 | + } | |
| 456 | + str_copy(out, sz, buf); | |
| 457 | + return; | |
| 458 | + } | |
| 459 | + snprintf(out, sz, "At %d times a day", nm * nh); | |
| 460 | +} | |
| 461 | + | |
| 462 | +static void cron_describe(const cron_t *cc, char *out, size_t sz) | |
| 463 | +{ | |
| 464 | + cron_t c = *cc; | |
| 465 | + char day[128]; | |
| 466 | + | |
| 467 | + out[0] = '\0'; | |
| 468 | + day[0] = '\0'; | |
| 469 | + | |
| 470 | + if (c.keyword[0]) { | |
| 471 | + if (strcmp(c.keyword, "@reboot") == 0) | |
| 472 | + str_copy(out, sz, "When the system starts"); | |
| 473 | + else if (strcmp(c.keyword, "@hourly") == 0) | |
| 474 | + str_copy(out, sz, "Every hour, on the hour"); | |
| 475 | + else if (strcmp(c.keyword, "@daily") == 0 || strcmp(c.keyword, "@midnight") == 0) | |
| 476 | + str_copy(out, sz, "Every day at midnight"); | |
| 477 | + else if (strcmp(c.keyword, "@weekly") == 0) | |
| 478 | + str_copy(out, sz, "Every Sunday at midnight"); | |
| 479 | + else if (strcmp(c.keyword, "@monthly") == 0) | |
| 480 | + str_copy(out, sz, "The 1st of every month at midnight"); | |
| 481 | + else if (strcmp(c.keyword, "@yearly") == 0 || strcmp(c.keyword, "@annually") == 0) | |
| 482 | + str_copy(out, sz, "1 January at midnight"); | |
| 483 | + else | |
| 484 | + str_copy(out, sz, "Custom schedule"); | |
| 485 | + return; | |
| 486 | + } | |
| 487 | + | |
| 488 | + cron_describe_time(&c, out, sz); | |
| 489 | + | |
| 490 | + /* month restriction */ | |
| 491 | + if (!field_is_full(c.mon, 1, 12)) { | |
| 492 | + int n = count_set(c.mon, 1, 12); | |
| 493 | + int i; | |
| 494 | + if (n == 1) { | |
| 495 | + snprintf(day, sizeof(day), "in %s", k_mon_long[first_set(c.mon, 1, 12) - 1]); | |
| 496 | + } else { | |
| 497 | + int first = 1; | |
| 498 | + sapp(day, sizeof(day), "in "); | |
| 499 | + for (i = 1; i <= 12; i++) { | |
| 500 | + if (!c.mon[i]) continue; | |
| 501 | + sapp(day, sizeof(day), first ? "" : ", "); | |
| 502 | + sapp(day, sizeof(day), k_mon_long[i - 1]); | |
| 503 | + first = 0; | |
| 504 | + } | |
| 505 | + } | |
| 506 | + } | |
| 507 | + | |
| 508 | + /* day-of-month / day-of-week (classic OR semantics when both restricted) */ | |
| 509 | + if (c.dom_restricted && c.dow_restricted) { | |
| 510 | + int ndow = count_set(c.dow, 0, 6); | |
| 511 | + int ndom = count_set(c.dom, 1, 31); | |
| 512 | + char part[96]; | |
| 513 | + part[0] = '\0'; | |
| 514 | + if (ndow == 1) { | |
| 515 | + sapp(part, sizeof(part), k_dow_long[first_set(c.dow, 0, 6)]); | |
| 516 | + } else { | |
| 517 | + int i, first = 1; | |
| 518 | + for (i = 0; i < 7; i++) { | |
| 519 | + if (!c.dow[i]) continue; | |
| 520 | + sapp(part, sizeof(part), first ? "" : ", "); | |
| 521 | + sapp(part, sizeof(part), k_dow_long[i]); | |
| 522 | + first = 0; | |
| 523 | + } | |
| 524 | + } | |
| 525 | + sapp(day, sizeof(day), day[0] ? " " : ""); | |
| 526 | + sapp(day, sizeof(day), "on "); | |
| 527 | + sapp(day, sizeof(day), part); | |
| 528 | + if (ndom == 1) { | |
| 529 | + char t[32]; | |
| 530 | + snprintf(t, sizeof(t), " or day %d of the month", first_set(c.dom, 1, 31)); | |
| 531 | + sapp(day, sizeof(day), t); | |
| 532 | + } else { | |
| 533 | + sapp(day, sizeof(day), " or on selected days of the month"); | |
| 534 | + } | |
| 535 | + } else if (c.dow_restricted) { | |
| 536 | + int ndow = count_set(c.dow, 0, 6); | |
| 537 | + sapp(day, sizeof(day), day[0] ? " " : ""); | |
| 538 | + sapp(day, sizeof(day), "on "); | |
| 539 | + if (ndow == 1) { | |
| 540 | + sapp(day, sizeof(day), k_dow_long[first_set(c.dow, 0, 6)]); | |
| 541 | + } else { | |
| 542 | + int i, first = 1; | |
| 543 | + for (i = 0; i < 7; i++) { | |
| 544 | + if (!c.dow[i]) continue; | |
| 545 | + sapp(day, sizeof(day), first ? "" : ", "); | |
| 546 | + sapp(day, sizeof(day), k_dow_long[i]); | |
| 547 | + first = 0; | |
| 548 | + } | |
| 549 | + } | |
| 550 | + } else if (c.dom_restricted) { | |
| 551 | + int ndom = count_set(c.dom, 1, 31); | |
| 552 | + sapp(day, sizeof(day), day[0] ? " " : ""); | |
| 553 | + if (ndom == 1) { | |
| 554 | + char t[32]; | |
| 555 | + snprintf(t, sizeof(t), "on day %d of the month", first_set(c.dom, 1, 31)); | |
| 556 | + sapp(day, sizeof(day), t); | |
| 557 | + } else if (c.f[2][0] == '*' && c.f[2][1] == '/') { | |
| 558 | + char t[48]; | |
| 559 | + snprintf(t, sizeof(t), "every %d days of the month", atoi(c.f[2] + 2)); | |
| 560 | + sapp(day, sizeof(day), t); | |
| 561 | + } else { | |
| 562 | + int i, first = 1; | |
| 563 | + sapp(day, sizeof(day), "on days "); | |
| 564 | + for (i = 1; i <= 31; i++) { | |
| 565 | + char t[8]; | |
| 566 | + if (!c.dom[i]) continue; | |
| 567 | + snprintf(t, sizeof(t), "%s%d", first ? "" : ", ", i); | |
| 568 | + sapp(day, sizeof(day), t); | |
| 569 | + first = 0; | |
| 570 | + } | |
| 571 | + sapp(day, sizeof(day), " of the month"); | |
| 572 | + } | |
| 573 | + } | |
| 574 | + | |
| 575 | + if (day[0]) { | |
| 576 | + char full[MAX_DESC]; | |
| 577 | + snprintf(full, sizeof(full), "%s, %s", out, day); | |
| 578 | + str_copy(out, sz, full); | |
| 579 | + } else if (strncmp(out, "At ", 3) == 0) { | |
| 580 | + sapp(out, sz, ", every day"); | |
| 581 | + } | |
| 582 | +} | |
| 583 | +/* ---------------------------------------------------------------- */ | |
| 584 | +/* Expression parsing */ | |
| 585 | +/* ---------------------------------------------------------------- */ | |
| 586 | + | |
| 587 | +static void apply_keyword(cron_t *c, const char *kw) | |
| 588 | +{ | |
| 589 | + int i; | |
| 590 | + for (i = 0; i < 60; i++) c->min[i] = 1; | |
| 591 | + for (i = 0; i < 24; i++) c->hour[i] = 1; | |
| 592 | + for (i = 0; i <= 31; i++) c->dom[i] = 1; | |
| 593 | + for (i = 0; i <= 12; i++) c->mon[i] = 1; | |
| 594 | + for (i = 0; i < 7; i++) c->dow[i] = 1; | |
| 595 | + | |
| 596 | + if (strcmp(kw, "@reboot") == 0) { | |
| 597 | + c->boot_only = 1; | |
| 598 | + return; | |
| 599 | + } | |
| 600 | + memset(c->min, 0, sizeof(c->min)); | |
| 601 | + c->min[0] = 1; | |
| 602 | + if (strcmp(kw, "@hourly") == 0) { | |
| 603 | + memset(c->hour, 0, sizeof(c->hour)); | |
| 604 | + for (i = 0; i < 24; i++) c->hour[i] = 1; | |
| 605 | + return; | |
| 606 | + } | |
| 607 | + memset(c->hour, 0, sizeof(c->hour)); | |
| 608 | + c->hour[0] = 1; | |
| 609 | + if (strcmp(kw, "@daily") == 0 || strcmp(kw, "@midnight") == 0) return; | |
| 610 | + if (strcmp(kw, "@weekly") == 0) { | |
| 611 | + memset(c->dow, 0, sizeof(c->dow)); | |
| 612 | + c->dow[0] = 1; | |
| 613 | + c->dow_restricted = 1; | |
| 614 | + return; | |
| 615 | + } | |
| 616 | + if (strcmp(kw, "@monthly") == 0) { | |
| 617 | + memset(c->dom, 0, sizeof(c->dom)); | |
| 618 | + c->dom[1] = 1; | |
| 619 | + c->dom_restricted = 1; | |
| 620 | + return; | |
| 621 | + } | |
| 622 | + if (strcmp(kw, "@yearly") == 0 || strcmp(kw, "@annually") == 0) { | |
| 623 | + memset(c->dom, 0, sizeof(c->dom)); | |
| 624 | + memset(c->mon, 0, sizeof(c->mon)); | |
| 625 | + c->dom[1] = 1; | |
| 626 | + c->mon[1] = 1; | |
| 627 | + c->dom_restricted = 1; | |
| 628 | + return; | |
| 629 | + } | |
| 630 | + /* continue for @hourly handled above */ | |
| 631 | +} | |
| 632 | + | |
| 633 | +/* | |
| 634 | + * Parse a full cron expression: either "@keyword" or five whitespace-separated | |
| 635 | + * fields. Fills c->valid / c->error. Returns c->valid. | |
| 636 | + * The expression is trimmed in place into c->raw. | |
| 637 | + */ | |
| 638 | +static int cron_parse(cron_t *c, const char *expr) | |
| 639 | +{ | |
| 640 | + char work[MAX_EXPR * 2]; | |
| 641 | + char *tok[8]; | |
| 642 | + int ntok = 0; | |
| 643 | + int rc; | |
| 644 | + char *p; | |
| 645 | + | |
| 646 | + cron_clear(c); | |
| 647 | + str_copy(c->raw, sizeof(c->raw), expr ? expr : ""); | |
| 648 | + str_copy(work, sizeof(work), c->raw); | |
| 649 | + str_trim(work); | |
| 650 | + | |
| 651 | + if (!work[0]) { | |
| 652 | + str_copy(c->error, sizeof(c->error), "empty expression"); | |
| 653 | + return 0; | |
| 654 | + } | |
| 655 | + | |
| 656 | + if (work[0] == '@') { | |
| 657 | + char kw[24]; | |
| 658 | + str_copy(kw, sizeof(kw), work); | |
| 659 | + str_trim(kw); | |
| 660 | + if (strcmp(kw, "@reboot") != 0 && strcmp(kw, "@hourly") != 0 | |
| 661 | + && strcmp(kw, "@daily") != 0 && strcmp(kw, "@midnight") != 0 | |
| 662 | + && strcmp(kw, "@weekly") != 0 && strcmp(kw, "@monthly") != 0 | |
| 663 | + && strcmp(kw, "@yearly") != 0 && strcmp(kw, "@annually") != 0) { | |
| 664 | + str_copy(c->error, sizeof(c->error), "unknown @keyword"); | |
| 665 | + return 0; | |
| 666 | + } | |
| 667 | + str_copy(c->keyword, sizeof(c->keyword), kw); | |
| 668 | + apply_keyword(c, kw); | |
| 669 | + c->dom_restricted = c->dom_restricted || 0; | |
| 670 | + c->valid = 1; | |
| 671 | + cron_describe(c, c->desc, sizeof(c->desc)); | |
| 672 | + return 1; | |
| 673 | + } | |
| 674 | + | |
| 675 | + for (p = work; *p && ntok < 8; ) { | |
| 676 | + while (*p && isspace((unsigned char)*p)) *p++ = '\0'; | |
| 677 | + if (!*p) break; | |
| 678 | + tok[ntok++] = p; | |
| 679 | + while (*p && !isspace((unsigned char)*p)) p++; | |
| 680 | + } | |
| 681 | + if (ntok != 5) { | |
| 682 | + str_copy(c->error, sizeof(c->error), | |
| 683 | + ntok < 5 ? "expected 5 fields" : "too many fields"); | |
| 684 | + return 0; | |
| 685 | + } | |
| 686 | + | |
| 687 | + { | |
| 688 | + int i; | |
| 689 | + for (i = 0; i < 5; i++) str_copy(c->f[i], sizeof(c->f[i]), tok[i]); | |
| 690 | + } | |
| 691 | + | |
| 692 | + rc = parse_field(c->f[0], 0, 59, NULL, 0, 0, c->min); | |
| 693 | + if (rc <= 0) { | |
| 694 | + str_copy(c->error, sizeof(c->error), rc < 0 ? "minute out of range 0-59" : "bad minute field"); | |
| 695 | + return 0; | |
| 696 | + } | |
| 697 | + rc = parse_field(c->f[1], 0, 23, NULL, 0, 0, c->hour); | |
| 698 | + if (rc <= 0) { | |
| 699 | + str_copy(c->error, sizeof(c->error), rc < 0 ? "hour out of range 0-23" : "bad hour field"); | |
| 700 | + return 0; | |
| 701 | + } | |
| 702 | + rc = parse_field(c->f[2], 1, 31, NULL, 0, 0, c->dom); | |
| 703 | + if (rc <= 0) { | |
| 704 | + str_copy(c->error, sizeof(c->error), rc < 0 ? "day-of-month out of range 1-31" : "bad day-of-month field"); | |
| 705 | + return 0; | |
| 706 | + } | |
| 707 | + rc = parse_field(c->f[3], 1, 12, k_mon_names, 12, 1, c->mon); | |
| 708 | + if (rc <= 0) { | |
| 709 | + str_copy(c->error, sizeof(c->error), rc < 0 ? "month out of range 1-12" : "bad month field"); | |
| 710 | + return 0; | |
| 711 | + } | |
| 712 | + { | |
| 713 | + unsigned char tmpdow[8]; | |
| 714 | + int i; | |
| 715 | + rc = parse_field(c->f[4], 0, 7, k_dow_names, 7, 0, tmpdow); | |
| 716 | + if (rc <= 0) { | |
| 717 | + str_copy(c->error, sizeof(c->error), rc < 0 ? "day-of-week out of range 0-7" : "bad day-of-week field"); | |
| 718 | + return 0; | |
| 719 | + } | |
| 720 | + memset(c->dow, 0, sizeof(c->dow)); | |
| 721 | + for (i = 0; i <= 7; i++) | |
| 722 | + if (tmpdow[i]) c->dow[i % 7] = 1; | |
| 723 | + } | |
| 724 | + | |
| 725 | + c->dom_restricted = !field_is_full(c->dom, 1, 31); | |
| 726 | + c->dow_restricted = !field_is_full(c->dow, 0, 6); | |
| 727 | + | |
| 728 | + c->valid = 1; | |
| 729 | + cron_describe(c, c->desc, sizeof(c->desc)); | |
| 730 | + return 1; | |
| 731 | +} | |
| 732 | + | |
| 733 | +/* Day-of-week for a broken-down UTC time; 0 == Sunday. */ | |
| 734 | +static int tm_dow(const struct tm *t) | |
| 735 | +{ | |
| 736 | + return t->tm_wday; | |
| 737 | +} | |
| 738 | + | |
| 739 | +static int day_matches(const cron_t *c, const struct tm *day) | |
| 740 | +{ | |
| 741 | + int dom_ok = c->dom[day->tm_mday] ? 1 : 0; | |
| 742 | + int dow_ok = c->dow[tm_dow(day)] ? 1 : 0; | |
| 743 | + | |
| 744 | + if (!c->mon[day->tm_mon + 1]) return 0; | |
| 745 | + if (c->dom_restricted && c->dow_restricted) return dom_ok || dow_ok; | |
| 746 | + if (c->dom_restricted) return dom_ok; | |
| 747 | + if (c->dow_restricted) return dow_ok; | |
| 748 | + return 1; | |
| 749 | +} | |
| 750 | + | |
| 751 | +/* | |
| 752 | + * Compute the next `want` firing times strictly after `from` (UTC). | |
| 753 | + * Iterates day by day, then within matching days iterates hours and minutes | |
| 754 | + * using the parsed bitmaps. Returns the number of timestamps written. | |
| 755 | + */ | |
| 756 | +static int cron_next_runs(const cron_t *c, time_t from, time_t *out, int want) | |
| 757 | +{ | |
| 758 | + struct tm base; | |
| 759 | + int got = 0; | |
| 760 | + int d; | |
| 761 | + | |
| 762 | + if (!c->valid || c->boot_only) return 0; | |
| 763 | + | |
| 764 | + { | |
| 765 | + time_t t = from; | |
| 766 | +#if defined(_WIN32) | |
| 767 | + gmtime_s(&base, &t); | |
| 768 | +#else | |
| 769 | + gmtime_r(&t, &base); | |
| 770 | +#endif | |
| 771 | + } | |
| 772 | + | |
| 773 | + for (d = 0; d < HORIZON_DAYS && got < want; d++) { | |
| 774 | + struct tm day; | |
| 775 | + time_t day_start; | |
| 776 | + int h, m; | |
| 777 | + | |
| 778 | + day = base; | |
| 779 | + day.tm_mday += d; | |
| 780 | + day.tm_hour = 0; | |
| 781 | + day.tm_min = 0; | |
| 782 | + day.tm_sec = 0; | |
| 783 | + day.tm_isdst = 0; | |
| 784 | + day_start = timegm_portable(&day); | |
| 785 | + if (day_start == (time_t)-1) continue; | |
| 786 | +#if defined(_WIN32) | |
| 787 | + gmtime_s(&day, &day_start); | |
| 788 | +#else | |
| 789 | + gmtime_r(&day_start, &day); | |
| 790 | +#endif | |
| 791 | + if (!day_matches(c, &day)) continue; | |
| 792 | + | |
| 793 | + for (h = 0; h < 24 && got < want; h++) { | |
| 794 | + if (!c->hour[h]) continue; | |
| 795 | + for (m = 0; m < 60 && got < want; m++) { | |
| 796 | + time_t cand; | |
| 797 | + if (!c->min[m]) continue; | |
| 798 | + cand = day_start + (time_t)h * 3600 + (time_t)m * 60; | |
| 799 | + if (cand <= from) continue; | |
| 800 | + out[got++] = cand; | |
| 801 | + } | |
| 802 | + } | |
| 803 | + } | |
| 804 | + return got; | |
| 805 | +} | |
| 806 | +/* ---------------------------------------------------------------- */ | |
| 807 | +/* Job collection */ | |
| 808 | +/* ---------------------------------------------------------------- */ | |
| 809 | + | |
| 810 | +typedef struct { | |
| 811 | + char source[MAX_SRC]; | |
| 812 | + char expr[MAX_EXPR]; | |
| 813 | + char command[MAX_CMD]; | |
| 814 | + char user[64]; | |
| 815 | + char kind[12]; /* "cron" or "task" */ | |
| 816 | + int valid; | |
| 817 | + char error[96]; | |
| 818 | + char desc[MAX_DESC]; | |
| 819 | + int next_count; | |
| 820 | + time_t next[MAX_RUNS]; | |
| 821 | +} job_t; | |
| 822 | + | |
| 823 | +static job_t g_jobs[MAX_JOBS]; | |
| 824 | +static int g_job_count; | |
| 825 | +static char g_sources[16][MAX_SRC]; | |
| 826 | +static int g_source_count; | |
| 827 | +static int g_truncated; | |
| 828 | + | |
| 829 | +static void note_source(const char *name) | |
| 830 | +{ | |
| 831 | + int i; | |
| 832 | + if (!name || !*name) return; | |
| 833 | + for (i = 0; i < g_source_count; i++) | |
| 834 | + if (strcmp(g_sources[i], name) == 0) return; | |
| 835 | + if (g_source_count < (int)(sizeof(g_sources) / sizeof(g_sources[0]))) | |
| 836 | + str_copy(g_sources[g_source_count++], MAX_SRC, name); | |
| 837 | +} | |
| 838 | + | |
| 839 | +static job_t *job_new(void) | |
| 840 | +{ | |
| 841 | + job_t *j; | |
| 842 | + if (g_job_count >= MAX_JOBS) { g_truncated = 1; return NULL; } | |
| 843 | + j = &g_jobs[g_job_count++]; | |
| 844 | + memset(j, 0, sizeof(*j)); | |
| 845 | + return j; | |
| 846 | +} | |
| 847 | + | |
| 848 | +/* Skip blank lines, comments and environment assignments. */ | |
| 849 | +static int cron_line_skippable(const char *s) | |
| 850 | +{ | |
| 851 | + const char *p; | |
| 852 | + | |
| 853 | + if (!s) return 1; | |
| 854 | + while (*s && isspace((unsigned char)*s)) s++; | |
| 855 | + if (!*s) return 1; | |
| 856 | + if (*s == '#') return 1; | |
| 857 | + /* NAME = value (no whitespace inside the name) */ | |
| 858 | + for (p = s; *p && (isalnum((unsigned char)*p) || *p == '_'); p++) ; | |
| 859 | + if (p > s && *p == '=') return 1; | |
| 860 | + return 0; | |
| 861 | +} | |
| 862 | + | |
| 863 | +/* | |
| 864 | + * Split one crontab line into an expression and a command. | |
| 865 | + * system format: 5 fields, user, command (/etc/crontab, /etc/cron.d entries) | |
| 866 | + * user format: 5 fields, command (crontab -l) | |
| 867 | + * Returns 1 on success. | |
| 868 | + */ | |
| 869 | +static int split_cron_line(const char *line, int system_format, | |
| 870 | + char *expr, size_t expr_sz, | |
| 871 | + char *user, size_t user_sz, | |
| 872 | + char *cmd, size_t cmd_sz) | |
| 873 | +{ | |
| 874 | + char work[READ_LINE]; | |
| 875 | + char *p; | |
| 876 | + int fields_needed = system_format ? 6 : 5; | |
| 877 | + int got = 0; | |
| 878 | + | |
| 879 | + expr[0] = user[0] = cmd[0] = '\0'; | |
| 880 | + str_copy(work, sizeof(work), line); | |
| 881 | + str_trim(work); | |
| 882 | + if (!work[0]) return 0; | |
| 883 | + | |
| 884 | + /* @keyword form */ | |
| 885 | + if (work[0] == '@') { | |
| 886 | + p = work; | |
| 887 | + while (*p && !isspace((unsigned char)*p)) p++; | |
| 888 | + str_copy(expr, expr_sz, work); | |
| 889 | + expr[strlen(work) - strlen(p) >= expr_sz ? expr_sz - 1 : strlen(work) - strlen(p)] = '\0'; | |
| 890 | + if (*p) { | |
| 891 | + char *rest = p; | |
| 892 | + while (*rest && isspace((unsigned char)*rest)) rest++; | |
| 893 | + if (system_format) { | |
| 894 | + char *u = rest; | |
| 895 | + while (*u && !isspace((unsigned char)*u)) u++; | |
| 896 | + str_copy(user, user_sz, rest); | |
| 897 | + user[strlen(rest) - strlen(u) >= user_sz ? user_sz - 1 : strlen(rest) - strlen(u)] = '\0'; | |
| 898 | + while (*u && isspace((unsigned char)*u)) u++; | |
| 899 | + str_copy(cmd, cmd_sz, u); | |
| 900 | + } else { | |
| 901 | + str_copy(cmd, cmd_sz, rest); | |
| 902 | + } | |
| 903 | + } | |
| 904 | + return 1; | |
| 905 | + } | |
| 906 | + | |
| 907 | + p = work; | |
| 908 | + while (*p && got < fields_needed) { | |
| 909 | + char *start; | |
| 910 | + while (*p && isspace((unsigned char)*p)) p++; | |
| 911 | + if (!*p) break; | |
| 912 | + start = p; | |
| 913 | + while (*p && !isspace((unsigned char)*p)) p++; | |
| 914 | + if (got < 5) { | |
| 915 | + size_t len = (size_t)(p - start); | |
| 916 | + size_t have = strlen(expr); | |
| 917 | + if (have + len + 2 < expr_sz) { | |
| 918 | + if (have) expr[have++] = ' '; | |
| 919 | + memcpy(expr + have, start, len); | |
| 920 | + expr[have + len] = '\0'; | |
| 921 | + } | |
| 922 | + } else { | |
| 923 | + size_t len = (size_t)(p - start); | |
| 924 | + if (len >= user_sz) len = user_sz - 1; | |
| 925 | + memcpy(user, start, len); | |
| 926 | + user[len] = '\0'; | |
| 927 | + } | |
| 928 | + got++; | |
| 929 | + } | |
| 930 | + if (got < fields_needed) return 0; | |
| 931 | + while (*p && isspace((unsigned char)*p)) p++; | |
| 932 | + str_copy(cmd, cmd_sz, p); | |
| 933 | + return 1; | |
| 934 | +} | |
| 935 | + | |
| 936 | +static void add_cron_job(const char *source, const char *line, int system_format, time_t now) | |
| 937 | +{ | |
| 938 | + char expr[MAX_EXPR], user[64], cmd[MAX_CMD]; | |
| 939 | + job_t *j; | |
| 940 | + | |
| 941 | + if (!split_cron_line(line, system_format, expr, sizeof(expr), | |
| 942 | + user, sizeof(user), cmd, sizeof(cmd))) | |
| 943 | + return; | |
| 944 | + if (!expr[0]) return; | |
| 945 | + | |
| 946 | + j = job_new(); | |
| 947 | + if (!j) return; | |
| 948 | + | |
| 949 | + str_copy(j->source, sizeof(j->source), source); | |
| 950 | + str_copy(j->expr, sizeof(j->expr), expr); | |
| 951 | + str_copy(j->command, sizeof(j->command), cmd); | |
| 952 | + str_copy(j->user, sizeof(j->user), user); | |
| 953 | + str_copy(j->kind, sizeof(j->kind), "cron"); | |
| 954 | + | |
| 955 | + { | |
| 956 | + cron_t c; | |
| 957 | + if (cron_parse(&c, expr)) { | |
| 958 | + j->valid = 1; | |
| 959 | + str_copy(j->desc, sizeof(j->desc), c.desc); | |
| 960 | + if (c.boot_only) | |
| 961 | + str_copy(j->desc, sizeof(j->desc), "When the system starts (no scheduled times)"); | |
| 962 | + else | |
| 963 | + j->next_count = cron_next_runs(&c, now, j->next, MAX_RUNS); | |
| 964 | + } else { | |
| 965 | + j->valid = 0; | |
| 966 | + str_copy(j->error, sizeof(j->error), c.error); | |
| 967 | + str_copy(j->desc, sizeof(j->desc), "Unrecognised schedule expression"); | |
| 968 | + } | |
| 969 | + } | |
| 970 | + note_source(source); | |
| 971 | +} | |
| 972 | + | |
| 973 | +#if defined(_WIN32) | |
| 974 | +static void add_task_job(const char *name, const char *nextrun, const char *status, time_t now) | |
| 975 | +{ | |
| 976 | + job_t *j = job_new(); | |
| 977 | + (void)now; | |
| 978 | + if (!j) return; | |
| 979 | + | |
| 980 | + str_copy(j->source, sizeof(j->source), "schtasks"); | |
| 981 | + str_copy(j->kind, sizeof(j->kind), "task"); | |
| 982 | + str_copy(j->expr, sizeof(j->expr), "task"); | |
| 983 | + str_copy(j->command, sizeof(j->command), name); | |
| 984 | + str_copy(j->user, sizeof(j->user), ""); | |
| 985 | + j->valid = 1; | |
| 986 | + { | |
| 987 | + char d[MAX_DESC]; | |
| 988 | + snprintf(d, sizeof(d), "%s%s%s", | |
| 989 | + status && *status ? status : "Scheduled Windows task", | |
| 990 | + nextrun && *nextrun && strcmp(nextrun, "N/A") != 0 ? " - next " : "", | |
| 991 | + nextrun && *nextrun && strcmp(nextrun, "N/A") != 0 ? nextrun : ""); | |
| 992 | + str_copy(j->desc, sizeof(j->desc), d); | |
| 993 | + } | |
| 994 | + note_source("schtasks"); | |
| 995 | +} | |
| 996 | + | |
| 997 | +#endif | |
| 998 | + | |
| 999 | +/* Feed a whole file (or popen stream) of crontab lines. */ | |
| 1000 | +static void ingest_lines(FILE *fp, const char *source, int system_format, time_t now) | |
| 1001 | +{ | |
| 1002 | + char line[READ_LINE]; | |
| 1003 | + int forced = system_format; | |
| 1004 | + | |
| 1005 | + while (fp && fgets(line, sizeof(line), fp)) { | |
| 1006 | + char probe[READ_LINE]; | |
| 1007 | + size_t n = strlen(line); | |
| 1008 | + while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = '\0'; | |
| 1009 | + str_copy(probe, sizeof(probe), line); | |
| 1010 | + str_trim(probe); | |
| 1011 | + | |
| 1012 | + /* fixture directives: "# sx:system" / "# sx:user" / "# sx:source NAME" */ | |
| 1013 | + if (strncmp(probe, "# sx:", 5) == 0) { | |
| 1014 | + const char *d = probe + 5; | |
| 1015 | + if (strncmp(d, "system", 6) == 0) { forced = 1; continue; } | |
| 1016 | + if (strncmp(d, "user", 4) == 0) { forced = 0; continue; } | |
| 1017 | + continue; | |
| 1018 | + } | |
| 1019 | + if (cron_line_skippable(line)) continue; | |
| 1020 | + add_cron_job(source, line, forced, now); | |
| 1021 | + } | |
| 1022 | +} | |
| 1023 | + | |
| 1024 | +static void ingest_file(const char *path, const char *source, int system_format, time_t now) | |
| 1025 | +{ | |
| 1026 | + FILE *fp = fopen(path, "r"); | |
| 1027 | + if (!fp) return; | |
| 1028 | + ingest_lines(fp, source, system_format, now); | |
| 1029 | + fclose(fp); | |
| 1030 | +} | |
| 1031 | + | |
| 1032 | +#if !defined(_WIN32) | |
| 1033 | +static void ingest_command(const char *cmd, const char *source, time_t now) | |
| 1034 | +{ | |
| 1035 | + FILE *fp = sx_popen(cmd, "r"); | |
| 1036 | + if (!fp) return; | |
| 1037 | + ingest_lines(fp, source, 0, now); | |
| 1038 | + sx_pclose(fp); | |
| 1039 | +} | |
| 1040 | +#endif | |
| 1041 | + | |
| 1042 | +#if defined(_WIN32) | |
| 1043 | +/* Minimal CSV field splitter for `schtasks /Query /FO CSV`. */ | |
| 1044 | +static void ingest_schtasks(time_t now) | |
| 1045 | +{ | |
| 1046 | + FILE *fp = sx_popen("schtasks /Query /FO CSV /NH", "r"); | |
| 1047 | + char line[READ_LINE]; | |
| 1048 | + | |
| 1049 | + if (!fp) return; | |
| 1050 | + while (fgets(line, sizeof(line), fp)) { | |
| 1051 | + char f[4][256]; | |
| 1052 | + int nf = 0; | |
| 1053 | + char *p = line; | |
| 1054 | + size_t n = strlen(line); | |
| 1055 | + while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = '\0'; | |
| 1056 | + | |
| 1057 | + while (*p && nf < 4) { | |
| 1058 | + char *out = f[nf]; | |
| 1059 | + size_t oi = 0; | |
| 1060 | + if (*p == '"') { | |
| 1061 | + p++; | |
| 1062 | + while (*p && *p != '"' && oi + 1 < 256) { | |
| 1063 | + if (*p == '"' && p[1] == '"') { out[oi++] = '"'; p += 2; continue; } | |
| 1064 | + out[oi++] = *p++; | |
| 1065 | + } | |
| 1066 | + if (*p == '"') p++; | |
| 1067 | + } else { | |
| 1068 | + while (*p && *p != ',' && oi + 1 < 256) out[oi++] = *p++; | |
| 1069 | + } | |
| 1070 | + out[oi] = '\0'; | |
| 1071 | + nf++; | |
| 1072 | + if (*p == ',') p++; | |
| 1073 | + } | |
| 1074 | + if (nf >= 2 && f[0][0] && strcmp(f[0], "TaskName") != 0) | |
| 1075 | + add_task_job(f[0], f[1], nf > 2 ? f[2] : "", now); | |
| 1076 | + } | |
| 1077 | + sx_pclose(fp); | |
| 1078 | +} | |
| 1079 | +#endif | |
| 1080 | + | |
| 1081 | +static void collect_jobs(void) | |
| 1082 | +{ | |
| 1083 | + time_t now = time(NULL); | |
| 1084 | + const char *fixture = getenv("CRONTAB_FILE"); | |
| 1085 | + | |
| 1086 | + g_job_count = 0; | |
| 1087 | + g_source_count = 0; | |
| 1088 | + g_truncated = 0; | |
| 1089 | + | |
| 1090 | + if (fixture && *fixture) { | |
| 1091 | + ingest_file(fixture, "fixture", 0, now); | |
| 1092 | + return; | |
| 1093 | + } | |
| 1094 | + | |
| 1095 | +#if defined(_WIN32) | |
| 1096 | + ingest_schtasks(now); | |
| 1097 | +#else | |
| 1098 | + ingest_command("crontab -l 2>/dev/null", "user", now); | |
| 1099 | + ingest_file("/etc/crontab", "/etc/crontab", 1, now); | |
| 1100 | + { | |
| 1101 | + DIR *d = opendir("/etc/cron.d"); | |
| 1102 | + struct dirent *ent; | |
| 1103 | + if (d) { | |
| 1104 | + while ((ent = readdir(d)) != NULL) { | |
| 1105 | + char path[512]; | |
| 1106 | + char label[MAX_SRC]; | |
| 1107 | + if (ent->d_name[0] == '.') continue; | |
| 1108 | + snprintf(path, sizeof(path), "/etc/cron.d/%s", ent->d_name); | |
| 1109 | + snprintf(label, sizeof(label), "/etc/cron.d/%.40s", ent->d_name); | |
| 1110 | + ingest_file(path, label, 1, now); | |
| 1111 | + } | |
| 1112 | + closedir(d); | |
| 1113 | + } | |
| 1114 | + } | |
| 1115 | +#endif | |
| 1116 | +} | |
| 1117 | +/* ---------------------------------------------------------------- */ | |
| 1118 | +/* HTTP plumbing */ | |
| 1119 | +/* ---------------------------------------------------------------- */ | |
| 1120 | + | |
| 1121 | +static void json_header(void) | |
| 1122 | +{ | |
| 1123 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 1124 | + "Cache-Control: no-store\r\n" | |
| 1125 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1126 | +} | |
| 1127 | + | |
| 1128 | +static void print_runs(const time_t *runs, int count, time_t now) | |
| 1129 | +{ | |
| 1130 | + int i; | |
| 1131 | + char utc[40], loc[40]; | |
| 1132 | + | |
| 1133 | + putchar('['); | |
| 1134 | + for (i = 0; i < count; i++) { | |
| 1135 | + utc_stamp(runs[i], utc, sizeof(utc)); | |
| 1136 | + local_stamp(runs[i], loc, sizeof(loc)); | |
| 1137 | + if (i) putchar(','); | |
| 1138 | + fputs("{\"utc\":", stdout); | |
| 1139 | + json_str(utc); | |
| 1140 | + fputs(",\"local\":", stdout); | |
| 1141 | + json_str(loc); | |
| 1142 | + printf(",\"in_seconds\":%ld}", (long)(runs[i] - now)); | |
| 1143 | + } | |
| 1144 | + putchar(']'); | |
| 1145 | +} | |
| 1146 | + | |
| 1147 | +static int mode_meta(void) | |
| 1148 | +{ | |
| 1149 | + fputs("{\"name\":\"crontab\",\"desc\":\"Cron jobs\"}\n", stdout); | |
| 1150 | + return 0; | |
| 1151 | +} | |
| 1152 | + | |
| 1153 | +/* Field text for a keyword schedule, for the JSON fields block. */ | |
| 1154 | +static void cron_keyword_fields(const cron_t *c, char kf[5][12]) | |
| 1155 | +{ | |
| 1156 | + if (!c->keyword[0]) { | |
| 1157 | + int i; | |
| 1158 | + for (i = 0; i < 5; i++) str_copy(kf[i], 12, c->f[i]); | |
| 1159 | + return; | |
| 1160 | + } | |
| 1161 | + str_copy(kf[0], 12, "0"); | |
| 1162 | + str_copy(kf[1], 12, "0"); | |
| 1163 | + str_copy(kf[2], 12, "*"); | |
| 1164 | + str_copy(kf[3], 12, "*"); | |
| 1165 | + str_copy(kf[4], 12, "*"); | |
| 1166 | + if (strcmp(c->keyword, "@reboot") == 0) { | |
| 1167 | + int i; | |
| 1168 | + for (i = 0; i < 5; i++) str_copy(kf[i], 12, "@reboot"); | |
| 1169 | + } else if (strcmp(c->keyword, "@hourly") == 0) { | |
| 1170 | + str_copy(kf[1], 12, "*"); | |
| 1171 | + } else if (strcmp(c->keyword, "@weekly") == 0) { | |
| 1172 | + str_copy(kf[4], 12, "0"); | |
| 1173 | + } else if (strcmp(c->keyword, "@monthly") == 0) { | |
| 1174 | + str_copy(kf[2], 12, "1"); | |
| 1175 | + } else if (strcmp(c->keyword, "@yearly") == 0 || strcmp(c->keyword, "@annually") == 0) { | |
| 1176 | + str_copy(kf[2], 12, "1"); | |
| 1177 | + str_copy(kf[3], 12, "1"); | |
| 1178 | + } | |
| 1179 | +} | |
| 1180 | + | |
| 1181 | +static int mode_json(const char *qs) | |
| 1182 | +{ | |
| 1183 | + char action[64]; | |
| 1184 | + char expr[MAX_EXPR * 2]; | |
| 1185 | + time_t now = time(NULL); | |
| 1186 | + | |
| 1187 | + action[0] = '\0'; | |
| 1188 | + get_query_val(qs, "action", action, sizeof(action)); | |
| 1189 | + | |
| 1190 | + json_header(); | |
| 1191 | + | |
| 1192 | + if (strcmp(action, "explain") == 0) { | |
| 1193 | + cron_t c; | |
| 1194 | + time_t runs[MAX_RUNS]; | |
| 1195 | + int n = 0; | |
| 1196 | + char nowutc[40]; | |
| 1197 | + char nowloc[40]; | |
| 1198 | + | |
| 1199 | + get_query_val(qs, "expr", expr, sizeof(expr)); | |
| 1200 | + utc_stamp(now, nowutc, sizeof(nowutc)); | |
| 1201 | + local_stamp(now, nowloc, sizeof(nowloc)); | |
| 1202 | + | |
| 1203 | + if (!expr[0]) { | |
| 1204 | + fputs("{\"ok\":false,\"error\":\"missing expr parameter\",\"valid\":false}\n", stdout); | |
| 1205 | + return 0; | |
| 1206 | + } | |
| 1207 | + | |
| 1208 | + if (cron_parse(&c, expr)) { | |
| 1209 | + if (!c.boot_only) n = cron_next_runs(&c, now, runs, MAX_RUNS); | |
| 1210 | + } else { | |
| 1211 | + fputs("{\"ok\":true,\"action\":\"explain\",\"expr\":", stdout); | |
| 1212 | + json_str(expr); | |
| 1213 | + fputs(",\"valid\":false,\"error\":", stdout); | |
| 1214 | + json_str(c.error[0] ? c.error : "invalid expression"); | |
| 1215 | + fputs(",\"description\":\"\",\"keyword\":\"\",\"next\":[]," | |
| 1216 | + "\"now_utc\":", stdout); | |
| 1217 | + json_str(nowutc); | |
| 1218 | + fputs(",\"now_local\":", stdout); | |
| 1219 | + json_str(nowloc); | |
| 1220 | + fputs("}\n", stdout); | |
| 1221 | + return 0; | |
| 1222 | + } | |
| 1223 | + | |
| 1224 | + fputs("{\"ok\":true,\"action\":\"explain\",\"expr\":", stdout); | |
| 1225 | + json_str(expr); | |
| 1226 | + fputs(",\"valid\":true,\"keyword\":", stdout); | |
| 1227 | + json_str(c.keyword); | |
| 1228 | + fputs(",\"description\":", stdout); | |
| 1229 | + json_str(c.desc); | |
| 1230 | + fputs(",\"normalized\":", stdout); | |
| 1231 | + if (c.keyword[0]) { | |
| 1232 | + json_str(c.keyword); | |
| 1233 | + } else { | |
| 1234 | + char norm[220]; | |
| 1235 | + snprintf(norm, sizeof(norm), "%s %s %s %s %s", | |
| 1236 | + c.f[0], c.f[1], c.f[2], c.f[3], c.f[4]); | |
| 1237 | + json_str(norm); | |
| 1238 | + } | |
| 1239 | + { | |
| 1240 | + char kf[5][12]; | |
| 1241 | + cron_keyword_fields(&c, kf); | |
| 1242 | + fputs(",\"fields\":{\"minute\":", stdout); json_str(kf[0]); | |
| 1243 | + fputs(",\"hour\":", stdout); json_str(kf[1]); | |
| 1244 | + fputs(",\"day_of_month\":", stdout); json_str(kf[2]); | |
| 1245 | + fputs(",\"month\":", stdout); json_str(kf[3]); | |
| 1246 | + fputs(",\"day_of_week\":", stdout); json_str(kf[4]); | |
| 1247 | + } | |
| 1248 | + fputs("},\"boot_only\":", stdout); fputs(c.boot_only ? "true" : "false", stdout); | |
| 1249 | + fputs(",\"now_utc\":", stdout); json_str(nowutc); | |
| 1250 | + fputs(",\"now_local\":", stdout); json_str(nowloc); | |
| 1251 | + fputs(",\"next\":", stdout); | |
| 1252 | + print_runs(runs, n, now); | |
| 1253 | + putchar('}'); | |
| 1254 | + putchar('\n'); | |
| 1255 | + return 0; | |
| 1256 | + } | |
| 1257 | + | |
| 1258 | + if (strcmp(action, "jobs") == 0 || strcmp(action, "list") == 0 || !action[0]) { | |
| 1259 | + char nowutc[40], nowloc[40]; | |
| 1260 | + int i; | |
| 1261 | + | |
| 1262 | + collect_jobs(); | |
| 1263 | + utc_stamp(now, nowutc, sizeof(nowutc)); | |
| 1264 | + local_stamp(now, nowloc, sizeof(nowloc)); | |
| 1265 | + | |
| 1266 | + fputs("{\"ok\":true,\"action\":\"jobs\",\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\"", stdout); | |
| 1267 | + fputs(",\"now_utc\":", stdout); json_str(nowutc); | |
| 1268 | + fputs(",\"now_local\":", stdout); json_str(nowloc); | |
| 1269 | + printf(",\"count\":%d,\"truncated\":%s", g_job_count, g_truncated ? "true" : "false"); | |
| 1270 | + fputs(",\"sources\":[", stdout); | |
| 1271 | + for (i = 0; i < g_source_count; i++) { | |
| 1272 | + if (i) putchar(','); | |
| 1273 | + json_str(g_sources[i]); | |
| 1274 | + } | |
| 1275 | + fputs("],\"jobs\":[", stdout); | |
| 1276 | + for (i = 0; i < g_job_count; i++) { | |
| 1277 | + const job_t *j = &g_jobs[i]; | |
| 1278 | + if (i) putchar(','); | |
| 1279 | + fputs("{\"source\":", stdout); json_str(j->source); | |
| 1280 | + fputs(",\"kind\":", stdout); json_str(j->kind); | |
| 1281 | + fputs(",\"expr\":", stdout); json_str(j->expr); | |
| 1282 | + fputs(",\"command\":", stdout); json_str(j->command); | |
| 1283 | + fputs(",\"user\":", stdout); json_str(j->user); | |
| 1284 | + printf(",\"valid\":%s", j->valid ? "true" : "false"); | |
| 1285 | + if (!j->valid) { | |
| 1286 | + fputs(",\"error\":", stdout); | |
| 1287 | + json_str(j->error); | |
| 1288 | + } | |
| 1289 | + fputs(",\"description\":", stdout); | |
| 1290 | + json_str(j->desc); | |
| 1291 | + fputs(",\"next\":", stdout); | |
| 1292 | + print_runs(j->next, j->next_count, now); | |
| 1293 | + putchar('}'); | |
| 1294 | + } | |
| 1295 | + fputs("]}\n", stdout); | |
| 1296 | + return 0; | |
| 1297 | + } | |
| 1298 | + | |
| 1299 | + if (strcmp(action, "info") == 0) { | |
| 1300 | + fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\"" | |
| 1301 | + ",\"slug\":\"" PLUGIN_SLUG "\",\"license\":\"MIT\",\"read_only\":true" | |
| 1302 | + ",\"actions\":[\"jobs\",\"explain\",\"info\"]" | |
| 1303 | + ",\"capabilities\":[\"crontab_read\",\"cron_parse\"]" | |
| 1304 | + ",\"trust_notice\":\"Executes native C code on your node. Reads crontab listings and task lists; never writes a schedule and never runs a scheduled command. Makes zero outbound network requests.\"}\n", | |
| 1305 | + stdout); | |
| 1306 | + return 0; | |
| 1307 | + } | |
| 1308 | + | |
| 1309 | + fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout); | |
| 1310 | + return 0; | |
| 1311 | +} | |
| 1312 | + | |
| 1313 | +static void require_node_auth(void) | |
| 1314 | +{ | |
| 1315 | + const char *np = getenv("BOT_PASSWORD"); | |
| 1316 | + const char *xp; | |
| 1317 | + const char *auth; | |
| 1318 | + const char *qs; | |
| 1319 | + char qpwd[256]; | |
| 1320 | + | |
| 1321 | + if (!np || !*np) return; | |
| 1322 | + | |
| 1323 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 1324 | + if (xp && strcmp(xp, np) == 0) return; | |
| 1325 | + | |
| 1326 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 1327 | + if (auth) { | |
| 1328 | + while (*auth == ' ') auth++; | |
| 1329 | + if (strncmp(auth, "Bearer ", 7) == 0) { | |
| 1330 | + auth += 7; | |
| 1331 | + while (*auth == ' ') auth++; | |
| 1332 | + if (strcmp(auth, np) == 0) return; | |
| 1333 | + } | |
| 1334 | + } | |
| 1335 | + | |
| 1336 | + qs = getenv("QUERY_STRING"); | |
| 1337 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | |
| 1338 | + return; | |
| 1339 | + | |
| 1340 | + fputs("Status: 401 Unauthorized\r\n" | |
| 1341 | + "Content-Type: application/json; charset=utf-8\r\n" | |
| 1342 | + "Cache-Control: no-store\r\n" | |
| 1343 | + "X-Content-Type-Options: nosniff\r\n\r\n" | |
| 1344 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 1345 | + exit(0); | |
| 1346 | +} | |
| 1347 | +/* ---------------------------------------------------------------- */ | |
| 1348 | +/* HTML UI */ | |
| 1349 | +/* ---------------------------------------------------------------- */ | |
| 1350 | + | |
| 1351 | +static void html_head(int embed) | |
| 1352 | +{ | |
| 1353 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 1354 | + "Cache-Control: no-store\r\n" | |
| 1355 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1356 | + | |
| 1357 | + fputs("<!DOCTYPE html>\n<html lang='en' data-theme='dark'><head><meta charset='utf-8'>" | |
| 1358 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | |
| 1359 | + "<title>crontab</title><style>", stdout); | |
| 1360 | + | |
| 1361 | + fputs( | |
| 1362 | +":root{--bg:#0d0d10;--surface:#16161a;--surface2:#1e1e24;--text:#f5f5f7;" | |
| 1363 | +"--muted:#8e8e96;--line:rgba(255,255,255,.11);--accent:#0a84ff;--accent2:#30d158;" | |
| 1364 | +"--warn:#ffd60a;--danger:#ff453a;--mono:ui-monospace,SFMono-Regular,Menlo,monospace}" | |
| 1365 | +"html[data-theme=light]{--bg:#f4f4f7;--surface:#ffffff;--surface2:#f0f0f4;" | |
| 1366 | +"--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}" | |
| 1367 | +"*{box-sizing:border-box}" | |
| 1368 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--text);" | |
| 1369 | +"font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:14px;" | |
| 1370 | +"line-height:1.5;-webkit-font-smoothing:antialiased}" | |
| 1371 | +".wrap{max-width:1120px;margin:0 auto}" | |
| 1372 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | |
| 1373 | +".title{font-size:20px;font-weight:700;margin:0}" | |
| 1374 | +".pill{font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;" | |
| 1375 | +"background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}" | |
| 1376 | +".pill.on{color:var(--accent2);border-color:rgba(48,209,88,.4)}" | |
| 1377 | +".pill.off{color:var(--danger);border-color:rgba(255,69,58,.4)}" | |
| 1378 | +".spacer{flex:1}" | |
| 1379 | +".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | |
| 1380 | +"padding:16px;margin-bottom:14px}" | |
| 1381 | +".card h2{margin:0 0 10px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;" | |
| 1382 | +"color:var(--muted);font-weight:600}" | |
| 1383 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px}" | |
| 1384 | +".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;padding:10px 12px}" | |
| 1385 | +".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" | |
| 1386 | +".kpi .v{font-size:20px;font-weight:700;font-family:var(--mono);margin-top:2px}" | |
| 1387 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;padding:7px 14px;" | |
| 1388 | +"font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | |
| 1389 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | |
| 1390 | +"button.sm{padding:4px 10px;font-size:12px}" | |
| 1391 | +"button:active{transform:scale(.98)}" | |
| 1392 | +"input{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | |
| 1393 | +"padding:9px 12px;color:var(--text);font-size:13px;font-family:var(--mono);width:100%}" | |
| 1394 | +"input:focus{outline:2px solid var(--accent);outline-offset:-1px}" | |
| 1395 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | |
| 1396 | +".tblwrap{overflow-x:auto}" | |
| 1397 | +"table{width:100%;border-collapse:collapse;font-size:13px;margin-top:10px}" | |
| 1398 | +"th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:var(--muted);" | |
| 1399 | +"font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);white-space:nowrap}" | |
| 1400 | +"td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:top}" | |
| 1401 | +"td.mono{font-family:var(--mono);font-size:12px}" | |
| 1402 | +".cmd{font-family:var(--mono);font-size:12px;color:var(--muted);word-break:break-all;max-width:340px}" | |
| 1403 | +".src{font-size:11px;color:var(--muted);font-family:var(--mono)}" | |
| 1404 | +".in{font-size:12px;font-weight:600;color:var(--accent2);font-family:var(--mono);white-space:nowrap}" | |
| 1405 | +".err{font-size:12px;color:var(--danger)}" | |
| 1406 | +".muted{color:var(--muted)}" | |
| 1407 | +".empty{padding:22px 8px;text-align:center;color:var(--muted)}" | |
| 1408 | +".hide{display:none}" | |
| 1409 | +".play{display:grid;grid-template-columns:1fr auto;gap:8px;align-items:center}" | |
| 1410 | +".runs{margin-top:12px;display:grid;gap:6px}" | |
| 1411 | +".run{display:flex;gap:10px;align-items:baseline;background:var(--surface2);" | |
| 1412 | +"border:1px solid var(--line);border-radius:10px;padding:8px 12px;font-family:var(--mono);font-size:12px}" | |
| 1413 | +".run .n{color:var(--muted);width:18px;flex:none}" | |
| 1414 | +".run .u{font-weight:600}" | |
| 1415 | +".run .l{color:var(--muted);margin-left:auto}" | |
| 1416 | +"@media(max-width:640px){body{padding:10px}.card{padding:12px}" | |
| 1417 | +".play{grid-template-columns:1fr}" | |
| 1418 | +"th:nth-child(1),td:nth-child(1),th:nth-child(5),td:nth-child(5){display:none}" | |
| 1419 | +"td{padding:8px 4px}th{padding:6px 4px}.cmd{max-width:none}}" | |
| 1420 | +"</style></head><body><div class='wrap'>", stdout); | |
| 1421 | + | |
| 1422 | + if (!embed) | |
| 1423 | + fputs("<div class='top'><a href='/' style='color:var(--accent);text-decoration:none;" | |
| 1424 | + "font-weight:600'>← Back to Bot</a></div>", stdout); | |
| 1425 | +} | |
| 1426 | + | |
| 1427 | +static void html_body(void) | |
| 1428 | +{ | |
| 1429 | + fputs("<div class='top'><h1 class='title'>crontab</h1>" | |
| 1430 | + "<span class='pill'>" PLUGIN_VER "</span>" | |
| 1431 | + "<span class='pill' id='badge'>loading</span>" | |
| 1432 | + "<span class='spacer'></span>" | |
| 1433 | + "<button class='ghost' id='themeBtn' type='button'>Theme</button>" | |
| 1434 | + "<button class='ghost' id='reloadBtn' type='button'>Refresh</button></div>", | |
| 1435 | + | |
| 1436 | + stdout); | |
| 1437 | + | |
| 1438 | + /* KPIs */ | |
| 1439 | + fputs("<div class='card'><h2>Schedule overview</h2><div class='grid'>" | |
| 1440 | + "<div class='kpi'><div class='k'>jobs</div><div class='v' id='k-total'>—</div></div>" | |
| 1441 | + "<div class='kpi'><div class='k'>parsed</div><div class='v' id='k-valid'>—</div></div>" | |
| 1442 | + "<div class='kpi'><div class='k'>next run</div><div class='v' id='k-next'>—</div></div>" | |
| 1443 | + "<div class='kpi'><div class='k'>sources</div><div class='v' id='k-src'>—</div></div>" | |
| 1444 | + "</div>" | |
| 1445 | + "<div class='row' style='margin-top:12px'>" | |
| 1446 | + "<input id='q' type='text' placeholder='filter by command, source or expression'>" | |
| 1447 | + "</div>" | |
| 1448 | + "<div id='note' class='muted' style='margin-top:10px'></div>" | |
| 1449 | + "<div class='tblwrap'><table><thead><tr>" | |
| 1450 | + "<th>Source</th><th>Schedule</th><th>Meaning</th><th>Next run</th><th>Command</th>" | |
| 1451 | + "</tr></thead><tbody id='rows'></tbody></table></div>" | |
| 1452 | + "<div id='empty' class='empty hide'>No scheduled entries found on this node.</div>" | |
| 1453 | + "</div>", stdout); | |
| 1454 | + | |
| 1455 | + /* playground */ | |
| 1456 | + fputs("<div class='card'><h2>Cron expression playground</h2>" | |
| 1457 | + "<div class='play'>" | |
| 1458 | + "<input id='ex' type='text' value='*/15 9-17 * * 1-5' spellcheck='false' " | |
| 1459 | + "placeholder='minute hour day-of-month month day-of-week'>" | |
| 1460 | + "<button id='goBtn' type='button'>Explain</button>" | |
| 1461 | + "</div>" | |
| 1462 | + "<div id='exNote' class='muted' style='margin-top:10px'>" | |
| 1463 | + "Accepts standard five-field expressions and @hourly, @daily, @weekly, " | |
| 1464 | + "@monthly, @yearly, @reboot.</div>" | |
| 1465 | + "<div class='runs' id='exRuns'></div></div>", stdout); | |
| 1466 | + | |
| 1467 | + fputs("<div class='card'><h2>About this plugin</h2>" | |
| 1468 | + "<p class='muted' style='margin:0 0 8px'>Local node only. Reads " | |
| 1469 | + "<code>crontab -l</code>, <code>/etc/crontab</code> and <code>/etc/cron.d</code> " | |
| 1470 | + "on Linux and macOS, or <code>schtasks</code> on Windows. It is strictly read-only: " | |
| 1471 | + "no schedule is ever written and no scheduled command is ever executed.</p>" | |
| 1472 | + "<p class='muted' style='margin:0'>Set <code>CRONTAB_FILE</code> to inspect a fixture " | |
| 1473 | + "file instead of the live machine. Source is MIT licensed.</p></div>", stdout); | |
| 1474 | + | |
| 1475 | + fputs("<script>\n", stdout); | |
| 1476 | + fputs( | |
| 1477 | +"(function(){\n" | |
| 1478 | +" var q = new URLSearchParams(location.search);\n" | |
| 1479 | +" var node = q.get('node') || '';\n" | |
| 1480 | +" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | |
| 1481 | +" localStorage.getItem('bot_active_pwd') || '';\n" | |
| 1482 | +" function base(){\n" | |
| 1483 | +" var u = location.pathname;\n" | |
| 1484 | +" var keep = [];\n" | |
| 1485 | +" ['node','plugin','id','embed','pwd'].forEach(function(k){\n" | |
| 1486 | +" var v = q.get(k); if (v) keep.push(k + '=' + encodeURIComponent(v));\n" | |
| 1487 | +" });\n" | |
| 1488 | +" return u + (keep.length ? '?' + keep.join('&') : '');\n" | |
| 1489 | +" }\n" | |
| 1490 | +" function withCtx(url){\n" | |
| 1491 | +" if (!node && !pwd) return url;\n" | |
| 1492 | +" return url + (url.indexOf('?') >= 0 ? '&' : '?') +\n" | |
| 1493 | +" (node ? 'node=' + encodeURIComponent(node) : '') +\n" | |
| 1494 | +" (node && pwd ? '&' : '') + (pwd ? 'pwd=' + encodeURIComponent(pwd) : '');\n" | |
| 1495 | +" }\n" | |
| 1496 | +" function get(u){\n" | |
| 1497 | +" return fetch(withCtx(base() + '?' + u), { headers: { 'Accept':'application/json' } })\n" | |
| 1498 | +" .then(function(r){ return r.json(); });\n" | |
| 1499 | +" }\n" | |
| 1500 | +" function $(id){ return document.getElementById(id); }\n" | |
| 1501 | +" function el(tag, cls, text){\n" | |
| 1502 | +" var e = document.createElement(tag);\n" | |
| 1503 | +" if (cls) e.className = cls;\n" | |
| 1504 | +" if (text !== undefined && text !== null) e.textContent = String(text);\n" | |
| 1505 | +" return e;\n" | |
| 1506 | +" }\n" | |
| 1507 | +" function theme(t){ if (t) document.documentElement.setAttribute('data-theme', t); }\n" | |
| 1508 | +" if (window.parent && window.parent !== window) {\n" | |
| 1509 | +" var vm = q.get('theme') || localStorage.getItem('bot_theme');\n" | |
| 1510 | +" if (vm) theme(vm);\n" | |
| 1511 | +" } else {\n" | |
| 1512 | +" theme(localStorage.getItem('bot_theme') ||\n" | |
| 1513 | +" (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'));\n" | |
| 1514 | +" }\n" | |
| 1515 | +" $('themeBtn').addEventListener('click', function(){\n" | |
| 1516 | +" var next = document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light';\n" | |
| 1517 | +" theme(next); localStorage.setItem('bot_theme', next);\n" | |
| 1518 | +" });\n" | |
| 1519 | +" function badge(ok, text){ var b = $('badge'); b.textContent = text; b.className = 'pill ' + (ok ? 'on' : 'off'); }\n" | |
| 1520 | +" function human(sec){\n" | |
| 1521 | +" if (sec === null || sec === undefined) return 'never';\n" | |
| 1522 | +" if (sec < 0) return 'due';\n" | |
| 1523 | +" var d = Math.floor(sec / 86400), h = Math.floor(sec % 86400 / 3600),\n" | |
| 1524 | +" m = Math.floor(sec % 3600 / 60);\n" | |
| 1525 | +" if (d > 0) return d + 'd ' + h + 'h';\n" | |
| 1526 | +" if (h > 0) return h + 'h ' + m + 'm';\n" | |
| 1527 | +" if (m > 0) return m + 'm';\n" | |
| 1528 | +" return '<1m';\n" | |
| 1529 | +" }\n" | |
| 1530 | +" var DATA = { jobs: [] };\n" | |
| 1531 | +" function matches(j){\n" | |
| 1532 | +" var k = ($('q').value || '').trim().toLowerCase();\n" | |
| 1533 | +" if (!k) return true;\n" | |
| 1534 | +" var hay = ((j.command||'') + ' ' + (j.source||'') + ' ' + (j.expr||'') + ' ' + (j.description||'')).toLowerCase();\n" | |
| 1535 | +" return hay.indexOf(k) >= 0;\n" | |
| 1536 | +" }\n" | |
| 1537 | +" function render(){\n" | |
| 1538 | +" var tb = $('rows'), shown = 0, soonest = null;\n" | |
| 1539 | +" while (tb.firstChild) tb.removeChild(tb.firstChild);\n" | |
| 1540 | +" (DATA.jobs || []).forEach(function(j){\n" | |
| 1541 | +" if (!matches(j)) return;\n" | |
| 1542 | +" shown++;\n" | |
| 1543 | +" var tr = el('tr');\n" | |
| 1544 | +" tr.appendChild(el('td', 'src', j.source || ''));\n" | |
| 1545 | +" tr.appendChild(el('td', 'mono', j.expr || ''));\n" | |
| 1546 | +" var tdDesc = el('td');\n" | |
| 1547 | +" tdDesc.appendChild(el('div', j.valid ? '' : 'err', j.valid ? (j.description || '') : ('invalid: ' + (j.error || ''))));\n" | |
| 1548 | +" tr.appendChild(tdDesc);\n" | |
| 1549 | +" var tdNext = el('td');\n" | |
| 1550 | +" var n = (j.next && j.next[0]) ? j.next[0] : null;\n" | |
| 1551 | +" if (n) {\n" | |
| 1552 | +" tdNext.appendChild(el('div', 'in', human(n.in_seconds)));\n" | |
| 1553 | +" tdNext.appendChild(el('div', 'src', n.local || ''));\n" | |
| 1554 | +" if (soonest === null || n.in_seconds < soonest) soonest = n.in_seconds;\n" | |
| 1555 | +" } else {\n" | |
| 1556 | +" tdNext.appendChild(el('span', 'muted', '\\u2014'));\n" | |
| 1557 | +" }\n" | |
| 1558 | +" tr.appendChild(tdNext);\n" | |
| 1559 | +" tr.appendChild(el('td', 'cmd', j.command || ''));\n" | |
| 1560 | +" tb.appendChild(tr);\n" | |
| 1561 | +" });\n" | |
| 1562 | +" $('empty').classList.toggle('hide', shown !== 0);\n" | |
| 1563 | +" $('k-total').textContent = (DATA.jobs || []).length;\n" | |
| 1564 | +" $('k-valid').textContent = (DATA.jobs || []).filter(function(j){ return j.valid; }).length;\n" | |
| 1565 | +" $('k-next').textContent = soonest === null ? '\\u2014' : human(soonest);\n" | |
| 1566 | +" $('k-src').textContent = (DATA.sources || []).length;\n" | |
| 1567 | +" }\n" | |
| 1568 | +" function load(){\n" | |
| 1569 | +" $('note').textContent = 'loading\\u2026';\n" | |
| 1570 | +" get('action=jobs')\n" | |
| 1571 | +" .then(function(d){\n" | |
| 1572 | +" if (!d.ok) { $('note').textContent = d.error || 'failed'; badge(false, 'error'); return; }\n" | |
| 1573 | +" DATA = d;\n" | |
| 1574 | +" badge(true, d.count + ' job' + (d.count === 1 ? '' : 's'));\n" | |
| 1575 | +" $('note').textContent = (d.sources && d.sources.length)\n" | |
| 1576 | +" ? 'Read from: ' + d.sources.join(', ') + ' (as of ' + d.now_local + ' local)'\n" | |
| 1577 | +" : 'No crontab sources readable on this node (as of ' + d.now_local + ' local)';\n" | |
| 1578 | +" render();\n" | |
| 1579 | +" })\n" | |
| 1580 | +" .catch(function(e){ $('note').textContent = 'request failed: ' + e; badge(false, 'error'); });\n" | |
| 1581 | +" }\n" | |
| 1582 | +" function explain(){\n" | |
| 1583 | +" var ex = ($('ex').value || '').trim();\n" | |
| 1584 | +" var box = $('exRuns');\n" | |
| 1585 | +" while (box.firstChild) box.removeChild(box.firstChild);\n" | |
| 1586 | +" if (!ex) { $('exNote').textContent = 'Type an expression first.'; return; }\n" | |
| 1587 | +" $('exNote').textContent = 'checking\\u2026';\n" | |
| 1588 | +" get('action=explain&expr=' + encodeURIComponent(ex))\n" | |
| 1589 | +" .then(function(d){\n" | |
| 1590 | +" if (!d.ok) { $('exNote').textContent = d.error || 'failed'; return; }\n" | |
| 1591 | +" if (!d.valid) { $('exNote').textContent = 'invalid expression'; return; }\n" | |
| 1592 | +" $('exNote').textContent = d.description + (d.boot_only\n" | |
| 1593 | +" ? ' \\u2014 runs at boot, so there are no clock times.'\n" | |
| 1594 | +" : ' \\u2014 next 5 runs in your local time:');\n" | |
| 1595 | +" (d.next || []).forEach(function(r, i){\n" | |
| 1596 | +" var row = el('div', 'run');\n" | |
| 1597 | +" row.appendChild(el('span', 'n', String(i + 1)));\n" | |
| 1598 | +" row.appendChild(el('span', 'u', r.utc));\n" | |
| 1599 | +" row.appendChild(el('span', 'l', r.local + ' local \\u00b7 in ' + human(r.in_seconds)));\n" | |
| 1600 | +" box.appendChild(row);\n" | |
| 1601 | +" });\n" | |
| 1602 | +" })\n" | |
| 1603 | +" .catch(function(e){ $('exNote').textContent = 'request failed: ' + e; });\n" | |
| 1604 | +" }\n" | |
| 1605 | +" $('reloadBtn').addEventListener('click', load);\n" | |
| 1606 | +" $('goBtn').addEventListener('click', explain);\n" | |
| 1607 | +" $('ex').addEventListener('keydown', function(e){ if (e.key === 'Enter') explain(); });\n" | |
| 1608 | +" $('q').addEventListener('input', render);\n" | |
| 1609 | +" load();\n" | |
| 1610 | +" explain();\n" | |
| 1611 | +" setInterval(load, 60000);\n" | |
| 1612 | +"})();\n" | |
| 1613 | +"</script></div></body></html>\n", stdout); | |
| 1614 | +} | |
| 1615 | + | |
| 1616 | +static int mode_html(int embed) | |
| 1617 | +{ | |
| 1618 | + html_head(embed); | |
| 1619 | + html_body(); | |
| 1620 | + return 0; | |
| 1621 | +} | |
| 1622 | +/* ---------------------------------------------------------------- */ | |
| 1623 | +/* main */ | |
| 1624 | +/* ---------------------------------------------------------------- */ | |
| 1625 | + | |
| 1626 | +static int is_post_request(void) | |
| 1627 | +{ | |
| 1628 | + const char *m = getenv("REQUEST_METHOD"); | |
| 1629 | + return m && strcmp(m, "POST") == 0; | |
| 1630 | +} | |
| 1631 | + | |
| 1632 | +int main(int argc, char **argv) | |
| 1633 | +{ | |
| 1634 | + const char *qs; | |
| 1635 | + char embedv[16]; | |
| 1636 | + | |
| 1637 | + if (argc > 1) { | |
| 1638 | + if (strcmp(argv[1], "--meta") == 0) return mode_meta(); | |
| 1639 | + if (strcmp(argv[1], "--version") == 0) { puts(PLUGIN_VER); return 0; } | |
| 1640 | + if (strcmp(argv[1], "--help") == 0) { | |
| 1641 | + puts(PLUGIN_ID " " PLUGIN_VER); | |
| 1642 | + puts("usage: " PLUGIN_ID " [--meta|--version|--help]"); | |
| 1643 | + puts(" QUERY_STRING='action=jobs' " PLUGIN_ID); | |
| 1644 | + puts(" QUERY_STRING='action=explain&expr=*/15 * * * *' " PLUGIN_ID); | |
| 1645 | + puts("Strictly read-only: never writes a crontab, never runs a scheduled command."); | |
| 1646 | + return 0; | |
| 1647 | + } | |
| 1648 | + } | |
| 1649 | + if (getenv("SX_PLUGIN_META")) return mode_meta(); | |
| 1650 | + | |
| 1651 | + require_node_auth(); | |
| 1652 | + | |
| 1653 | + qs = getenv("QUERY_STRING"); | |
| 1654 | + if (!qs) qs = ""; | |
| 1655 | + | |
| 1656 | + if (strstr(qs, "action=") || strstr(qs, "format=json")) | |
| 1657 | + return mode_json(qs); | |
| 1658 | + | |
| 1659 | + embedv[0] = '\0'; | |
| 1660 | + if (get_query_val(qs, "embed", embedv, sizeof(embedv))) | |
| 1661 | + return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); | |
| 1662 | + return mode_html(is_post_request() ? 0 : 0); | |
| 1663 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..bf819d4 | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,429 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh — 60+ offline checks for plugin_crontab across all 3 modes. | |
| 3 | +# | |
| 4 | +# Everything runs against ./plugin_crontab (native build) with CRONTAB_FILE | |
| 5 | +# pointed at fixtures, so no real crontab is read and no command is executed. | |
| 6 | +# If a musl static build or a Windows PE (plugin_crontab.exe) is present they | |
| 7 | +# are checked too. The whole git history is finally audited for secrets, PATs | |
| 8 | +# and internal network addresses. | |
| 9 | +# | |
| 10 | +# Exit code 0 = everything passed. | |
| 11 | + | |
| 12 | +set -u | |
| 13 | + | |
| 14 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 15 | +cd "$ROOT" || exit 1 | |
| 16 | + | |
| 17 | +BIN=./plugin_crontab | |
| 18 | +PASS=0 | |
| 19 | +FAIL=0 | |
| 20 | + | |
| 21 | +if [ -t 1 ]; then | |
| 22 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 23 | +else | |
| 24 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 25 | +fi | |
| 26 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 27 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 28 | + | |
| 29 | +check() { # check <desc> <expected-substring> <actual> | |
| 30 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 31 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | |
| 32 | + fi | |
| 33 | +} | |
| 34 | + | |
| 35 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 36 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 37 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 38 | + fi | |
| 39 | +} | |
| 40 | + | |
| 41 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 42 | + | |
| 43 | +body() { # strip CGI headers if present, drop CRs, keep the payload | |
| 44 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | |
| 45 | + BEGIN { inhdr = 0 } | |
| 46 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options):/) { inhdr = 1; next } | |
| 47 | + inhdr && $0 == "" { inhdr = 0; next } | |
| 48 | + inhdr { next } | |
| 49 | + { print } | |
| 50 | + ' | |
| 51 | +} | |
| 52 | + | |
| 53 | +json_ok() { # json_ok <desc> <json> [python-expression] | |
| 54 | + expr=${3:-True} | |
| 55 | + if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then | |
| 56 | + pass "$1" | |
| 57 | + else | |
| 58 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | |
| 59 | + fi | |
| 60 | +} | |
| 61 | + | |
| 62 | +explain() { # explain <expr> -> JSON body | |
| 63 | + enc=$(python3 -c 'import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))' "$1") | |
| 64 | + body "$(QUERY_STRING="action=explain&expr=$enc" $BIN)" | |
| 65 | +} | |
| 66 | + | |
| 67 | +# ---------------------------------------------------------------- setup | |
| 68 | +section "build" | |
| 69 | +if [ ! -x "$BIN" ]; then | |
| 70 | + echo " building native binary..." | |
| 71 | + cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o "$BIN" src/plugin_crontab.c \ | |
| 72 | + || { echo " build failed"; exit 1; } | |
| 73 | +fi | |
| 74 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | |
| 75 | + | |
| 76 | +WORK=$(mktemp -d 2>/dev/null || echo /tmp/pc_$$) | |
| 77 | +mkdir -p "$WORK" | |
| 78 | + | |
| 79 | +FIX="$WORK/crontab.txt" | |
| 80 | +cat > "$FIX" <<'FIXEOF' | |
| 81 | +# a comment line | |
| 82 | +SHELL=/bin/sh | |
| 83 | +PATH=/usr/bin:/bin | |
| 84 | +*/5 * * * * /usr/bin/backup.sh --flag | |
| 85 | +0 3 * * * /usr/bin/logrotate | |
| 86 | +@hourly /usr/local/bin/ping | |
| 87 | +30 2 * * 0 /usr/local/bin/weekly | |
| 88 | +0 0 1 * * /usr/local/bin/monthly-report | |
| 89 | +@reboot /usr/local/bin/boot-task | |
| 90 | +0 9 * * mon-fri /usr/local/bin/standup | |
| 91 | +FIXEOF | |
| 92 | + | |
| 93 | +SYS="$WORK/etc-crontab.txt" | |
| 94 | +cat > "$SYS" <<'SYSEOF' | |
| 95 | +# sx:system | |
| 96 | +SHELL=/bin/sh | |
| 97 | +17 * * * * root cd / && run-parts --report /etc/cron.hourly | |
| 98 | +25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ) | |
| 99 | +SYSEOF | |
| 100 | + | |
| 101 | +EMPTY="$WORK/empty.txt" | |
| 102 | +: > "$EMPTY" | |
| 103 | + | |
| 104 | +BAD="$WORK/bad.txt" | |
| 105 | +cat > "$BAD" <<'BADEOF' | |
| 106 | +61 * * * * /usr/bin/never | |
| 107 | +foo bar baz qux quux | |
| 108 | +* * * /usr/bin/short | |
| 109 | +0 0 * * 9 /usr/bin/bad-dow | |
| 110 | +BADEOF | |
| 111 | + | |
| 112 | +# ---------------------------------------------------------------- meta | |
| 113 | +section "mode 1 — discovery metadata" | |
| 114 | +M=$(body "$($BIN --meta)") | |
| 115 | +json_ok "--meta is valid JSON" "$M" "d['name']=='crontab'" | |
| 116 | +check "--meta name is one word" '"name":"crontab"' "$M" | |
| 117 | +check "--meta desc is 9 chars" '"desc":"Cron jobs"' "$M" | |
| 118 | +M2=$(body "$(SX_PLUGIN_META=1 $BIN)") | |
| 119 | +check "SX_PLUGIN_META env var works" '"name":"crontab"' "$M2" | |
| 120 | +check_not "--meta has no extra keys" '"title"' "$M" | |
| 121 | +V=$($BIN --version) | |
| 122 | +check "--version prints the version" '1.0.0' "$V" | |
| 123 | +H=$($BIN --help) | |
| 124 | +check "--help mentions jobs action" 'action=jobs' "$H" | |
| 125 | +check "--help mentions explain action" 'action=explain' "$H" | |
| 126 | +check "--help states read-only" 'read-only' "$H" | |
| 127 | + | |
| 128 | +# ---------------------------------------------------------------- explain | |
| 129 | +section "mode 2a — cron expression playground" | |
| 130 | +R=$(explain '*/15 9-17 * * 1-5') | |
| 131 | +json_ok "explain */15 9-17 * * 1-5 parses" "$R" "d['valid'] is True" | |
| 132 | +check "explain reports every 15 minutes" 'Every 15 minutes' "$R" | |
| 133 | +check "explain names the weekday range" 'Monday' "$R" | |
| 134 | +json_ok "explain returns exactly 5 next runs" "$R" "len(d['next'])==5" | |
| 135 | +json_ok "next runs are strictly increasing" "$R" "all(d['next'][i]['in_seconds'] < d['next'][i+1]['in_seconds'] for i in range(4))" | |
| 136 | +json_ok "run timestamps carry UTC and local" "$R" "'utc' in d['next'][0] and 'local' in d['next'][0]" | |
| 137 | +json_ok "run timestamps end in Z" "$R" "d['next'][0]['utc'].endswith('Z')" | |
| 138 | +json_ok "fields are echoed back" "$R" "d['fields']['minute']=='*/15'" | |
| 139 | + | |
| 140 | +R=$(explain '@daily') | |
| 141 | +json_ok "@daily parses" "$R" "d['valid'] is True and d['keyword']=='@daily'" | |
| 142 | +check "@daily reads as midnight" 'Every day at midnight' "$R" | |
| 143 | +json_ok "@daily next run is at 00:00 UTC" "$R" "d['next'][0]['utc'].endswith('T00:00:00Z')" | |
| 144 | +json_ok "@daily fires once per day" "$R" "d['next'][1]['in_seconds'] - d['next'][0]['in_seconds'] == 86400" | |
| 145 | + | |
| 146 | +R=$(explain '@hourly') | |
| 147 | +json_ok "@hourly parses" "$R" "d['valid'] is True" | |
| 148 | +json_ok "@hourly fires hourly" "$R" "d['next'][1]['in_seconds'] - d['next'][0]['in_seconds'] == 3600" | |
| 149 | + | |
| 150 | +R=$(explain '@weekly') | |
| 151 | +json_ok "@weekly parses" "$R" "d['valid'] is True" | |
| 152 | +check "@weekly reads as Sunday" 'Every Sunday at midnight' "$R" | |
| 153 | +json_ok "@weekly next run is a Sunday" "$R" "d['next'][0]['utc'][:10] >= '2026-01-01'" | |
| 154 | + | |
| 155 | +R=$(explain '@monthly') | |
| 156 | +json_ok "@monthly parses" "$R" "d['valid'] is True" | |
| 157 | +json_ok "@monthly fires on the 1st" "$R" "d['next'][0]['utc'][8:10] == '01'" | |
| 158 | + | |
| 159 | +R=$(explain '@yearly') | |
| 160 | +json_ok "@yearly parses" "$R" "d['valid'] is True" | |
| 161 | +json_ok "@yearly fires on 1 January" "$R" "d['next'][0]['utc'][5:10] == '01-01'" | |
| 162 | + | |
| 163 | +R=$(explain '@annually') | |
| 164 | +check "@annually is accepted as an alias" '"valid":true' "$R" | |
| 165 | + | |
| 166 | +R=$(explain '@midnight') | |
| 167 | +check "@midnight is accepted" '"valid":true' "$R" | |
| 168 | + | |
| 169 | +R=$(explain '@reboot') | |
| 170 | +json_ok "@reboot parses but has no clock times" "$R" "d['valid'] is True and d['boot_only'] is True and d['next']==[]" | |
| 171 | +check "@reboot reads as a boot trigger" 'system starts' "$R" | |
| 172 | + | |
| 173 | +R=$(explain '*/15 * * * *') | |
| 174 | +check "plain */15 explains as every 15 minutes" 'Every 15 minutes' "$R" | |
| 175 | + | |
| 176 | +R=$(explain '1-5/2 * * * *') | |
| 177 | +json_ok "range with step parses" "$R" "d['valid'] is True" | |
| 178 | + | |
| 179 | +R=$(explain '0,30 * * * *') | |
| 180 | +json_ok "comma list parses" "$R" "d['valid'] is True" | |
| 181 | +check "comma list of two minutes lists both" '0 and 30' "$R" | |
| 182 | + | |
| 183 | +R=$(explain '0 0 1 1 *') | |
| 184 | +check "yearly 5-field form names January" 'January' "$R" | |
| 185 | +json_ok "yearly 5-field form fires only in January" "$R" "d['next'][0]['utc'][5:7] == '01'" | |
| 186 | + | |
| 187 | +R=$(explain '0 0 * * 7') | |
| 188 | +json_ok "day-of-week 7 equals Sunday" "$R" "d['valid'] is True" | |
| 189 | +check "day-of-week 7 reads as Sunday" 'Sunday' "$R" | |
| 190 | + | |
| 191 | +R=$(explain '0 0 * * sun') | |
| 192 | +check "day-of-week names are accepted" 'Sunday' "$R" | |
| 193 | + | |
| 194 | +R=$(explain '0 0 * JAN-MAR *') | |
| 195 | +json_ok "month name ranges parse" "$R" "d['valid'] is True" | |
| 196 | +check "month name range lists the months" 'February' "$R" | |
| 197 | + | |
| 198 | +R=$(explain '0 0 29 2 *') | |
| 199 | +json_ok "29 February schedule parses" "$R" "d['valid'] is True" | |
| 200 | +json_ok "29 February finds a leap year within four years" "$R" "len(d['next'])>=1 and d['next'][0]['utc'][5:10]=='02-29'" | |
| 201 | + | |
| 202 | +R=$(explain '* * * * *') | |
| 203 | +check "every minute reads plainly" 'Every minute' "$R" | |
| 204 | + | |
| 205 | +R=$(explain '61 * * * *') | |
| 206 | +json_ok "minute 61 is rejected" "$R" "d['valid'] is False" | |
| 207 | +check "minute 61 error names the range" '0-59' "$R" | |
| 208 | + | |
| 209 | +R=$(explain '0 24 * * *') | |
| 210 | +json_ok "hour 24 is rejected" "$R" "d['valid'] is False" | |
| 211 | +check "hour 24 error names the range" '0-23' "$R" | |
| 212 | + | |
| 213 | +R=$(explain '0 0 32 * *') | |
| 214 | +json_ok "day 32 is rejected" "$R" "d['valid'] is False" | |
| 215 | + | |
| 216 | +R=$(explain '0 0 * 13 *') | |
| 217 | +json_ok "month 13 is rejected" "$R" "d['valid'] is False" | |
| 218 | + | |
| 219 | +R=$(explain '0 0 * * 9') | |
| 220 | +json_ok "day-of-week 9 is rejected" "$R" "d['valid'] is False" | |
| 221 | + | |
| 222 | +R=$(explain '* * *') | |
| 223 | +json_ok "three fields are rejected" "$R" "d['valid'] is False" | |
| 224 | +check "three-field error says 5 fields" 'expected 5 fields' "$R" | |
| 225 | + | |
| 226 | +R=$(explain '* * * * * *') | |
| 227 | +json_ok "six fields are rejected" "$R" "d['valid'] is False" | |
| 228 | + | |
| 229 | +R=$(explain 'abc * * * *') | |
| 230 | +json_ok "non-numeric minute is rejected" "$R" "d['valid'] is False" | |
| 231 | + | |
| 232 | +R=$(explain '*/0 * * * *') | |
| 233 | +json_ok "zero step is rejected" "$R" "d['valid'] is False" | |
| 234 | + | |
| 235 | +R=$(explain '5-1 * * * *') | |
| 236 | +json_ok "descending range is rejected" "$R" "d['valid'] is False" | |
| 237 | + | |
| 238 | +R=$(explain '@sometimes') | |
| 239 | +json_ok "unknown keyword is rejected" "$R" "d['valid'] is False" | |
| 240 | +check "unknown keyword error is explicit" 'unknown @keyword' "$R" | |
| 241 | + | |
| 242 | +R=$(body "$(QUERY_STRING='action=explain' $BIN)") | |
| 243 | +json_ok "missing expr parameter fails cleanly" "$R" "d['ok'] is False" | |
| 244 | +check "missing expr names the parameter" 'missing expr' "$R" | |
| 245 | + | |
| 246 | +R=$(explain '0 12 * * *') | |
| 247 | +json_ok "noon schedule returns UTC times" "$R" "d['next'][0]['utc'].endswith('T12:00:00Z')" | |
| 248 | +json_ok "noon schedule carries a local string" "$R" "len(d['next'][0]['local']) == 16" | |
| 249 | + | |
| 250 | +# URL-encoded spaces and plus signs survive | |
| 251 | +R=$(body "$(QUERY_STRING='action=explain&expr=0+1+*+*+*' $BIN)") | |
| 252 | +json_ok "plus-sign space encoding works" "$R" "d['valid'] is True and d['fields']['hour']=='1'" | |
| 253 | + | |
| 254 | +# ---------------------------------------------------------------- jobs | |
| 255 | +section "mode 2b — local job listing" | |
| 256 | +J=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='action=jobs' $BIN)") | |
| 257 | +json_ok "jobs returns valid JSON" "$J" "d['ok'] is True" | |
| 258 | +json_ok "jobs counts only real schedule lines" "$J" "d['count']==7" | |
| 259 | +check "jobs source is the fixture" '"fixture"' "$J" | |
| 260 | +check_not "environment assignments are skipped" 'SHELL=/bin/sh' "$J" | |
| 261 | +json_ok "every fixture job parsed" "$J" "all(j['valid'] for j in d['jobs'])" | |
| 262 | +json_ok "each job carries 5 next runs" "$J" "all(len(j['next'])==5 for j in d['jobs'] if j['expr']!='@reboot')" | |
| 263 | +json_ok "@reboot job has no runs" "$J" "any(j['expr']=='@reboot' and j['next']==[] for j in d['jobs'])" | |
| 264 | +json_ok "comments never become jobs" "$J" "not any('comment' in j['command'] for j in d['jobs'])" | |
| 265 | +json_ok "commands are preserved verbatim" "$J" "any(j['command']=='/usr/bin/backup.sh --flag' for j in d['jobs'])" | |
| 266 | +json_ok "descriptions are human readable" "$J" "all(len(j['description'])>3 for j in d['jobs'])" | |
| 267 | +json_ok "kind is marked cron" "$J" "all(j['kind']=='cron' for j in d['jobs'])" | |
| 268 | +json_ok "now timestamps are present" "$J" "'now_utc' in d and 'now_local' in d" | |
| 269 | +json_ok "truncated flag is false" "$J" "d['truncated'] is False" | |
| 270 | + | |
| 271 | +S=$(body "$(CRONTAB_FILE="$SYS" QUERY_STRING='action=jobs' $BIN)") | |
| 272 | +json_ok "system crontab format parses" "$S" "d['count']==2" | |
| 273 | +json_ok "system format extracts the run-as user" "$S" "all(j['user']=='root' for j in d['jobs'])" | |
| 274 | +json_ok "system format keeps the command" "$S" "any('run-parts' in j['command'] for j in d['jobs'])" | |
| 275 | +json_ok "system hourly job reads as minute 17" "$S" "any('minute 17' in j['description'] for j in d['jobs'])" | |
| 276 | + | |
| 277 | +E=$(body "$(CRONTAB_FILE="$EMPTY" QUERY_STRING='action=jobs' $BIN)") | |
| 278 | +json_ok "empty fixture returns zero jobs" "$E" "d['count']==0" | |
| 279 | +json_ok "empty fixture still returns ok" "$E" "d['ok'] is True and d['jobs']==[]" | |
| 280 | + | |
| 281 | +B=$(body "$(CRONTAB_FILE="$BAD" QUERY_STRING='action=jobs' $BIN)") | |
| 282 | +json_ok "malformed lines still produce a response" "$B" "d['ok'] is True" | |
| 283 | +json_ok "invalid lines are flagged, not dropped" "$B" "any(j['valid'] is False for j in d['jobs'])" | |
| 284 | +json_ok "invalid lines carry an error string" "$B" "all(j['error'] for j in d['jobs'] if not j['valid'])" | |
| 285 | +json_ok "invalid lines have no next runs" "$B" "all(j['next']==[] for j in d['jobs'] if not j['valid'])" | |
| 286 | + | |
| 287 | +L=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='action=list' $BIN)") | |
| 288 | +json_ok "action=list is an alias for jobs" "$L" "d['count']==7" | |
| 289 | + | |
| 290 | +F=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='format=json' $BIN)") | |
| 291 | +json_ok "format=json alone returns the job listing" "$F" "d['ok'] is True and 'jobs' in d" | |
| 292 | + | |
| 293 | +I=$(body "$(QUERY_STRING='action=info' $BIN)") | |
| 294 | +json_ok "info action returns metadata" "$I" "d['plugin']=='plugin_crontab'" | |
| 295 | +json_ok "info declares read-only" "$I" "d['read_only'] is True" | |
| 296 | +json_ok "info lists the supported actions" "$I" "set(d['actions'])=={'jobs','explain','info'}" | |
| 297 | +json_ok "info carries a trust notice" "$I" "len(d['trust_notice'])>20" | |
| 298 | + | |
| 299 | +U=$(body "$(QUERY_STRING='action=nope' $BIN)") | |
| 300 | +json_ok "unknown action fails cleanly" "$U" "d['ok'] is False" | |
| 301 | +check "unknown action names the problem" 'unknown action' "$U" | |
| 302 | + | |
| 303 | +# ---------------------------------------------------------------- auth | |
| 304 | +section "node password gate" | |
| 305 | +A=$(QUERY_STRING='action=info' BOT_PASSWORD=s3cret $BIN) | |
| 306 | +check "wrong password is rejected" '401 Unauthorized' "$A" | |
| 307 | +A=$(QUERY_STRING='action=info' BOT_PASSWORD=s3cret HTTP_X_BOT_PASSWORD=s3cret $BIN) | |
| 308 | +check "X-Bot-Password header is accepted" '"ok":true' "$A" | |
| 309 | +A=$(QUERY_STRING='action=info' BOT_PASSWORD=s3cret HTTP_AUTHORIZATION='Bearer s3cret' $BIN) | |
| 310 | +check "Bearer token is accepted" '"ok":true' "$A" | |
| 311 | +A=$(QUERY_STRING='action=info&pwd=s3cret' BOT_PASSWORD=s3cret $BIN) | |
| 312 | +check "pwd query parameter is accepted" '"ok":true' "$A" | |
| 313 | +A=$(QUERY_STRING='action=info&pwd=wrong' BOT_PASSWORD=s3cret $BIN) | |
| 314 | +check "wrong pwd query parameter is rejected" '401 Unauthorized' "$A" | |
| 315 | + | |
| 316 | +# ---------------------------------------------------------------- html | |
| 317 | +section "mode 3 — HTML UI" | |
| 318 | +HTML=$(CRONTAB_FILE="$FIX" QUERY_STRING='' $BIN) | |
| 319 | +check "HTML declares utf-8 charset" "Content-Type: text/html; charset=utf-8" "$HTML" | |
| 320 | +check "HTML sets no-store" 'Cache-Control: no-store' "$HTML" | |
| 321 | +check_not "HTML sets no Content-Length" 'Content-Length' "$HTML" | |
| 322 | +check "HTML has a doctype" '<!DOCTYPE html>' "$HTML" | |
| 323 | +check "HTML shows the plugin title" "<h1 class='title'>crontab</h1>" "$HTML" | |
| 324 | +check "HTML has the jobs table" "<tbody id='rows'>" "$HTML" | |
| 325 | +check "HTML has the playground input" "id='ex'" "$HTML" | |
| 326 | +check "HTML has the explain button" "id='goBtn'" "$HTML" | |
| 327 | +check "HTML has a theme toggle" "id='themeBtn'" "$HTML" | |
| 328 | +check "HTML honours bot_theme" 'bot_theme' "$HTML" | |
| 329 | +check "HTML polls for refreshes" 'setInterval(load' "$HTML" | |
| 330 | +check "HTML documents read-only behaviour" 'never' "$HTML" | |
| 331 | +check "HTML mentions the fixture override" 'CRONTAB_FILE' "$HTML" | |
| 332 | +check "HTML has a mobile breakpoint" '@media(max-width:640px)' "$HTML" | |
| 333 | +check "HTML escapes its own shell prompt" "location.pathname" "$HTML" | |
| 334 | +check "HTML exposes the KPI block" "id='k-total'" "$HTML" | |
| 335 | +check "HTML playground defaults to a real expression" "*/15 9-17 * * 1-5" "$HTML" | |
| 336 | +check_not "HTML contains no emoji" '🚀' "$HTML" | |
| 337 | + | |
| 338 | +EMB=$(CRONTAB_FILE="$FIX" QUERY_STRING='embed=1' $BIN) | |
| 339 | +check_not "embed=1 hides the back link" 'Back to Bot' "$EMB" | |
| 340 | +check "embed=1 still renders the table" "<tbody id='rows'>" "$EMB" | |
| 341 | +PL=$(CRONTAB_FILE="$FIX" QUERY_STRING='embed=1' BOT_PASSWORD= $BIN) | |
| 342 | +check "embed as string 'true' also works" 'crontab' "$(CRONTAB_FILE="$FIX" QUERY_STRING='embed=true' $BIN)" | |
| 343 | + | |
| 344 | +# ---------------------------------------------------------------- read-only | |
| 345 | +section "read-only guarantees" | |
| 346 | +N=$(grep -c 'crontab -l' src/plugin_crontab.c) | |
| 347 | +if [ "$N" -ge 1 ]; then pass "plugin reads the user crontab"; else fail "no crontab -l read found"; fi | |
| 348 | +check_not "no crontab write path" 'crontab -' "$(grep -v 'crontab -l' src/plugin_crontab.c | grep -F 'crontab -' || true)" | |
| 349 | +check_not "no crontab install path" 'crontab -r' "$(cat src/plugin_crontab.c)" | |
| 350 | +check_not "no schtasks write path" 'schtasks /Create' "$(cat src/plugin_crontab.c)" | |
| 351 | +check_not "no repository-network egress" 'http://' "$(cat src/plugin_crontab.c)" | |
| 352 | +check_not "no TLS egress" 'https://' "$(cat src/plugin_crontab.c)" | |
| 353 | +check_not "no socket API" 'socket(' "$(cat src/plugin_crontab.c)" | |
| 354 | +check "reads the system crontab" '/etc/crontab' "$(cat src/plugin_crontab.c)" | |
| 355 | +check "reads cron.d drop-ins" '/etc/cron.d' "$(cat src/plugin_crontab.c)" | |
| 356 | +check "supports the Windows task list" 'schtasks /Query' "$(cat src/plugin_crontab.c)" | |
| 357 | +check "honours CRONTAB_FILE" 'CRONTAB_FILE' "$(cat src/plugin_crontab.c)" | |
| 358 | + | |
| 359 | +# ---------------------------------------------------------------- cross builds | |
| 360 | +section "cross-platform artifacts" | |
| 361 | +if [ -f "$BIN.musl" ]; then | |
| 362 | + if file "$BIN.musl" 2>/dev/null | grep -q 'statically linked'; then | |
| 363 | + pass "musl build is statically linked" | |
| 364 | + else | |
| 365 | + pass "musl build present (file(1) unavailable or non-static report)" | |
| 366 | + fi | |
| 367 | + M2=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='action=jobs' "$BIN".musl)") | |
| 368 | + check "musl build runs" '"ok":true' "$M2" | |
| 369 | +else | |
| 370 | + echo " skip musl build (not built here)" | |
| 371 | +fi | |
| 372 | + | |
| 373 | +if [ -f plugin_crontab.exe ]; then | |
| 374 | + if [ "$(head -c 2 plugin_crontab.exe)" = "MZ" ]; then | |
| 375 | + pass "windows artifact starts with an MZ header" | |
| 376 | + else | |
| 377 | + fail "windows artifact is not a PE" | |
| 378 | + fi | |
| 379 | + SZ=$(wc -c < plugin_crontab.exe | tr -d ' ') | |
| 380 | + if [ "$SZ" -gt 20000 ]; then pass "windows artifact has a plausible size"; else fail "windows artifact is too small"; fi | |
| 381 | +else | |
| 382 | + echo " skip windows artifact (not built here)" | |
| 383 | +fi | |
| 384 | + | |
| 385 | +for f in LICENSE README.md Makefile build.ps1 release-dist.sh; do | |
| 386 | + [ -f "$f" ] && pass "$f present" || fail "$f missing" | |
| 387 | +done | |
| 388 | +check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)" | |
| 389 | +check "README documents the actions" 'action=explain' "$(cat README.md)" | |
| 390 | + | |
| 391 | +# ---------------------------------------------------------------- history audit | |
| 392 | +section "git history secret audit" | |
| 393 | +if git rev-parse --git-dir >/dev/null 2>&1; then | |
| 394 | + ALL="$WORK/history.txt" | |
| 395 | + git log -p --all 2>/dev/null \ | |
| 396 | + | grep -v '^Author: ' \ | |
| 397 | + | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "html has no internal fleet' \ | |
| 398 | + > "$ALL" || : > "$ALL" | |
| 399 | + | |
| 400 | + audit() { # audit <label> <regex> | |
| 401 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | |
| 402 | + if [ -n "$H" ]; then | |
| 403 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | |
| 404 | + else | |
| 405 | + pass "history clean: $1" | |
| 406 | + fi | |
| 407 | + } | |
| 408 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 409 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 410 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 411 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 412 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 413 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 414 | + audit "internal fleet path" '/codebases/[a-z]|\.worktrees/' | |
| 415 | +else | |
| 416 | + echo " skip history audit (not a git checkout)" | |
| 417 | +fi | |
| 418 | + | |
| 419 | +# ---------------------------------------------------------------- summary | |
| 420 | +rm -rf "$WORK" | |
| 421 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | |
| 422 | +printf ' passed: %d\n' "$PASS" | |
| 423 | +printf ' failed: %d\n' "$FAIL" | |
| 424 | +if [ "$FAIL" -ne 0 ]; then | |
| 425 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | |
| 426 | + exit 1 | |
| 427 | +fi | |
| 428 | +printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0" | |
| 429 | +exit 0 | |
| 0 | 430 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..6382725 | index 0000000..6382725 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,8 @@ | @@ -0,0 +1,8 @@ | ||
| 1 | +/plugin_crontab | ||
| 2 | +/plugin_crontab.musl | ||
| 3 | +/plugin_crontab.exe | ||
| 4 | +/plugin_crontab.macos-arm64 | ||
| 5 | +/plugin_crontab.macos-x86_64 | ||
| 6 | +*.o | ||
| 7 | +*.tmp | ||
| 8 | +*.dSYM |
| 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..24be400 | index 0000000..24be400 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,56 @@ | @@ -0,0 +1,56 @@ | ||
| 1 | +# plugin_crontab — ScorpioX Bot open-source cron schedule inspector | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_crontab | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_crontab (fully static) | ||
| 6 | +# make win64 MinGW-w64 static -> ./plugin_crontab.exe | ||
| 7 | +# make macos Apple clang -> ./plugin_crontab (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 -Wno-overlength-strings | ||
| 15 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 16 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings | ||
| 17 | +SRC := src/plugin_crontab.c | ||
| 18 | +BIN := plugin_crontab | ||
| 19 | +EXE := plugin_crontab.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).musl $(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) $(BIN).musl $(EXE) $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 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..eb4c10d | index 0000000..eb4c10d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,192 @@ | @@ -0,0 +1,192 @@ | ||
| 1 | +# plugin_crontab — ScorpioX Bot open-source cron schedule inspector | ||
| 2 | + | ||
| 3 | +A clean-room, MIT-licensed [ScorpioX Bot](https://bot.scorpiox.net) dynamic plugin that | ||
| 4 | +shows the scheduled entries on **your own node**, explains what each cron expression | ||
| 5 | +means in plain English, and computes the exact next five firing times — in UTC and in | ||
| 6 | +your local time. It also ships an interactive cron playground that works on any machine, | ||
| 7 | +even one with zero cron jobs installed. | ||
| 8 | + | ||
| 9 | +One C99 file. No dependencies. No daemon of its own. No outbound network requests. | ||
| 10 | + | ||
| 11 | +``` | ||
| 12 | +plugin_crontab --meta | ||
| 13 | +{"name":"crontab","desc":"Cron jobs"} | ||
| 14 | +``` | ||
| 15 | + | ||
| 16 | +--- | ||
| 17 | + | ||
| 18 | +## What it does | ||
| 19 | + | ||
| 20 | +| Area | Detail | | ||
| 21 | +|---|---| | ||
| 22 | +| **Job listing** | Reads `crontab -l`, `/etc/crontab` and every file in `/etc/cron.d` on Linux and macOS. On Windows it reads `schtasks /Query /FO CSV /NH`. | | ||
| 23 | +| **Schedule parsing** | Full five-field syntax: `*`, `N`, `a-b`, `*/step`, `a-b/step` and comma lists, plus month and weekday names (`JAN`, `mon-fri`, ...). `0` and `7` both mean Sunday. | | ||
| 24 | +| **Keywords** | `@reboot`, `@hourly`, `@daily`, `@midnight`, `@weekly`, `@monthly`, `@yearly`, `@annually`. | | ||
| 25 | +| **Plain English** | Every expression is described: `Every 15 minutes, between 09:00 and 17:59, on Monday, Tuesday, Wednesday, Thursday, Friday`. | | ||
| 26 | +| **Next runs** | The next five firing times, as ISO-8601 UTC and as local `YYYY-MM-DD HH:MM`, with a second-by-second countdown in the UI. | | ||
| 27 | +| **Playground** | Type any expression and get live validation plus its next five runs. Works with no crontab present. | | ||
| 28 | +| **Day semantics** | Honours the classic cron rule: when both day-of-month and day-of-week are restricted, a day matches if **either** field matches. | | ||
| 29 | +| **Theme** | Follows the Bot theme (`localStorage.bot_theme`), dark by default, no flash. | | ||
| 30 | +| **Embed mode** | `?embed=1` drops the back-link so it fits the chat floating window. | | ||
| 31 | + | ||
| 32 | +### Why it is safe | ||
| 33 | + | ||
| 34 | +**1. Strictly read-only.** There is no code path that writes a crontab, installs a | ||
| 35 | +scheduled task, or executes a scheduled command. The only external programs invoked are | ||
| 36 | +`crontab -l` (POSIX, list) and `schtasks /Query` (Windows, query). Both are read-only and | ||
| 37 | +both are hard-coded — no user-supplied value ever reaches a command line, so there is no | ||
| 38 | +injection surface at all. | ||
| 39 | + | ||
| 40 | +**2. Node authentication.** The node API (`:8150`) is reachable from the LAN, so the plugin | ||
| 41 | +refuses any request that does not carry the node password. Accepted forms match the rest of | ||
| 42 | +the node API: `X-Bot-Password: <pwd>` (what `bot-web` proxies with), `Authorization: Bearer | ||
| 43 | +<pwd>`, or `?pwd=<pwd>` (what the plugin iframe appends). If `BOT_PASSWORD` is unset the node | ||
| 44 | +is in explicitly open mode and the check is a no-op, exactly like `terminal_tmux.c`. | ||
| 45 | + | ||
| 46 | +**3. Deterministic fixture mode.** `CRONTAB_FILE=/path/to/file` makes the parser read that | ||
| 47 | +file instead of the live machine. That is what the test suite uses, and it means the whole | ||
| 48 | +scheduler model can be audited offline without touching a real crontab. | ||
| 49 | + | ||
| 50 | +**4. No network egress.** The binary contains no `http://`, no `https://` and no socket | ||
| 51 | +call. All it does is read local files and print. | ||
| 52 | + | ||
| 53 | +--- | ||
| 54 | + | ||
| 55 | +## Install | ||
| 56 | + | ||
| 57 | +### Pre-built (no compiler needed) | ||
| 58 | + | ||
| 59 | +```sh | ||
| 60 | +# Linux x86_64 — the static musl binary works on Alpine, Debian, Ubuntu, Arch, Omarchy | ||
| 61 | +mkdir -p ~/.scorpiox/plugins | ||
| 62 | +curl -fsSL https://dist.scorpiox.net/bot-plugins/crontab/1.0.0/linux-x86_64-musl/plugin_crontab \ | ||
| 63 | + -o ~/.scorpiox/plugins/plugin_crontab | ||
| 64 | +chmod +x ~/.scorpiox/plugins/plugin_crontab | ||
| 65 | +~/.scorpiox/plugins/plugin_crontab --meta | ||
| 66 | +``` | ||
| 67 | + | ||
| 68 | +On Windows, put `plugin_crontab.exe` in `%LOCALAPPDATA%\scorpiox\plugins\`. | ||
| 69 | +On a BotCloud container, use `/workspace/.scorpiox/plugins/` so it survives restarts. | ||
| 70 | + | ||
| 71 | +No server restart is required — `scorpiox-server` resolves plugin routes live. | ||
| 72 | + | ||
| 73 | +### From source | ||
| 74 | + | ||
| 75 | +```sh | ||
| 76 | +git clone https://plugingit.scorpiox.net/scorpiox-bot-plugin-crontab.git | ||
| 77 | +cd scorpiox-bot-plugin-crontab | ||
| 78 | +make # native build -> ./plugin_crontab | ||
| 79 | +make musl # fully static Linux -> ./plugin_crontab.musl | ||
| 80 | +make win64 # static Windows PE -> ./plugin_crontab.exe | ||
| 81 | +make test # 80+ offline assertions | ||
| 82 | +``` | ||
| 83 | + | ||
| 84 | +### Agent-assisted build | ||
| 85 | + | ||
| 86 | +Paste this into ScorpioX Bot Chat: | ||
| 87 | + | ||
| 88 | +> Clone `https://plugingit.scorpiox.net/scorpiox-bot-plugin-crontab.git`, audit | ||
| 89 | +> `src/plugin_crontab.c` for safety, customise it for my setup, compile it natively on this | ||
| 90 | +> machine, verify `--meta`, and install it to `~/.scorpiox/plugins/`. | ||
| 91 | + | ||
| 92 | +Because the plugin is a single dependency-free C99 file, that takes seconds. | ||
| 93 | + | ||
| 94 | +--- | ||
| 95 | + | ||
| 96 | +## HTTP API | ||
| 97 | + | ||
| 98 | +All JSON responses are `Content-Type: application/json; charset=utf-8` with | ||
| 99 | +`Cache-Control: no-store`. | ||
| 100 | + | ||
| 101 | +### `?action=jobs` (alias `list`, or `?format=json`) | ||
| 102 | + | ||
| 103 | +```json | ||
| 104 | +{ | ||
| 105 | + "ok": true, | ||
| 106 | + "action": "jobs", | ||
| 107 | + "plugin": "plugin_crontab", | ||
| 108 | + "version": "1.0.0", | ||
| 109 | + "now_utc": "2026-11-11T04:49:22Z", | ||
| 110 | + "now_local": "2026-11-11 04:49", | ||
| 111 | + "count": 7, | ||
| 112 | + "truncated": false, | ||
| 113 | + "sources": ["user", "/etc/crontab"], | ||
| 114 | + "jobs": [ | ||
| 115 | + { | ||
| 116 | + "source": "user", | ||
| 117 | + "kind": "cron", | ||
| 118 | + "expr": "*/5 * * * *", | ||
| 119 | + "command": "/usr/bin/backup.sh --flag", | ||
| 120 | + "user": "", | ||
| 121 | + "valid": true, | ||
| 122 | + "description": "Every 5 minutes, every day", | ||
| 123 | + "next": [ | ||
| 124 | + {"utc": "2026-11-11T04:50:00Z", "local": "2026-11-11 04:50", "in_seconds": 38} | ||
| 125 | + ] | ||
| 126 | + } | ||
| 127 | + ] | ||
| 128 | +} | ||
| 129 | +``` | ||
| 130 | + | ||
| 131 | +`count` is the number of scheduled entries found. `truncated` is set when the node has more | ||
| 132 | +than 512 entries. Lines that fail to parse are still listed with `valid: false` and an | ||
| 133 | +`error` string, rather than being silently dropped. | ||
| 134 | + | ||
| 135 | +### `?action=explain&expr=<expression>` | ||
| 136 | + | ||
| 137 | +```json | ||
| 138 | +{ | ||
| 139 | + "ok": true, | ||
| 140 | + "action": "explain", | ||
| 141 | + "expr": "*/15 9-17 * * 1-5", | ||
| 142 | + "valid": true, | ||
| 143 | + "keyword": "", | ||
| 144 | + "description": "Every 15 minutes, between 09:00 and 17:59, on Monday, Tuesday, Wednesday, Thursday, Friday", | ||
| 145 | + "normalized": "*/15 9-17 * * 1-5", | ||
| 146 | + "fields": {"minute": "*/15", "hour": "9-17", "day_of_month": "*", "month": "*", "day_of_week": "1-5"}, | ||
| 147 | + "boot_only": false, | ||
| 148 | + "now_utc": "2026-11-11T04:47:32Z", | ||
| 149 | + "now_local": "2026-11-11 04:47", | ||
| 150 | + "next": [ | ||
| 151 | + {"utc": "2026-11-11T09:00:00Z", "local": "2026-11-11 09:00", "in_seconds": 15148} | ||
| 152 | + ] | ||
| 153 | +} | ||
| 154 | +``` | ||
| 155 | + | ||
| 156 | +Invalid expressions return `"valid": false` with a specific `error` | ||
| 157 | +(`minute out of range 0-59`, `expected 5 fields`, `unknown @keyword`, ...). | ||
| 158 | + | ||
| 159 | +`@reboot` returns `"boot_only": true` and an empty `next` array — it has no clock times. | ||
| 160 | + | ||
| 161 | +Explanations are always available, on any machine, whether or not a crontab exists. | ||
| 162 | + | ||
| 163 | +### `?action=info` | ||
| 164 | + | ||
| 165 | +Plugin identity, version, supported actions, capabilities and the trust notice. | ||
| 166 | + | ||
| 167 | +--- | ||
| 168 | + | ||
| 169 | +## Scope boundaries | ||
| 170 | + | ||
| 171 | +- **Read-only.** No crontab writes, no task creation, no command execution. | ||
| 172 | +- **No network.** No sockets, no HTTP client, no telemetry. | ||
| 173 | +- **Two external programs, both query-only:** `crontab -l` and `schtasks /Query`. | ||
| 174 | +- **No user input reaches a shell.** Fixture paths come from the environment, not the query. | ||
| 175 | +- **Next-run horizon** is four years, which covers every expression including | ||
| 176 | + `0 0 29 2 *` (29 February) and `0 0 1 1 *` (1 January). | ||
| 177 | + | ||
| 178 | +--- | ||
| 179 | + | ||
| 180 | +## Layout | ||
| 181 | + | ||
| 182 | +``` | ||
| 183 | +src/plugin_crontab.c the whole plugin: cron parser, next-run engine, JSON API, HTML UI | ||
| 184 | +tests/run.sh 80+ offline assertions, all against fixtures | ||
| 185 | +Makefile all / musl / win64 / macos / test / clean | ||
| 186 | +build.ps1 Windows PowerShell build with an MZ sanity check | ||
| 187 | +release-dist.sh secret scan -> multi-target build -> dist upload -> plugingit mirror | ||
| 188 | +``` | ||
| 189 | + | ||
| 190 | +## Licence | ||
| 191 | + | ||
| 192 | +MIT. See `LICENSE`. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..799bff1 | index 0000000..799bff1 | ||
| --- /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_crontab | ||
| 2 | +# | ||
| 3 | +# Usage (from the repo root, PowerShell): | ||
| 4 | +# powershell -ExecutionPolicy Bypass -File build.ps1 | ||
| 5 | +# | ||
| 6 | +# Produces .\plugin_crontab.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_crontab.c" | ||
| 14 | + $Out = Join-Path $ScriptDir "plugin_crontab.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_crontab.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_crontab.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`"" | ||
| 50 | +} | ||
| 51 | +finally { | ||
| 52 | + Pop-Location | ||
| 53 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..a39a843 | index 0000000..a39a843 | ||
| --- /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_crontab 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="crontab" | ||
| 30 | +ID="plugin_crontab" | ||
| 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": "crontab",\n' | ||
| 210 | + printf ' "desc": "Cron jobs",\n' | ||
| 211 | + printf ' "title": "Local Cron Schedule Inspector",\n' | ||
| 212 | + printf ' "summary": "Zero-dependency local cron inspector: lists the scheduled jobs on your node, explains each expression in plain English, and computes the exact next five firing times in UTC and local time. Includes an interactive cron expression playground that works even with no crontab installed.",\n' | ||
| 213 | + printf ' "category": "devtools",\n' | ||
| 214 | + printf ' "version": "%s",\n' "$VERSION" | ||
| 215 | + printf ' "license": "MIT",\n' | ||
| 216 | + printf ' "trust_notice": "Executes native C code on your node. Strictly read-only: reads crontab listings and Windows task lists to describe schedules, never writes a schedule and never executes a scheduled command. Makes zero outbound network requests.",\n' | ||
| 217 | + printf ' "capabilities": ["crontab_read", "cron_parse", "cron_next_run"],\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..7524065 | index 0000000..7524065 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_crontab.c | +++ b/src/plugin_crontab.c | ||
| @@ -0,0 +1,1663 @@ | @@ -0,0 +1,1663 @@ | ||
| 1 | +/* | ||
| 2 | + * plugin_crontab — ScorpioX Bot open-source cron schedule inspector | ||
| 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=jobs | ?action=explain&expr=... | ?format=json -> JSON node API | ||
| 7 | + * 3. GET (default) -> responsive HTML schedule inspector | ||
| 8 | + * | ||
| 9 | + * Strictly READ-ONLY. It never writes a crontab, never installs a task and | ||
| 10 | + * never executes a scheduled command. On POSIX it reads the user's | ||
| 11 | + * `crontab -l` output plus /etc/crontab and the files in /etc/cron.d; on Windows it reads | ||
| 12 | + * `schtasks /Query /FO CSV`. Setting CRONTAB_FILE to a fixture path bypasses | ||
| 13 | + * all of that, which is what the offline tests use. | ||
| 14 | + * | ||
| 15 | + * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and | ||
| 16 | + * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under | ||
| 17 | + * scorpiox-server on the node. | ||
| 18 | + * | ||
| 19 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 20 | + */ | ||
| 21 | + | ||
| 22 | +#if !defined(_WIN32) | ||
| 23 | +# define _POSIX_C_SOURCE 200809L | ||
| 24 | +# define _DEFAULT_SOURCE 1 | ||
| 25 | +#endif | ||
| 26 | + | ||
| 27 | +#include <stdio.h> | ||
| 28 | +#include <stdlib.h> | ||
| 29 | +#include <string.h> | ||
| 30 | +#include <time.h> | ||
| 31 | +#include <ctype.h> | ||
| 32 | + | ||
| 33 | +#if defined(_WIN32) | ||
| 34 | +# define WIN32_LEAN_AND_MEAN | ||
| 35 | +# include <windows.h> | ||
| 36 | +# define sx_popen _popen | ||
| 37 | +# define sx_pclose _pclose | ||
| 38 | +#else | ||
| 39 | +# include <unistd.h> | ||
| 40 | +# include <dirent.h> | ||
| 41 | +# define sx_popen popen | ||
| 42 | +# define sx_pclose pclose | ||
| 43 | +#endif | ||
| 44 | + | ||
| 45 | +#define PLUGIN_SLUG "crontab" | ||
| 46 | +#define PLUGIN_ID "plugin_crontab" | ||
| 47 | +#define PLUGIN_VER "1.0.0" | ||
| 48 | + | ||
| 49 | +#define MAX_JOBS 512 | ||
| 50 | +#define MAX_EXPR 128 | ||
| 51 | +#define MAX_DESC 224 | ||
| 52 | +#define MAX_CMD 512 | ||
| 53 | +#define MAX_SRC 64 | ||
| 54 | +#define MAX_RUNS 5 | ||
| 55 | +#define HORIZON_DAYS 1461 | ||
| 56 | +#define READ_LINE 2048 | ||
| 57 | + | ||
| 58 | +/* ------------------------------------------------------------------ */ | ||
| 59 | +/* Small utilities */ | ||
| 60 | +/* ------------------------------------------------------------------ */ | ||
| 61 | + | ||
| 62 | +static void url_decode(char *s) | ||
| 63 | +{ | ||
| 64 | + char *o = s; | ||
| 65 | + if (!s) return; | ||
| 66 | + while (*s) { | ||
| 67 | + if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { | ||
| 68 | + int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); | ||
| 69 | + int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); | ||
| 70 | + *o++ = (char)((hi << 4) | lo); | ||
| 71 | + s += 3; | ||
| 72 | + } else if (*s == '+') { | ||
| 73 | + *o++ = ' '; | ||
| 74 | + s++; | ||
| 75 | + } else { | ||
| 76 | + *o++ = *s++; | ||
| 77 | + } | ||
| 78 | + } | ||
| 79 | + *o = '\0'; | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 83 | +{ | ||
| 84 | + size_t klen; | ||
| 85 | + const char *p; | ||
| 86 | + | ||
| 87 | + if (!out || outsz == 0) return 0; | ||
| 88 | + out[0] = '\0'; | ||
| 89 | + if (!qs || !key) return 0; | ||
| 90 | + klen = strlen(key); | ||
| 91 | + | ||
| 92 | + for (p = qs; *p; ) { | ||
| 93 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 94 | + const char *v = p + klen + 1; | ||
| 95 | + size_t i = 0; | ||
| 96 | + while (*v && *v != '&' && i + 1 < outsz) | ||
| 97 | + out[i++] = *v++; | ||
| 98 | + out[i] = '\0'; | ||
| 99 | + url_decode(out); | ||
| 100 | + return 1; | ||
| 101 | + } | ||
| 102 | + p = strchr(p, '&'); | ||
| 103 | + if (!p) break; | ||
| 104 | + p++; | ||
| 105 | + } | ||
| 106 | + return 0; | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +static void json_str(const char *s) | ||
| 110 | +{ | ||
| 111 | + putchar('"'); | ||
| 112 | + for (; s && *s; s++) { | ||
| 113 | + unsigned char c = (unsigned char)*s; | ||
| 114 | + switch (c) { | ||
| 115 | + case '"': fputs("\\\"", stdout); break; | ||
| 116 | + case '\\': fputs("\\\\", stdout); break; | ||
| 117 | + case '\n': fputs("\\n", stdout); break; | ||
| 118 | + case '\r': fputs("\\r", stdout); break; | ||
| 119 | + case '\t': fputs("\\t", stdout); break; | ||
| 120 | + default: | ||
| 121 | + if (c < 0x20) printf("\\u%04x", c); | ||
| 122 | + else putchar(c); | ||
| 123 | + } | ||
| 124 | + } | ||
| 125 | + putchar('"'); | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +static void str_copy(char *dst, size_t sz, const char *src) | ||
| 129 | +{ | ||
| 130 | + size_t n; | ||
| 131 | + if (!dst || sz == 0) return; | ||
| 132 | + if (!src) { dst[0] = '\0'; return; } | ||
| 133 | + n = strlen(src); | ||
| 134 | + if (n >= sz) n = sz - 1; | ||
| 135 | + memcpy(dst, src, n); | ||
| 136 | + dst[n] = '\0'; | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +static void str_trim(char *s) | ||
| 140 | +{ | ||
| 141 | + size_t n; | ||
| 142 | + char *p; | ||
| 143 | + | ||
| 144 | + if (!s) return; | ||
| 145 | + p = s; | ||
| 146 | + while (*p && isspace((unsigned char)*p)) p++; | ||
| 147 | + if (p != s) memmove(s, p, strlen(p) + 1); | ||
| 148 | + n = strlen(s); | ||
| 149 | + while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0'; | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +static void utc_stamp(time_t t, char *buf, size_t sz) | ||
| 153 | +{ | ||
| 154 | + struct tm tmv; | ||
| 155 | +#if defined(_WIN32) | ||
| 156 | + gmtime_s(&tmv, &t); | ||
| 157 | +#else | ||
| 158 | + gmtime_r(&t, &tmv); | ||
| 159 | +#endif | ||
| 160 | + if (strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv) == 0) | ||
| 161 | + str_copy(buf, sz, "1970-01-01T00:00:00Z"); | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +static void local_stamp(time_t t, char *buf, size_t sz) | ||
| 165 | +{ | ||
| 166 | + struct tm tmv; | ||
| 167 | +#if defined(_WIN32) | ||
| 168 | + localtime_s(&tmv, &t); | ||
| 169 | +#else | ||
| 170 | + localtime_r(&t, &tmv); | ||
| 171 | +#endif | ||
| 172 | + if (strftime(buf, sz, "%Y-%m-%d %H:%M", &tmv) == 0) | ||
| 173 | + str_copy(buf, sz, "1970-01-01 00:00"); | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +/* ------------------------------------------------------------------ */ | ||
| 177 | +/* Cron model */ | ||
| 178 | +/* ------------------------------------------------------------------ */ | ||
| 179 | + | ||
| 180 | +typedef struct { | ||
| 181 | + int valid; | ||
| 182 | + char error[96]; | ||
| 183 | + char raw[MAX_EXPR]; | ||
| 184 | + char keyword[16]; /* "@daily" etc; empty for 5-field syntax */ | ||
| 185 | + char f[5][40]; /* original field texts */ | ||
| 186 | + unsigned char min[60]; | ||
| 187 | + unsigned char hour[24]; | ||
| 188 | + unsigned char dom[32]; /* index 1..31 used */ | ||
| 189 | + unsigned char mon[13]; /* index 1..12 used */ | ||
| 190 | + unsigned char dow[7]; /* index 0 == Sunday */ | ||
| 191 | + int dom_restricted; | ||
| 192 | + int dow_restricted; | ||
| 193 | + int boot_only; /* @reboot — no computable fire times */ | ||
| 194 | + char desc[MAX_DESC]; | ||
| 195 | +} cron_t; | ||
| 196 | + | ||
| 197 | +static const char *const k_mon_names[12] = { | ||
| 198 | + "jan", "feb", "mar", "apr", "may", "jun", | ||
| 199 | + "jul", "aug", "sep", "oct", "nov", "dec" | ||
| 200 | +}; | ||
| 201 | +static const char *const k_dow_names[7] = { "sun", "mon", "tue", "wed", "thu", "fri", "sat" }; | ||
| 202 | +static const char *const k_mon_long[12] = { | ||
| 203 | + "January", "February", "March", "April", "May", "June", | ||
| 204 | + "July", "August", "September", "October", "November", "December" | ||
| 205 | +}; | ||
| 206 | +static const char *const k_dow_long[7] = { | ||
| 207 | + "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" | ||
| 208 | +}; | ||
| 209 | + | ||
| 210 | +static void cron_clear(cron_t *c) | ||
| 211 | +{ | ||
| 212 | + memset(c, 0, sizeof(*c)); | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +static int name_index(const char *tok, int len, const char *const *names, int count) | ||
| 216 | +{ | ||
| 217 | + int i; | ||
| 218 | + char buf[16]; | ||
| 219 | + if (len <= 0 || len >= (int)sizeof(buf)) return -1; | ||
| 220 | + for (i = 0; i < len; i++) buf[i] = (char)tolower((unsigned char)tok[i]); | ||
| 221 | + buf[len] = '\0'; | ||
| 222 | + for (i = 0; i < count; i++) | ||
| 223 | + if (strcmp(buf, names[i]) == 0) return i; | ||
| 224 | + return -1; | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +/* Plain number or 3-letter name -> value. Returns 1 on success. */ | ||
| 228 | +static int parse_value(const char *tok, int len, const char *const *names, | ||
| 229 | + int namecount, int name_offset, int *out) | ||
| 230 | +{ | ||
| 231 | + int i; | ||
| 232 | + int v = 0; | ||
| 233 | + int named; | ||
| 234 | + | ||
| 235 | + if (len <= 0) return 0; | ||
| 236 | + named = name_index(tok, len, names, namecount); | ||
| 237 | + if (named >= 0) { *out = named + name_offset; return 1; } | ||
| 238 | + for (i = 0; i < len; i++) { | ||
| 239 | + if (!isdigit((unsigned char)tok[i])) return 0; | ||
| 240 | + v = v * 10 + (tok[i] - '0'); | ||
| 241 | + if (v > 100000) return 0; | ||
| 242 | + } | ||
| 243 | + *out = v; | ||
| 244 | + return 1; | ||
| 245 | +} | ||
| 246 | + | ||
| 247 | +/* | ||
| 248 | + * Parse one cron field into a flag array (indices lo..hi). | ||
| 249 | + * Accepts "*", "N", "a-b", "*/step", "a-b/step" and comma lists. | ||
| 250 | + * Returns 1 on success, 0 on syntax error, -1 on out-of-range value. | ||
| 251 | + */ | ||
| 252 | +static int parse_field(const char *text, int lo, int hi, | ||
| 253 | + const char *const *names, int namecount, int name_offset, | ||
| 254 | + unsigned char *flags) | ||
| 255 | +{ | ||
| 256 | + char work[256]; | ||
| 257 | + char *item; | ||
| 258 | + | ||
| 259 | + memset(flags, 0, (size_t)(hi + 1)); | ||
| 260 | + if (!text || !*text) return 0; | ||
| 261 | + if (strlen(text) >= sizeof(work)) return 0; | ||
| 262 | + str_copy(work, sizeof(work), text); | ||
| 263 | + | ||
| 264 | + item = work; | ||
| 265 | + while (item && *item) { | ||
| 266 | + char *comma = strchr(item, ','); | ||
| 267 | + char rng[128]; | ||
| 268 | + const char *slash; | ||
| 269 | + int step = 1; | ||
| 270 | + int start = lo; | ||
| 271 | + int end = hi; | ||
| 272 | + int v; | ||
| 273 | + | ||
| 274 | + if (comma) *comma = '\0'; | ||
| 275 | + str_trim(item); | ||
| 276 | + if (!*item) return 0; | ||
| 277 | + | ||
| 278 | + slash = strchr(item, '/'); | ||
| 279 | + if (slash) { | ||
| 280 | + size_t off = (size_t)(slash - item); | ||
| 281 | + if (off >= sizeof(rng)) return 0; | ||
| 282 | + memcpy(rng, item, off); | ||
| 283 | + rng[off] = '\0'; | ||
| 284 | + if (!parse_value(slash + 1, (int)strlen(slash + 1), NULL, 0, 0, &step)) return 0; | ||
| 285 | + if (step <= 0) return 0; | ||
| 286 | + if (step > hi - lo + 1) step = hi - lo + 1; | ||
| 287 | + } else { | ||
| 288 | + str_copy(rng, sizeof(rng), item); | ||
| 289 | + } | ||
| 290 | + | ||
| 291 | + if (strcmp(rng, "*") == 0) { | ||
| 292 | + start = lo; | ||
| 293 | + end = hi; | ||
| 294 | + } else { | ||
| 295 | + const char *dash = strchr(rng, '-'); | ||
| 296 | + if (dash) { | ||
| 297 | + if (!parse_value(rng, (int)(dash - rng), names, namecount, name_offset, &start)) return 0; | ||
| 298 | + if (!parse_value(dash + 1, (int)strlen(dash + 1), names, namecount, name_offset, &end)) return 0; | ||
| 299 | + } else { | ||
| 300 | + if (!parse_value(rng, (int)strlen(rng), names, namecount, name_offset, &start)) return 0; | ||
| 301 | + end = slash ? hi : start; | ||
| 302 | + } | ||
| 303 | + } | ||
| 304 | + | ||
| 305 | + if (start < lo || start > hi || end < lo || end > hi) return -1; | ||
| 306 | + if (end < start) return -1; | ||
| 307 | + for (v = start; v <= end; v += step) flags[v] = 1; | ||
| 308 | + | ||
| 309 | + if (!comma) break; | ||
| 310 | + item = comma + 1; | ||
| 311 | + } | ||
| 312 | + return 1; | ||
| 313 | +} | ||
| 314 | + | ||
| 315 | +/* True when every value in lo..hi is selected. */ | ||
| 316 | +static int field_is_full(const unsigned char *flags, int lo, int hi) | ||
| 317 | +{ | ||
| 318 | + int i; | ||
| 319 | + for (i = lo; i <= hi; i++) | ||
| 320 | + if (!flags[i]) return 0; | ||
| 321 | + return 1; | ||
| 322 | +} | ||
| 323 | + | ||
| 324 | +static int count_set(const unsigned char *flags, int lo, int hi) | ||
| 325 | +{ | ||
| 326 | + int i, n = 0; | ||
| 327 | + for (i = lo; i <= hi; i++) if (flags[i]) n++; | ||
| 328 | + return n; | ||
| 329 | +} | ||
| 330 | + | ||
| 331 | +/* ---------------------------------------------------------------- */ | ||
| 332 | +/* Portable UTC mktime */ | ||
| 333 | +/* ---------------------------------------------------------------- */ | ||
| 334 | + | ||
| 335 | +static time_t timegm_portable(struct tm *tmv) | ||
| 336 | +{ | ||
| 337 | +#if defined(_WIN32) | ||
| 338 | + return _mkgmtime(tmv); | ||
| 339 | +#else | ||
| 340 | + return timegm(tmv); | ||
| 341 | +#endif | ||
| 342 | +} | ||
| 343 | +/* ---------------------------------------------------------------- */ | ||
| 344 | +/* Human readable description of a parsed schedule */ | ||
| 345 | +/* ---------------------------------------------------------------- */ | ||
| 346 | + | ||
| 347 | +/* Append with bounds. */ | ||
| 348 | +static void sapp(char *dst, size_t sz, const char *src) | ||
| 349 | +{ | ||
| 350 | + size_t have; | ||
| 351 | + if (!dst || sz == 0 || !src) return; | ||
| 352 | + have = strlen(dst); | ||
| 353 | + if (have + 1 >= sz) return; | ||
| 354 | + strncat(dst, src, sz - have - 1); | ||
| 355 | +} | ||
| 356 | + | ||
| 357 | +/* First selected index in [lo,hi], or lo when none. */ | ||
| 358 | +static int first_set(const unsigned char *flags, int lo, int hi) | ||
| 359 | +{ | ||
| 360 | + int i; | ||
| 361 | + for (i = lo; i <= hi; i++) if (flags[i]) return i; | ||
| 362 | + return lo; | ||
| 363 | +} | ||
| 364 | + | ||
| 365 | +static void cron_describe_time(const cron_t *c, char *out, size_t sz) | ||
| 366 | +{ | ||
| 367 | + int nm, nh; | ||
| 368 | + | ||
| 369 | + out[0] = '\0'; | ||
| 370 | + | ||
| 371 | + if (field_is_full(c->min, 0, 59) && field_is_full(c->hour, 0, 23)) { | ||
| 372 | + str_copy(out, sz, "Every minute"); | ||
| 373 | + return; | ||
| 374 | + } | ||
| 375 | + if (c->f[0][0] == '*' && c->f[0][1] == '/' && field_is_full(c->hour, 0, 23) | ||
| 376 | + && !strchr(c->f[0], ',')) { | ||
| 377 | + int step = atoi(c->f[0] + 2); | ||
| 378 | + if (step == 1) str_copy(out, sz, "Every minute"); | ||
| 379 | + else snprintf(out, sz, "Every %d minutes", step); | ||
| 380 | + return; | ||
| 381 | + } | ||
| 382 | + if (field_is_full(c->hour, 0, 23) && c->f[1][0] == '*') { | ||
| 383 | + int n = count_set(c->min, 0, 59); | ||
| 384 | + if (c->f[0][0] == '*' && c->f[0][1] == '\0') { | ||
| 385 | + str_copy(out, sz, "Every minute"); | ||
| 386 | + } else if (n <= 6) { | ||
| 387 | + int m, first = 1; | ||
| 388 | + sapp(out, sz, "Every hour at minute "); | ||
| 389 | + for (m = 0; m < 60; m++) { | ||
| 390 | + char t[8]; | ||
| 391 | + if (!c->min[m]) continue; | ||
| 392 | + snprintf(t, sizeof(t), "%s%d", first ? "" : " and ", m); | ||
| 393 | + sapp(out, sz, t); | ||
| 394 | + first = 0; | ||
| 395 | + } | ||
| 396 | + } else { | ||
| 397 | + snprintf(out, sz, "Every hour at %d selected minutes", n); | ||
| 398 | + } | ||
| 399 | + return; | ||
| 400 | + } | ||
| 401 | + if (c->f[1][0] == '*' && c->f[1][1] == '/' && c->min[0] == 0 | ||
| 402 | + && count_set(c->min, 0, 59) == 1 && !c->dom_restricted && !c->dow_restricted) { | ||
| 403 | + int step = atoi(c->f[1] + 2); | ||
| 404 | + snprintf(out, sz, "Every %d hours at minute %d", step, first_set(c->min, 0, 59)); | ||
| 405 | + return; | ||
| 406 | + } | ||
| 407 | + | ||
| 408 | + nm = count_set(c->min, 0, 59); | ||
| 409 | + nh = count_set(c->hour, 0, 23); | ||
| 410 | + | ||
| 411 | + /* uniform minute step inside a restricted hour window */ | ||
| 412 | + if (c->f[0][0] == '*' && c->f[0][1] == '/' && !strchr(c->f[0], ',')) { | ||
| 413 | + int step = atoi(c->f[0] + 2); | ||
| 414 | + int hlo = first_set(c->hour, 0, 23); | ||
| 415 | + int hhi = hlo; | ||
| 416 | + int h; | ||
| 417 | + for (h = 23; h >= 0; h--) if (c->hour[h]) { hhi = h; break; } | ||
| 418 | + if (step > 0 && nh > 1) { | ||
| 419 | + snprintf(out, sz, "Every %d minutes, between %02d:00 and %02d:59", | ||
| 420 | + step, hlo, hhi); | ||
| 421 | + return; | ||
| 422 | + } | ||
| 423 | + } | ||
| 424 | + | ||
| 425 | + if (nm == 1 && nh == 1) { | ||
| 426 | + snprintf(out, sz, "At %02d:%02d", first_set(c->hour, 0, 23), first_set(c->min, 0, 59)); | ||
| 427 | + return; | ||
| 428 | + } | ||
| 429 | + if (nm * nh <= 6) { | ||
| 430 | + int h, m, first = 1; | ||
| 431 | + sapp(out, sz, "At "); | ||
| 432 | + for (h = 0; h < 24; h++) { | ||
| 433 | + if (!c->hour[h]) continue; | ||
| 434 | + for (m = 0; m < 60; m++) { | ||
| 435 | + char t[8]; | ||
| 436 | + if (!c->min[m]) continue; | ||
| 437 | + snprintf(t, sizeof(t), "%s%02d:%02d", first ? "" : ", ", h, m); | ||
| 438 | + sapp(out, sz, t); | ||
| 439 | + first = 0; | ||
| 440 | + } | ||
| 441 | + } | ||
| 442 | + return; | ||
| 443 | + } | ||
| 444 | + if (nm == 1 && nh < 24) { | ||
| 445 | + int h, first = 1; | ||
| 446 | + char buf[256]; | ||
| 447 | + snprintf(buf, sizeof(buf), "At minute %d past hour%s ", | ||
| 448 | + first_set(c->min, 0, 59), nh == 1 ? "" : "s"); | ||
| 449 | + for (h = 0; h < 24; h++) { | ||
| 450 | + char t[8]; | ||
| 451 | + if (!c->hour[h]) continue; | ||
| 452 | + snprintf(t, sizeof(t), "%s%d", first ? "" : ", ", h); | ||
| 453 | + sapp(buf, sizeof(buf), t); | ||
| 454 | + first = 0; | ||
| 455 | + } | ||
| 456 | + str_copy(out, sz, buf); | ||
| 457 | + return; | ||
| 458 | + } | ||
| 459 | + snprintf(out, sz, "At %d times a day", nm * nh); | ||
| 460 | +} | ||
| 461 | + | ||
| 462 | +static void cron_describe(const cron_t *cc, char *out, size_t sz) | ||
| 463 | +{ | ||
| 464 | + cron_t c = *cc; | ||
| 465 | + char day[128]; | ||
| 466 | + | ||
| 467 | + out[0] = '\0'; | ||
| 468 | + day[0] = '\0'; | ||
| 469 | + | ||
| 470 | + if (c.keyword[0]) { | ||
| 471 | + if (strcmp(c.keyword, "@reboot") == 0) | ||
| 472 | + str_copy(out, sz, "When the system starts"); | ||
| 473 | + else if (strcmp(c.keyword, "@hourly") == 0) | ||
| 474 | + str_copy(out, sz, "Every hour, on the hour"); | ||
| 475 | + else if (strcmp(c.keyword, "@daily") == 0 || strcmp(c.keyword, "@midnight") == 0) | ||
| 476 | + str_copy(out, sz, "Every day at midnight"); | ||
| 477 | + else if (strcmp(c.keyword, "@weekly") == 0) | ||
| 478 | + str_copy(out, sz, "Every Sunday at midnight"); | ||
| 479 | + else if (strcmp(c.keyword, "@monthly") == 0) | ||
| 480 | + str_copy(out, sz, "The 1st of every month at midnight"); | ||
| 481 | + else if (strcmp(c.keyword, "@yearly") == 0 || strcmp(c.keyword, "@annually") == 0) | ||
| 482 | + str_copy(out, sz, "1 January at midnight"); | ||
| 483 | + else | ||
| 484 | + str_copy(out, sz, "Custom schedule"); | ||
| 485 | + return; | ||
| 486 | + } | ||
| 487 | + | ||
| 488 | + cron_describe_time(&c, out, sz); | ||
| 489 | + | ||
| 490 | + /* month restriction */ | ||
| 491 | + if (!field_is_full(c.mon, 1, 12)) { | ||
| 492 | + int n = count_set(c.mon, 1, 12); | ||
| 493 | + int i; | ||
| 494 | + if (n == 1) { | ||
| 495 | + snprintf(day, sizeof(day), "in %s", k_mon_long[first_set(c.mon, 1, 12) - 1]); | ||
| 496 | + } else { | ||
| 497 | + int first = 1; | ||
| 498 | + sapp(day, sizeof(day), "in "); | ||
| 499 | + for (i = 1; i <= 12; i++) { | ||
| 500 | + if (!c.mon[i]) continue; | ||
| 501 | + sapp(day, sizeof(day), first ? "" : ", "); | ||
| 502 | + sapp(day, sizeof(day), k_mon_long[i - 1]); | ||
| 503 | + first = 0; | ||
| 504 | + } | ||
| 505 | + } | ||
| 506 | + } | ||
| 507 | + | ||
| 508 | + /* day-of-month / day-of-week (classic OR semantics when both restricted) */ | ||
| 509 | + if (c.dom_restricted && c.dow_restricted) { | ||
| 510 | + int ndow = count_set(c.dow, 0, 6); | ||
| 511 | + int ndom = count_set(c.dom, 1, 31); | ||
| 512 | + char part[96]; | ||
| 513 | + part[0] = '\0'; | ||
| 514 | + if (ndow == 1) { | ||
| 515 | + sapp(part, sizeof(part), k_dow_long[first_set(c.dow, 0, 6)]); | ||
| 516 | + } else { | ||
| 517 | + int i, first = 1; | ||
| 518 | + for (i = 0; i < 7; i++) { | ||
| 519 | + if (!c.dow[i]) continue; | ||
| 520 | + sapp(part, sizeof(part), first ? "" : ", "); | ||
| 521 | + sapp(part, sizeof(part), k_dow_long[i]); | ||
| 522 | + first = 0; | ||
| 523 | + } | ||
| 524 | + } | ||
| 525 | + sapp(day, sizeof(day), day[0] ? " " : ""); | ||
| 526 | + sapp(day, sizeof(day), "on "); | ||
| 527 | + sapp(day, sizeof(day), part); | ||
| 528 | + if (ndom == 1) { | ||
| 529 | + char t[32]; | ||
| 530 | + snprintf(t, sizeof(t), " or day %d of the month", first_set(c.dom, 1, 31)); | ||
| 531 | + sapp(day, sizeof(day), t); | ||
| 532 | + } else { | ||
| 533 | + sapp(day, sizeof(day), " or on selected days of the month"); | ||
| 534 | + } | ||
| 535 | + } else if (c.dow_restricted) { | ||
| 536 | + int ndow = count_set(c.dow, 0, 6); | ||
| 537 | + sapp(day, sizeof(day), day[0] ? " " : ""); | ||
| 538 | + sapp(day, sizeof(day), "on "); | ||
| 539 | + if (ndow == 1) { | ||
| 540 | + sapp(day, sizeof(day), k_dow_long[first_set(c.dow, 0, 6)]); | ||
| 541 | + } else { | ||
| 542 | + int i, first = 1; | ||
| 543 | + for (i = 0; i < 7; i++) { | ||
| 544 | + if (!c.dow[i]) continue; | ||
| 545 | + sapp(day, sizeof(day), first ? "" : ", "); | ||
| 546 | + sapp(day, sizeof(day), k_dow_long[i]); | ||
| 547 | + first = 0; | ||
| 548 | + } | ||
| 549 | + } | ||
| 550 | + } else if (c.dom_restricted) { | ||
| 551 | + int ndom = count_set(c.dom, 1, 31); | ||
| 552 | + sapp(day, sizeof(day), day[0] ? " " : ""); | ||
| 553 | + if (ndom == 1) { | ||
| 554 | + char t[32]; | ||
| 555 | + snprintf(t, sizeof(t), "on day %d of the month", first_set(c.dom, 1, 31)); | ||
| 556 | + sapp(day, sizeof(day), t); | ||
| 557 | + } else if (c.f[2][0] == '*' && c.f[2][1] == '/') { | ||
| 558 | + char t[48]; | ||
| 559 | + snprintf(t, sizeof(t), "every %d days of the month", atoi(c.f[2] + 2)); | ||
| 560 | + sapp(day, sizeof(day), t); | ||
| 561 | + } else { | ||
| 562 | + int i, first = 1; | ||
| 563 | + sapp(day, sizeof(day), "on days "); | ||
| 564 | + for (i = 1; i <= 31; i++) { | ||
| 565 | + char t[8]; | ||
| 566 | + if (!c.dom[i]) continue; | ||
| 567 | + snprintf(t, sizeof(t), "%s%d", first ? "" : ", ", i); | ||
| 568 | + sapp(day, sizeof(day), t); | ||
| 569 | + first = 0; | ||
| 570 | + } | ||
| 571 | + sapp(day, sizeof(day), " of the month"); | ||
| 572 | + } | ||
| 573 | + } | ||
| 574 | + | ||
| 575 | + if (day[0]) { | ||
| 576 | + char full[MAX_DESC]; | ||
| 577 | + snprintf(full, sizeof(full), "%s, %s", out, day); | ||
| 578 | + str_copy(out, sz, full); | ||
| 579 | + } else if (strncmp(out, "At ", 3) == 0) { | ||
| 580 | + sapp(out, sz, ", every day"); | ||
| 581 | + } | ||
| 582 | +} | ||
| 583 | +/* ---------------------------------------------------------------- */ | ||
| 584 | +/* Expression parsing */ | ||
| 585 | +/* ---------------------------------------------------------------- */ | ||
| 586 | + | ||
| 587 | +static void apply_keyword(cron_t *c, const char *kw) | ||
| 588 | +{ | ||
| 589 | + int i; | ||
| 590 | + for (i = 0; i < 60; i++) c->min[i] = 1; | ||
| 591 | + for (i = 0; i < 24; i++) c->hour[i] = 1; | ||
| 592 | + for (i = 0; i <= 31; i++) c->dom[i] = 1; | ||
| 593 | + for (i = 0; i <= 12; i++) c->mon[i] = 1; | ||
| 594 | + for (i = 0; i < 7; i++) c->dow[i] = 1; | ||
| 595 | + | ||
| 596 | + if (strcmp(kw, "@reboot") == 0) { | ||
| 597 | + c->boot_only = 1; | ||
| 598 | + return; | ||
| 599 | + } | ||
| 600 | + memset(c->min, 0, sizeof(c->min)); | ||
| 601 | + c->min[0] = 1; | ||
| 602 | + if (strcmp(kw, "@hourly") == 0) { | ||
| 603 | + memset(c->hour, 0, sizeof(c->hour)); | ||
| 604 | + for (i = 0; i < 24; i++) c->hour[i] = 1; | ||
| 605 | + return; | ||
| 606 | + } | ||
| 607 | + memset(c->hour, 0, sizeof(c->hour)); | ||
| 608 | + c->hour[0] = 1; | ||
| 609 | + if (strcmp(kw, "@daily") == 0 || strcmp(kw, "@midnight") == 0) return; | ||
| 610 | + if (strcmp(kw, "@weekly") == 0) { | ||
| 611 | + memset(c->dow, 0, sizeof(c->dow)); | ||
| 612 | + c->dow[0] = 1; | ||
| 613 | + c->dow_restricted = 1; | ||
| 614 | + return; | ||
| 615 | + } | ||
| 616 | + if (strcmp(kw, "@monthly") == 0) { | ||
| 617 | + memset(c->dom, 0, sizeof(c->dom)); | ||
| 618 | + c->dom[1] = 1; | ||
| 619 | + c->dom_restricted = 1; | ||
| 620 | + return; | ||
| 621 | + } | ||
| 622 | + if (strcmp(kw, "@yearly") == 0 || strcmp(kw, "@annually") == 0) { | ||
| 623 | + memset(c->dom, 0, sizeof(c->dom)); | ||
| 624 | + memset(c->mon, 0, sizeof(c->mon)); | ||
| 625 | + c->dom[1] = 1; | ||
| 626 | + c->mon[1] = 1; | ||
| 627 | + c->dom_restricted = 1; | ||
| 628 | + return; | ||
| 629 | + } | ||
| 630 | + /* continue for @hourly handled above */ | ||
| 631 | +} | ||
| 632 | + | ||
| 633 | +/* | ||
| 634 | + * Parse a full cron expression: either "@keyword" or five whitespace-separated | ||
| 635 | + * fields. Fills c->valid / c->error. Returns c->valid. | ||
| 636 | + * The expression is trimmed in place into c->raw. | ||
| 637 | + */ | ||
| 638 | +static int cron_parse(cron_t *c, const char *expr) | ||
| 639 | +{ | ||
| 640 | + char work[MAX_EXPR * 2]; | ||
| 641 | + char *tok[8]; | ||
| 642 | + int ntok = 0; | ||
| 643 | + int rc; | ||
| 644 | + char *p; | ||
| 645 | + | ||
| 646 | + cron_clear(c); | ||
| 647 | + str_copy(c->raw, sizeof(c->raw), expr ? expr : ""); | ||
| 648 | + str_copy(work, sizeof(work), c->raw); | ||
| 649 | + str_trim(work); | ||
| 650 | + | ||
| 651 | + if (!work[0]) { | ||
| 652 | + str_copy(c->error, sizeof(c->error), "empty expression"); | ||
| 653 | + return 0; | ||
| 654 | + } | ||
| 655 | + | ||
| 656 | + if (work[0] == '@') { | ||
| 657 | + char kw[24]; | ||
| 658 | + str_copy(kw, sizeof(kw), work); | ||
| 659 | + str_trim(kw); | ||
| 660 | + if (strcmp(kw, "@reboot") != 0 && strcmp(kw, "@hourly") != 0 | ||
| 661 | + && strcmp(kw, "@daily") != 0 && strcmp(kw, "@midnight") != 0 | ||
| 662 | + && strcmp(kw, "@weekly") != 0 && strcmp(kw, "@monthly") != 0 | ||
| 663 | + && strcmp(kw, "@yearly") != 0 && strcmp(kw, "@annually") != 0) { | ||
| 664 | + str_copy(c->error, sizeof(c->error), "unknown @keyword"); | ||
| 665 | + return 0; | ||
| 666 | + } | ||
| 667 | + str_copy(c->keyword, sizeof(c->keyword), kw); | ||
| 668 | + apply_keyword(c, kw); | ||
| 669 | + c->dom_restricted = c->dom_restricted || 0; | ||
| 670 | + c->valid = 1; | ||
| 671 | + cron_describe(c, c->desc, sizeof(c->desc)); | ||
| 672 | + return 1; | ||
| 673 | + } | ||
| 674 | + | ||
| 675 | + for (p = work; *p && ntok < 8; ) { | ||
| 676 | + while (*p && isspace((unsigned char)*p)) *p++ = '\0'; | ||
| 677 | + if (!*p) break; | ||
| 678 | + tok[ntok++] = p; | ||
| 679 | + while (*p && !isspace((unsigned char)*p)) p++; | ||
| 680 | + } | ||
| 681 | + if (ntok != 5) { | ||
| 682 | + str_copy(c->error, sizeof(c->error), | ||
| 683 | + ntok < 5 ? "expected 5 fields" : "too many fields"); | ||
| 684 | + return 0; | ||
| 685 | + } | ||
| 686 | + | ||
| 687 | + { | ||
| 688 | + int i; | ||
| 689 | + for (i = 0; i < 5; i++) str_copy(c->f[i], sizeof(c->f[i]), tok[i]); | ||
| 690 | + } | ||
| 691 | + | ||
| 692 | + rc = parse_field(c->f[0], 0, 59, NULL, 0, 0, c->min); | ||
| 693 | + if (rc <= 0) { | ||
| 694 | + str_copy(c->error, sizeof(c->error), rc < 0 ? "minute out of range 0-59" : "bad minute field"); | ||
| 695 | + return 0; | ||
| 696 | + } | ||
| 697 | + rc = parse_field(c->f[1], 0, 23, NULL, 0, 0, c->hour); | ||
| 698 | + if (rc <= 0) { | ||
| 699 | + str_copy(c->error, sizeof(c->error), rc < 0 ? "hour out of range 0-23" : "bad hour field"); | ||
| 700 | + return 0; | ||
| 701 | + } | ||
| 702 | + rc = parse_field(c->f[2], 1, 31, NULL, 0, 0, c->dom); | ||
| 703 | + if (rc <= 0) { | ||
| 704 | + str_copy(c->error, sizeof(c->error), rc < 0 ? "day-of-month out of range 1-31" : "bad day-of-month field"); | ||
| 705 | + return 0; | ||
| 706 | + } | ||
| 707 | + rc = parse_field(c->f[3], 1, 12, k_mon_names, 12, 1, c->mon); | ||
| 708 | + if (rc <= 0) { | ||
| 709 | + str_copy(c->error, sizeof(c->error), rc < 0 ? "month out of range 1-12" : "bad month field"); | ||
| 710 | + return 0; | ||
| 711 | + } | ||
| 712 | + { | ||
| 713 | + unsigned char tmpdow[8]; | ||
| 714 | + int i; | ||
| 715 | + rc = parse_field(c->f[4], 0, 7, k_dow_names, 7, 0, tmpdow); | ||
| 716 | + if (rc <= 0) { | ||
| 717 | + str_copy(c->error, sizeof(c->error), rc < 0 ? "day-of-week out of range 0-7" : "bad day-of-week field"); | ||
| 718 | + return 0; | ||
| 719 | + } | ||
| 720 | + memset(c->dow, 0, sizeof(c->dow)); | ||
| 721 | + for (i = 0; i <= 7; i++) | ||
| 722 | + if (tmpdow[i]) c->dow[i % 7] = 1; | ||
| 723 | + } | ||
| 724 | + | ||
| 725 | + c->dom_restricted = !field_is_full(c->dom, 1, 31); | ||
| 726 | + c->dow_restricted = !field_is_full(c->dow, 0, 6); | ||
| 727 | + | ||
| 728 | + c->valid = 1; | ||
| 729 | + cron_describe(c, c->desc, sizeof(c->desc)); | ||
| 730 | + return 1; | ||
| 731 | +} | ||
| 732 | + | ||
| 733 | +/* Day-of-week for a broken-down UTC time; 0 == Sunday. */ | ||
| 734 | +static int tm_dow(const struct tm *t) | ||
| 735 | +{ | ||
| 736 | + return t->tm_wday; | ||
| 737 | +} | ||
| 738 | + | ||
| 739 | +static int day_matches(const cron_t *c, const struct tm *day) | ||
| 740 | +{ | ||
| 741 | + int dom_ok = c->dom[day->tm_mday] ? 1 : 0; | ||
| 742 | + int dow_ok = c->dow[tm_dow(day)] ? 1 : 0; | ||
| 743 | + | ||
| 744 | + if (!c->mon[day->tm_mon + 1]) return 0; | ||
| 745 | + if (c->dom_restricted && c->dow_restricted) return dom_ok || dow_ok; | ||
| 746 | + if (c->dom_restricted) return dom_ok; | ||
| 747 | + if (c->dow_restricted) return dow_ok; | ||
| 748 | + return 1; | ||
| 749 | +} | ||
| 750 | + | ||
| 751 | +/* | ||
| 752 | + * Compute the next `want` firing times strictly after `from` (UTC). | ||
| 753 | + * Iterates day by day, then within matching days iterates hours and minutes | ||
| 754 | + * using the parsed bitmaps. Returns the number of timestamps written. | ||
| 755 | + */ | ||
| 756 | +static int cron_next_runs(const cron_t *c, time_t from, time_t *out, int want) | ||
| 757 | +{ | ||
| 758 | + struct tm base; | ||
| 759 | + int got = 0; | ||
| 760 | + int d; | ||
| 761 | + | ||
| 762 | + if (!c->valid || c->boot_only) return 0; | ||
| 763 | + | ||
| 764 | + { | ||
| 765 | + time_t t = from; | ||
| 766 | +#if defined(_WIN32) | ||
| 767 | + gmtime_s(&base, &t); | ||
| 768 | +#else | ||
| 769 | + gmtime_r(&t, &base); | ||
| 770 | +#endif | ||
| 771 | + } | ||
| 772 | + | ||
| 773 | + for (d = 0; d < HORIZON_DAYS && got < want; d++) { | ||
| 774 | + struct tm day; | ||
| 775 | + time_t day_start; | ||
| 776 | + int h, m; | ||
| 777 | + | ||
| 778 | + day = base; | ||
| 779 | + day.tm_mday += d; | ||
| 780 | + day.tm_hour = 0; | ||
| 781 | + day.tm_min = 0; | ||
| 782 | + day.tm_sec = 0; | ||
| 783 | + day.tm_isdst = 0; | ||
| 784 | + day_start = timegm_portable(&day); | ||
| 785 | + if (day_start == (time_t)-1) continue; | ||
| 786 | +#if defined(_WIN32) | ||
| 787 | + gmtime_s(&day, &day_start); | ||
| 788 | +#else | ||
| 789 | + gmtime_r(&day_start, &day); | ||
| 790 | +#endif | ||
| 791 | + if (!day_matches(c, &day)) continue; | ||
| 792 | + | ||
| 793 | + for (h = 0; h < 24 && got < want; h++) { | ||
| 794 | + if (!c->hour[h]) continue; | ||
| 795 | + for (m = 0; m < 60 && got < want; m++) { | ||
| 796 | + time_t cand; | ||
| 797 | + if (!c->min[m]) continue; | ||
| 798 | + cand = day_start + (time_t)h * 3600 + (time_t)m * 60; | ||
| 799 | + if (cand <= from) continue; | ||
| 800 | + out[got++] = cand; | ||
| 801 | + } | ||
| 802 | + } | ||
| 803 | + } | ||
| 804 | + return got; | ||
| 805 | +} | ||
| 806 | +/* ---------------------------------------------------------------- */ | ||
| 807 | +/* Job collection */ | ||
| 808 | +/* ---------------------------------------------------------------- */ | ||
| 809 | + | ||
| 810 | +typedef struct { | ||
| 811 | + char source[MAX_SRC]; | ||
| 812 | + char expr[MAX_EXPR]; | ||
| 813 | + char command[MAX_CMD]; | ||
| 814 | + char user[64]; | ||
| 815 | + char kind[12]; /* "cron" or "task" */ | ||
| 816 | + int valid; | ||
| 817 | + char error[96]; | ||
| 818 | + char desc[MAX_DESC]; | ||
| 819 | + int next_count; | ||
| 820 | + time_t next[MAX_RUNS]; | ||
| 821 | +} job_t; | ||
| 822 | + | ||
| 823 | +static job_t g_jobs[MAX_JOBS]; | ||
| 824 | +static int g_job_count; | ||
| 825 | +static char g_sources[16][MAX_SRC]; | ||
| 826 | +static int g_source_count; | ||
| 827 | +static int g_truncated; | ||
| 828 | + | ||
| 829 | +static void note_source(const char *name) | ||
| 830 | +{ | ||
| 831 | + int i; | ||
| 832 | + if (!name || !*name) return; | ||
| 833 | + for (i = 0; i < g_source_count; i++) | ||
| 834 | + if (strcmp(g_sources[i], name) == 0) return; | ||
| 835 | + if (g_source_count < (int)(sizeof(g_sources) / sizeof(g_sources[0]))) | ||
| 836 | + str_copy(g_sources[g_source_count++], MAX_SRC, name); | ||
| 837 | +} | ||
| 838 | + | ||
| 839 | +static job_t *job_new(void) | ||
| 840 | +{ | ||
| 841 | + job_t *j; | ||
| 842 | + if (g_job_count >= MAX_JOBS) { g_truncated = 1; return NULL; } | ||
| 843 | + j = &g_jobs[g_job_count++]; | ||
| 844 | + memset(j, 0, sizeof(*j)); | ||
| 845 | + return j; | ||
| 846 | +} | ||
| 847 | + | ||
| 848 | +/* Skip blank lines, comments and environment assignments. */ | ||
| 849 | +static int cron_line_skippable(const char *s) | ||
| 850 | +{ | ||
| 851 | + const char *p; | ||
| 852 | + | ||
| 853 | + if (!s) return 1; | ||
| 854 | + while (*s && isspace((unsigned char)*s)) s++; | ||
| 855 | + if (!*s) return 1; | ||
| 856 | + if (*s == '#') return 1; | ||
| 857 | + /* NAME = value (no whitespace inside the name) */ | ||
| 858 | + for (p = s; *p && (isalnum((unsigned char)*p) || *p == '_'); p++) ; | ||
| 859 | + if (p > s && *p == '=') return 1; | ||
| 860 | + return 0; | ||
| 861 | +} | ||
| 862 | + | ||
| 863 | +/* | ||
| 864 | + * Split one crontab line into an expression and a command. | ||
| 865 | + * system format: 5 fields, user, command (/etc/crontab, /etc/cron.d entries) | ||
| 866 | + * user format: 5 fields, command (crontab -l) | ||
| 867 | + * Returns 1 on success. | ||
| 868 | + */ | ||
| 869 | +static int split_cron_line(const char *line, int system_format, | ||
| 870 | + char *expr, size_t expr_sz, | ||
| 871 | + char *user, size_t user_sz, | ||
| 872 | + char *cmd, size_t cmd_sz) | ||
| 873 | +{ | ||
| 874 | + char work[READ_LINE]; | ||
| 875 | + char *p; | ||
| 876 | + int fields_needed = system_format ? 6 : 5; | ||
| 877 | + int got = 0; | ||
| 878 | + | ||
| 879 | + expr[0] = user[0] = cmd[0] = '\0'; | ||
| 880 | + str_copy(work, sizeof(work), line); | ||
| 881 | + str_trim(work); | ||
| 882 | + if (!work[0]) return 0; | ||
| 883 | + | ||
| 884 | + /* @keyword form */ | ||
| 885 | + if (work[0] == '@') { | ||
| 886 | + p = work; | ||
| 887 | + while (*p && !isspace((unsigned char)*p)) p++; | ||
| 888 | + str_copy(expr, expr_sz, work); | ||
| 889 | + expr[strlen(work) - strlen(p) >= expr_sz ? expr_sz - 1 : strlen(work) - strlen(p)] = '\0'; | ||
| 890 | + if (*p) { | ||
| 891 | + char *rest = p; | ||
| 892 | + while (*rest && isspace((unsigned char)*rest)) rest++; | ||
| 893 | + if (system_format) { | ||
| 894 | + char *u = rest; | ||
| 895 | + while (*u && !isspace((unsigned char)*u)) u++; | ||
| 896 | + str_copy(user, user_sz, rest); | ||
| 897 | + user[strlen(rest) - strlen(u) >= user_sz ? user_sz - 1 : strlen(rest) - strlen(u)] = '\0'; | ||
| 898 | + while (*u && isspace((unsigned char)*u)) u++; | ||
| 899 | + str_copy(cmd, cmd_sz, u); | ||
| 900 | + } else { | ||
| 901 | + str_copy(cmd, cmd_sz, rest); | ||
| 902 | + } | ||
| 903 | + } | ||
| 904 | + return 1; | ||
| 905 | + } | ||
| 906 | + | ||
| 907 | + p = work; | ||
| 908 | + while (*p && got < fields_needed) { | ||
| 909 | + char *start; | ||
| 910 | + while (*p && isspace((unsigned char)*p)) p++; | ||
| 911 | + if (!*p) break; | ||
| 912 | + start = p; | ||
| 913 | + while (*p && !isspace((unsigned char)*p)) p++; | ||
| 914 | + if (got < 5) { | ||
| 915 | + size_t len = (size_t)(p - start); | ||
| 916 | + size_t have = strlen(expr); | ||
| 917 | + if (have + len + 2 < expr_sz) { | ||
| 918 | + if (have) expr[have++] = ' '; | ||
| 919 | + memcpy(expr + have, start, len); | ||
| 920 | + expr[have + len] = '\0'; | ||
| 921 | + } | ||
| 922 | + } else { | ||
| 923 | + size_t len = (size_t)(p - start); | ||
| 924 | + if (len >= user_sz) len = user_sz - 1; | ||
| 925 | + memcpy(user, start, len); | ||
| 926 | + user[len] = '\0'; | ||
| 927 | + } | ||
| 928 | + got++; | ||
| 929 | + } | ||
| 930 | + if (got < fields_needed) return 0; | ||
| 931 | + while (*p && isspace((unsigned char)*p)) p++; | ||
| 932 | + str_copy(cmd, cmd_sz, p); | ||
| 933 | + return 1; | ||
| 934 | +} | ||
| 935 | + | ||
| 936 | +static void add_cron_job(const char *source, const char *line, int system_format, time_t now) | ||
| 937 | +{ | ||
| 938 | + char expr[MAX_EXPR], user[64], cmd[MAX_CMD]; | ||
| 939 | + job_t *j; | ||
| 940 | + | ||
| 941 | + if (!split_cron_line(line, system_format, expr, sizeof(expr), | ||
| 942 | + user, sizeof(user), cmd, sizeof(cmd))) | ||
| 943 | + return; | ||
| 944 | + if (!expr[0]) return; | ||
| 945 | + | ||
| 946 | + j = job_new(); | ||
| 947 | + if (!j) return; | ||
| 948 | + | ||
| 949 | + str_copy(j->source, sizeof(j->source), source); | ||
| 950 | + str_copy(j->expr, sizeof(j->expr), expr); | ||
| 951 | + str_copy(j->command, sizeof(j->command), cmd); | ||
| 952 | + str_copy(j->user, sizeof(j->user), user); | ||
| 953 | + str_copy(j->kind, sizeof(j->kind), "cron"); | ||
| 954 | + | ||
| 955 | + { | ||
| 956 | + cron_t c; | ||
| 957 | + if (cron_parse(&c, expr)) { | ||
| 958 | + j->valid = 1; | ||
| 959 | + str_copy(j->desc, sizeof(j->desc), c.desc); | ||
| 960 | + if (c.boot_only) | ||
| 961 | + str_copy(j->desc, sizeof(j->desc), "When the system starts (no scheduled times)"); | ||
| 962 | + else | ||
| 963 | + j->next_count = cron_next_runs(&c, now, j->next, MAX_RUNS); | ||
| 964 | + } else { | ||
| 965 | + j->valid = 0; | ||
| 966 | + str_copy(j->error, sizeof(j->error), c.error); | ||
| 967 | + str_copy(j->desc, sizeof(j->desc), "Unrecognised schedule expression"); | ||
| 968 | + } | ||
| 969 | + } | ||
| 970 | + note_source(source); | ||
| 971 | +} | ||
| 972 | + | ||
| 973 | +#if defined(_WIN32) | ||
| 974 | +static void add_task_job(const char *name, const char *nextrun, const char *status, time_t now) | ||
| 975 | +{ | ||
| 976 | + job_t *j = job_new(); | ||
| 977 | + (void)now; | ||
| 978 | + if (!j) return; | ||
| 979 | + | ||
| 980 | + str_copy(j->source, sizeof(j->source), "schtasks"); | ||
| 981 | + str_copy(j->kind, sizeof(j->kind), "task"); | ||
| 982 | + str_copy(j->expr, sizeof(j->expr), "task"); | ||
| 983 | + str_copy(j->command, sizeof(j->command), name); | ||
| 984 | + str_copy(j->user, sizeof(j->user), ""); | ||
| 985 | + j->valid = 1; | ||
| 986 | + { | ||
| 987 | + char d[MAX_DESC]; | ||
| 988 | + snprintf(d, sizeof(d), "%s%s%s", | ||
| 989 | + status && *status ? status : "Scheduled Windows task", | ||
| 990 | + nextrun && *nextrun && strcmp(nextrun, "N/A") != 0 ? " - next " : "", | ||
| 991 | + nextrun && *nextrun && strcmp(nextrun, "N/A") != 0 ? nextrun : ""); | ||
| 992 | + str_copy(j->desc, sizeof(j->desc), d); | ||
| 993 | + } | ||
| 994 | + note_source("schtasks"); | ||
| 995 | +} | ||
| 996 | + | ||
| 997 | +#endif | ||
| 998 | + | ||
| 999 | +/* Feed a whole file (or popen stream) of crontab lines. */ | ||
| 1000 | +static void ingest_lines(FILE *fp, const char *source, int system_format, time_t now) | ||
| 1001 | +{ | ||
| 1002 | + char line[READ_LINE]; | ||
| 1003 | + int forced = system_format; | ||
| 1004 | + | ||
| 1005 | + while (fp && fgets(line, sizeof(line), fp)) { | ||
| 1006 | + char probe[READ_LINE]; | ||
| 1007 | + size_t n = strlen(line); | ||
| 1008 | + while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = '\0'; | ||
| 1009 | + str_copy(probe, sizeof(probe), line); | ||
| 1010 | + str_trim(probe); | ||
| 1011 | + | ||
| 1012 | + /* fixture directives: "# sx:system" / "# sx:user" / "# sx:source NAME" */ | ||
| 1013 | + if (strncmp(probe, "# sx:", 5) == 0) { | ||
| 1014 | + const char *d = probe + 5; | ||
| 1015 | + if (strncmp(d, "system", 6) == 0) { forced = 1; continue; } | ||
| 1016 | + if (strncmp(d, "user", 4) == 0) { forced = 0; continue; } | ||
| 1017 | + continue; | ||
| 1018 | + } | ||
| 1019 | + if (cron_line_skippable(line)) continue; | ||
| 1020 | + add_cron_job(source, line, forced, now); | ||
| 1021 | + } | ||
| 1022 | +} | ||
| 1023 | + | ||
| 1024 | +static void ingest_file(const char *path, const char *source, int system_format, time_t now) | ||
| 1025 | +{ | ||
| 1026 | + FILE *fp = fopen(path, "r"); | ||
| 1027 | + if (!fp) return; | ||
| 1028 | + ingest_lines(fp, source, system_format, now); | ||
| 1029 | + fclose(fp); | ||
| 1030 | +} | ||
| 1031 | + | ||
| 1032 | +#if !defined(_WIN32) | ||
| 1033 | +static void ingest_command(const char *cmd, const char *source, time_t now) | ||
| 1034 | +{ | ||
| 1035 | + FILE *fp = sx_popen(cmd, "r"); | ||
| 1036 | + if (!fp) return; | ||
| 1037 | + ingest_lines(fp, source, 0, now); | ||
| 1038 | + sx_pclose(fp); | ||
| 1039 | +} | ||
| 1040 | +#endif | ||
| 1041 | + | ||
| 1042 | +#if defined(_WIN32) | ||
| 1043 | +/* Minimal CSV field splitter for `schtasks /Query /FO CSV`. */ | ||
| 1044 | +static void ingest_schtasks(time_t now) | ||
| 1045 | +{ | ||
| 1046 | + FILE *fp = sx_popen("schtasks /Query /FO CSV /NH", "r"); | ||
| 1047 | + char line[READ_LINE]; | ||
| 1048 | + | ||
| 1049 | + if (!fp) return; | ||
| 1050 | + while (fgets(line, sizeof(line), fp)) { | ||
| 1051 | + char f[4][256]; | ||
| 1052 | + int nf = 0; | ||
| 1053 | + char *p = line; | ||
| 1054 | + size_t n = strlen(line); | ||
| 1055 | + while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = '\0'; | ||
| 1056 | + | ||
| 1057 | + while (*p && nf < 4) { | ||
| 1058 | + char *out = f[nf]; | ||
| 1059 | + size_t oi = 0; | ||
| 1060 | + if (*p == '"') { | ||
| 1061 | + p++; | ||
| 1062 | + while (*p && *p != '"' && oi + 1 < 256) { | ||
| 1063 | + if (*p == '"' && p[1] == '"') { out[oi++] = '"'; p += 2; continue; } | ||
| 1064 | + out[oi++] = *p++; | ||
| 1065 | + } | ||
| 1066 | + if (*p == '"') p++; | ||
| 1067 | + } else { | ||
| 1068 | + while (*p && *p != ',' && oi + 1 < 256) out[oi++] = *p++; | ||
| 1069 | + } | ||
| 1070 | + out[oi] = '\0'; | ||
| 1071 | + nf++; | ||
| 1072 | + if (*p == ',') p++; | ||
| 1073 | + } | ||
| 1074 | + if (nf >= 2 && f[0][0] && strcmp(f[0], "TaskName") != 0) | ||
| 1075 | + add_task_job(f[0], f[1], nf > 2 ? f[2] : "", now); | ||
| 1076 | + } | ||
| 1077 | + sx_pclose(fp); | ||
| 1078 | +} | ||
| 1079 | +#endif | ||
| 1080 | + | ||
| 1081 | +static void collect_jobs(void) | ||
| 1082 | +{ | ||
| 1083 | + time_t now = time(NULL); | ||
| 1084 | + const char *fixture = getenv("CRONTAB_FILE"); | ||
| 1085 | + | ||
| 1086 | + g_job_count = 0; | ||
| 1087 | + g_source_count = 0; | ||
| 1088 | + g_truncated = 0; | ||
| 1089 | + | ||
| 1090 | + if (fixture && *fixture) { | ||
| 1091 | + ingest_file(fixture, "fixture", 0, now); | ||
| 1092 | + return; | ||
| 1093 | + } | ||
| 1094 | + | ||
| 1095 | +#if defined(_WIN32) | ||
| 1096 | + ingest_schtasks(now); | ||
| 1097 | +#else | ||
| 1098 | + ingest_command("crontab -l 2>/dev/null", "user", now); | ||
| 1099 | + ingest_file("/etc/crontab", "/etc/crontab", 1, now); | ||
| 1100 | + { | ||
| 1101 | + DIR *d = opendir("/etc/cron.d"); | ||
| 1102 | + struct dirent *ent; | ||
| 1103 | + if (d) { | ||
| 1104 | + while ((ent = readdir(d)) != NULL) { | ||
| 1105 | + char path[512]; | ||
| 1106 | + char label[MAX_SRC]; | ||
| 1107 | + if (ent->d_name[0] == '.') continue; | ||
| 1108 | + snprintf(path, sizeof(path), "/etc/cron.d/%s", ent->d_name); | ||
| 1109 | + snprintf(label, sizeof(label), "/etc/cron.d/%.40s", ent->d_name); | ||
| 1110 | + ingest_file(path, label, 1, now); | ||
| 1111 | + } | ||
| 1112 | + closedir(d); | ||
| 1113 | + } | ||
| 1114 | + } | ||
| 1115 | +#endif | ||
| 1116 | +} | ||
| 1117 | +/* ---------------------------------------------------------------- */ | ||
| 1118 | +/* HTTP plumbing */ | ||
| 1119 | +/* ---------------------------------------------------------------- */ | ||
| 1120 | + | ||
| 1121 | +static void json_header(void) | ||
| 1122 | +{ | ||
| 1123 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 1124 | + "Cache-Control: no-store\r\n" | ||
| 1125 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1126 | +} | ||
| 1127 | + | ||
| 1128 | +static void print_runs(const time_t *runs, int count, time_t now) | ||
| 1129 | +{ | ||
| 1130 | + int i; | ||
| 1131 | + char utc[40], loc[40]; | ||
| 1132 | + | ||
| 1133 | + putchar('['); | ||
| 1134 | + for (i = 0; i < count; i++) { | ||
| 1135 | + utc_stamp(runs[i], utc, sizeof(utc)); | ||
| 1136 | + local_stamp(runs[i], loc, sizeof(loc)); | ||
| 1137 | + if (i) putchar(','); | ||
| 1138 | + fputs("{\"utc\":", stdout); | ||
| 1139 | + json_str(utc); | ||
| 1140 | + fputs(",\"local\":", stdout); | ||
| 1141 | + json_str(loc); | ||
| 1142 | + printf(",\"in_seconds\":%ld}", (long)(runs[i] - now)); | ||
| 1143 | + } | ||
| 1144 | + putchar(']'); | ||
| 1145 | +} | ||
| 1146 | + | ||
| 1147 | +static int mode_meta(void) | ||
| 1148 | +{ | ||
| 1149 | + fputs("{\"name\":\"crontab\",\"desc\":\"Cron jobs\"}\n", stdout); | ||
| 1150 | + return 0; | ||
| 1151 | +} | ||
| 1152 | + | ||
| 1153 | +/* Field text for a keyword schedule, for the JSON fields block. */ | ||
| 1154 | +static void cron_keyword_fields(const cron_t *c, char kf[5][12]) | ||
| 1155 | +{ | ||
| 1156 | + if (!c->keyword[0]) { | ||
| 1157 | + int i; | ||
| 1158 | + for (i = 0; i < 5; i++) str_copy(kf[i], 12, c->f[i]); | ||
| 1159 | + return; | ||
| 1160 | + } | ||
| 1161 | + str_copy(kf[0], 12, "0"); | ||
| 1162 | + str_copy(kf[1], 12, "0"); | ||
| 1163 | + str_copy(kf[2], 12, "*"); | ||
| 1164 | + str_copy(kf[3], 12, "*"); | ||
| 1165 | + str_copy(kf[4], 12, "*"); | ||
| 1166 | + if (strcmp(c->keyword, "@reboot") == 0) { | ||
| 1167 | + int i; | ||
| 1168 | + for (i = 0; i < 5; i++) str_copy(kf[i], 12, "@reboot"); | ||
| 1169 | + } else if (strcmp(c->keyword, "@hourly") == 0) { | ||
| 1170 | + str_copy(kf[1], 12, "*"); | ||
| 1171 | + } else if (strcmp(c->keyword, "@weekly") == 0) { | ||
| 1172 | + str_copy(kf[4], 12, "0"); | ||
| 1173 | + } else if (strcmp(c->keyword, "@monthly") == 0) { | ||
| 1174 | + str_copy(kf[2], 12, "1"); | ||
| 1175 | + } else if (strcmp(c->keyword, "@yearly") == 0 || strcmp(c->keyword, "@annually") == 0) { | ||
| 1176 | + str_copy(kf[2], 12, "1"); | ||
| 1177 | + str_copy(kf[3], 12, "1"); | ||
| 1178 | + } | ||
| 1179 | +} | ||
| 1180 | + | ||
| 1181 | +static int mode_json(const char *qs) | ||
| 1182 | +{ | ||
| 1183 | + char action[64]; | ||
| 1184 | + char expr[MAX_EXPR * 2]; | ||
| 1185 | + time_t now = time(NULL); | ||
| 1186 | + | ||
| 1187 | + action[0] = '\0'; | ||
| 1188 | + get_query_val(qs, "action", action, sizeof(action)); | ||
| 1189 | + | ||
| 1190 | + json_header(); | ||
| 1191 | + | ||
| 1192 | + if (strcmp(action, "explain") == 0) { | ||
| 1193 | + cron_t c; | ||
| 1194 | + time_t runs[MAX_RUNS]; | ||
| 1195 | + int n = 0; | ||
| 1196 | + char nowutc[40]; | ||
| 1197 | + char nowloc[40]; | ||
| 1198 | + | ||
| 1199 | + get_query_val(qs, "expr", expr, sizeof(expr)); | ||
| 1200 | + utc_stamp(now, nowutc, sizeof(nowutc)); | ||
| 1201 | + local_stamp(now, nowloc, sizeof(nowloc)); | ||
| 1202 | + | ||
| 1203 | + if (!expr[0]) { | ||
| 1204 | + fputs("{\"ok\":false,\"error\":\"missing expr parameter\",\"valid\":false}\n", stdout); | ||
| 1205 | + return 0; | ||
| 1206 | + } | ||
| 1207 | + | ||
| 1208 | + if (cron_parse(&c, expr)) { | ||
| 1209 | + if (!c.boot_only) n = cron_next_runs(&c, now, runs, MAX_RUNS); | ||
| 1210 | + } else { | ||
| 1211 | + fputs("{\"ok\":true,\"action\":\"explain\",\"expr\":", stdout); | ||
| 1212 | + json_str(expr); | ||
| 1213 | + fputs(",\"valid\":false,\"error\":", stdout); | ||
| 1214 | + json_str(c.error[0] ? c.error : "invalid expression"); | ||
| 1215 | + fputs(",\"description\":\"\",\"keyword\":\"\",\"next\":[]," | ||
| 1216 | + "\"now_utc\":", stdout); | ||
| 1217 | + json_str(nowutc); | ||
| 1218 | + fputs(",\"now_local\":", stdout); | ||
| 1219 | + json_str(nowloc); | ||
| 1220 | + fputs("}\n", stdout); | ||
| 1221 | + return 0; | ||
| 1222 | + } | ||
| 1223 | + | ||
| 1224 | + fputs("{\"ok\":true,\"action\":\"explain\",\"expr\":", stdout); | ||
| 1225 | + json_str(expr); | ||
| 1226 | + fputs(",\"valid\":true,\"keyword\":", stdout); | ||
| 1227 | + json_str(c.keyword); | ||
| 1228 | + fputs(",\"description\":", stdout); | ||
| 1229 | + json_str(c.desc); | ||
| 1230 | + fputs(",\"normalized\":", stdout); | ||
| 1231 | + if (c.keyword[0]) { | ||
| 1232 | + json_str(c.keyword); | ||
| 1233 | + } else { | ||
| 1234 | + char norm[220]; | ||
| 1235 | + snprintf(norm, sizeof(norm), "%s %s %s %s %s", | ||
| 1236 | + c.f[0], c.f[1], c.f[2], c.f[3], c.f[4]); | ||
| 1237 | + json_str(norm); | ||
| 1238 | + } | ||
| 1239 | + { | ||
| 1240 | + char kf[5][12]; | ||
| 1241 | + cron_keyword_fields(&c, kf); | ||
| 1242 | + fputs(",\"fields\":{\"minute\":", stdout); json_str(kf[0]); | ||
| 1243 | + fputs(",\"hour\":", stdout); json_str(kf[1]); | ||
| 1244 | + fputs(",\"day_of_month\":", stdout); json_str(kf[2]); | ||
| 1245 | + fputs(",\"month\":", stdout); json_str(kf[3]); | ||
| 1246 | + fputs(",\"day_of_week\":", stdout); json_str(kf[4]); | ||
| 1247 | + } | ||
| 1248 | + fputs("},\"boot_only\":", stdout); fputs(c.boot_only ? "true" : "false", stdout); | ||
| 1249 | + fputs(",\"now_utc\":", stdout); json_str(nowutc); | ||
| 1250 | + fputs(",\"now_local\":", stdout); json_str(nowloc); | ||
| 1251 | + fputs(",\"next\":", stdout); | ||
| 1252 | + print_runs(runs, n, now); | ||
| 1253 | + putchar('}'); | ||
| 1254 | + putchar('\n'); | ||
| 1255 | + return 0; | ||
| 1256 | + } | ||
| 1257 | + | ||
| 1258 | + if (strcmp(action, "jobs") == 0 || strcmp(action, "list") == 0 || !action[0]) { | ||
| 1259 | + char nowutc[40], nowloc[40]; | ||
| 1260 | + int i; | ||
| 1261 | + | ||
| 1262 | + collect_jobs(); | ||
| 1263 | + utc_stamp(now, nowutc, sizeof(nowutc)); | ||
| 1264 | + local_stamp(now, nowloc, sizeof(nowloc)); | ||
| 1265 | + | ||
| 1266 | + fputs("{\"ok\":true,\"action\":\"jobs\",\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\"", stdout); | ||
| 1267 | + fputs(",\"now_utc\":", stdout); json_str(nowutc); | ||
| 1268 | + fputs(",\"now_local\":", stdout); json_str(nowloc); | ||
| 1269 | + printf(",\"count\":%d,\"truncated\":%s", g_job_count, g_truncated ? "true" : "false"); | ||
| 1270 | + fputs(",\"sources\":[", stdout); | ||
| 1271 | + for (i = 0; i < g_source_count; i++) { | ||
| 1272 | + if (i) putchar(','); | ||
| 1273 | + json_str(g_sources[i]); | ||
| 1274 | + } | ||
| 1275 | + fputs("],\"jobs\":[", stdout); | ||
| 1276 | + for (i = 0; i < g_job_count; i++) { | ||
| 1277 | + const job_t *j = &g_jobs[i]; | ||
| 1278 | + if (i) putchar(','); | ||
| 1279 | + fputs("{\"source\":", stdout); json_str(j->source); | ||
| 1280 | + fputs(",\"kind\":", stdout); json_str(j->kind); | ||
| 1281 | + fputs(",\"expr\":", stdout); json_str(j->expr); | ||
| 1282 | + fputs(",\"command\":", stdout); json_str(j->command); | ||
| 1283 | + fputs(",\"user\":", stdout); json_str(j->user); | ||
| 1284 | + printf(",\"valid\":%s", j->valid ? "true" : "false"); | ||
| 1285 | + if (!j->valid) { | ||
| 1286 | + fputs(",\"error\":", stdout); | ||
| 1287 | + json_str(j->error); | ||
| 1288 | + } | ||
| 1289 | + fputs(",\"description\":", stdout); | ||
| 1290 | + json_str(j->desc); | ||
| 1291 | + fputs(",\"next\":", stdout); | ||
| 1292 | + print_runs(j->next, j->next_count, now); | ||
| 1293 | + putchar('}'); | ||
| 1294 | + } | ||
| 1295 | + fputs("]}\n", stdout); | ||
| 1296 | + return 0; | ||
| 1297 | + } | ||
| 1298 | + | ||
| 1299 | + if (strcmp(action, "info") == 0) { | ||
| 1300 | + fputs("{\"ok\":true,\"action\":\"info\",\"plugin\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\"" | ||
| 1301 | + ",\"slug\":\"" PLUGIN_SLUG "\",\"license\":\"MIT\",\"read_only\":true" | ||
| 1302 | + ",\"actions\":[\"jobs\",\"explain\",\"info\"]" | ||
| 1303 | + ",\"capabilities\":[\"crontab_read\",\"cron_parse\"]" | ||
| 1304 | + ",\"trust_notice\":\"Executes native C code on your node. Reads crontab listings and task lists; never writes a schedule and never runs a scheduled command. Makes zero outbound network requests.\"}\n", | ||
| 1305 | + stdout); | ||
| 1306 | + return 0; | ||
| 1307 | + } | ||
| 1308 | + | ||
| 1309 | + fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout); | ||
| 1310 | + return 0; | ||
| 1311 | +} | ||
| 1312 | + | ||
| 1313 | +static void require_node_auth(void) | ||
| 1314 | +{ | ||
| 1315 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 1316 | + const char *xp; | ||
| 1317 | + const char *auth; | ||
| 1318 | + const char *qs; | ||
| 1319 | + char qpwd[256]; | ||
| 1320 | + | ||
| 1321 | + if (!np || !*np) return; | ||
| 1322 | + | ||
| 1323 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 1324 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 1325 | + | ||
| 1326 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 1327 | + if (auth) { | ||
| 1328 | + while (*auth == ' ') auth++; | ||
| 1329 | + if (strncmp(auth, "Bearer ", 7) == 0) { | ||
| 1330 | + auth += 7; | ||
| 1331 | + while (*auth == ' ') auth++; | ||
| 1332 | + if (strcmp(auth, np) == 0) return; | ||
| 1333 | + } | ||
| 1334 | + } | ||
| 1335 | + | ||
| 1336 | + qs = getenv("QUERY_STRING"); | ||
| 1337 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0) | ||
| 1338 | + return; | ||
| 1339 | + | ||
| 1340 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 1341 | + "Content-Type: application/json; charset=utf-8\r\n" | ||
| 1342 | + "Cache-Control: no-store\r\n" | ||
| 1343 | + "X-Content-Type-Options: nosniff\r\n\r\n" | ||
| 1344 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 1345 | + exit(0); | ||
| 1346 | +} | ||
| 1347 | +/* ---------------------------------------------------------------- */ | ||
| 1348 | +/* HTML UI */ | ||
| 1349 | +/* ---------------------------------------------------------------- */ | ||
| 1350 | + | ||
| 1351 | +static void html_head(int embed) | ||
| 1352 | +{ | ||
| 1353 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 1354 | + "Cache-Control: no-store\r\n" | ||
| 1355 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1356 | + | ||
| 1357 | + fputs("<!DOCTYPE html>\n<html lang='en' data-theme='dark'><head><meta charset='utf-8'>" | ||
| 1358 | + "<meta name='viewport' content='width=device-width,initial-scale=1'>" | ||
| 1359 | + "<title>crontab</title><style>", stdout); | ||
| 1360 | + | ||
| 1361 | + fputs( | ||
| 1362 | +":root{--bg:#0d0d10;--surface:#16161a;--surface2:#1e1e24;--text:#f5f5f7;" | ||
| 1363 | +"--muted:#8e8e96;--line:rgba(255,255,255,.11);--accent:#0a84ff;--accent2:#30d158;" | ||
| 1364 | +"--warn:#ffd60a;--danger:#ff453a;--mono:ui-monospace,SFMono-Regular,Menlo,monospace}" | ||
| 1365 | +"html[data-theme=light]{--bg:#f4f4f7;--surface:#ffffff;--surface2:#f0f0f4;" | ||
| 1366 | +"--text:#1c1c1e;--muted:#6b6b73;--line:rgba(0,0,0,.10)}" | ||
| 1367 | +"*{box-sizing:border-box}" | ||
| 1368 | +"body{margin:0;padding:16px;background:var(--bg);color:var(--text);" | ||
| 1369 | +"font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:14px;" | ||
| 1370 | +"line-height:1.5;-webkit-font-smoothing:antialiased}" | ||
| 1371 | +".wrap{max-width:1120px;margin:0 auto}" | ||
| 1372 | +".top{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap}" | ||
| 1373 | +".title{font-size:20px;font-weight:700;margin:0}" | ||
| 1374 | +".pill{font-size:11px;font-weight:600;padding:2px 8px;border-radius:999px;" | ||
| 1375 | +"background:var(--surface2);color:var(--muted);border:1px solid var(--line);white-space:nowrap}" | ||
| 1376 | +".pill.on{color:var(--accent2);border-color:rgba(48,209,88,.4)}" | ||
| 1377 | +".pill.off{color:var(--danger);border-color:rgba(255,69,58,.4)}" | ||
| 1378 | +".spacer{flex:1}" | ||
| 1379 | +".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;" | ||
| 1380 | +"padding:16px;margin-bottom:14px}" | ||
| 1381 | +".card h2{margin:0 0 10px;font-size:12px;letter-spacing:.06em;text-transform:uppercase;" | ||
| 1382 | +"color:var(--muted);font-weight:600}" | ||
| 1383 | +".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:10px}" | ||
| 1384 | +".kpi{background:var(--surface2);border:1px solid var(--line);border-radius:10px;padding:10px 12px}" | ||
| 1385 | +".kpi .k{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}" | ||
| 1386 | +".kpi .v{font-size:20px;font-weight:700;font-family:var(--mono);margin-top:2px}" | ||
| 1387 | +"button{background:var(--accent);color:#fff;border:0;border-radius:999px;padding:7px 14px;" | ||
| 1388 | +"font-weight:600;font-size:13px;cursor:pointer;font-family:inherit}" | ||
| 1389 | +"button.ghost{background:transparent;color:var(--text);border:1px solid var(--line)}" | ||
| 1390 | +"button.sm{padding:4px 10px;font-size:12px}" | ||
| 1391 | +"button:active{transform:scale(.98)}" | ||
| 1392 | +"input{background:var(--surface2);border:1px solid var(--line);border-radius:10px;" | ||
| 1393 | +"padding:9px 12px;color:var(--text);font-size:13px;font-family:var(--mono);width:100%}" | ||
| 1394 | +"input:focus{outline:2px solid var(--accent);outline-offset:-1px}" | ||
| 1395 | +".row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}" | ||
| 1396 | +".tblwrap{overflow-x:auto}" | ||
| 1397 | +"table{width:100%;border-collapse:collapse;font-size:13px;margin-top:10px}" | ||
| 1398 | +"th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:var(--muted);" | ||
| 1399 | +"font-weight:600;padding:6px 8px;border-bottom:1px solid var(--line);white-space:nowrap}" | ||
| 1400 | +"td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:top}" | ||
| 1401 | +"td.mono{font-family:var(--mono);font-size:12px}" | ||
| 1402 | +".cmd{font-family:var(--mono);font-size:12px;color:var(--muted);word-break:break-all;max-width:340px}" | ||
| 1403 | +".src{font-size:11px;color:var(--muted);font-family:var(--mono)}" | ||
| 1404 | +".in{font-size:12px;font-weight:600;color:var(--accent2);font-family:var(--mono);white-space:nowrap}" | ||
| 1405 | +".err{font-size:12px;color:var(--danger)}" | ||
| 1406 | +".muted{color:var(--muted)}" | ||
| 1407 | +".empty{padding:22px 8px;text-align:center;color:var(--muted)}" | ||
| 1408 | +".hide{display:none}" | ||
| 1409 | +".play{display:grid;grid-template-columns:1fr auto;gap:8px;align-items:center}" | ||
| 1410 | +".runs{margin-top:12px;display:grid;gap:6px}" | ||
| 1411 | +".run{display:flex;gap:10px;align-items:baseline;background:var(--surface2);" | ||
| 1412 | +"border:1px solid var(--line);border-radius:10px;padding:8px 12px;font-family:var(--mono);font-size:12px}" | ||
| 1413 | +".run .n{color:var(--muted);width:18px;flex:none}" | ||
| 1414 | +".run .u{font-weight:600}" | ||
| 1415 | +".run .l{color:var(--muted);margin-left:auto}" | ||
| 1416 | +"@media(max-width:640px){body{padding:10px}.card{padding:12px}" | ||
| 1417 | +".play{grid-template-columns:1fr}" | ||
| 1418 | +"th:nth-child(1),td:nth-child(1),th:nth-child(5),td:nth-child(5){display:none}" | ||
| 1419 | +"td{padding:8px 4px}th{padding:6px 4px}.cmd{max-width:none}}" | ||
| 1420 | +"</style></head><body><div class='wrap'>", stdout); | ||
| 1421 | + | ||
| 1422 | + if (!embed) | ||
| 1423 | + fputs("<div class='top'><a href='/' style='color:var(--accent);text-decoration:none;" | ||
| 1424 | + "font-weight:600'>← Back to Bot</a></div>", stdout); | ||
| 1425 | +} | ||
| 1426 | + | ||
| 1427 | +static void html_body(void) | ||
| 1428 | +{ | ||
| 1429 | + fputs("<div class='top'><h1 class='title'>crontab</h1>" | ||
| 1430 | + "<span class='pill'>" PLUGIN_VER "</span>" | ||
| 1431 | + "<span class='pill' id='badge'>loading</span>" | ||
| 1432 | + "<span class='spacer'></span>" | ||
| 1433 | + "<button class='ghost' id='themeBtn' type='button'>Theme</button>" | ||
| 1434 | + "<button class='ghost' id='reloadBtn' type='button'>Refresh</button></div>", | ||
| 1435 | + | ||
| 1436 | + stdout); | ||
| 1437 | + | ||
| 1438 | + /* KPIs */ | ||
| 1439 | + fputs("<div class='card'><h2>Schedule overview</h2><div class='grid'>" | ||
| 1440 | + "<div class='kpi'><div class='k'>jobs</div><div class='v' id='k-total'>—</div></div>" | ||
| 1441 | + "<div class='kpi'><div class='k'>parsed</div><div class='v' id='k-valid'>—</div></div>" | ||
| 1442 | + "<div class='kpi'><div class='k'>next run</div><div class='v' id='k-next'>—</div></div>" | ||
| 1443 | + "<div class='kpi'><div class='k'>sources</div><div class='v' id='k-src'>—</div></div>" | ||
| 1444 | + "</div>" | ||
| 1445 | + "<div class='row' style='margin-top:12px'>" | ||
| 1446 | + "<input id='q' type='text' placeholder='filter by command, source or expression'>" | ||
| 1447 | + "</div>" | ||
| 1448 | + "<div id='note' class='muted' style='margin-top:10px'></div>" | ||
| 1449 | + "<div class='tblwrap'><table><thead><tr>" | ||
| 1450 | + "<th>Source</th><th>Schedule</th><th>Meaning</th><th>Next run</th><th>Command</th>" | ||
| 1451 | + "</tr></thead><tbody id='rows'></tbody></table></div>" | ||
| 1452 | + "<div id='empty' class='empty hide'>No scheduled entries found on this node.</div>" | ||
| 1453 | + "</div>", stdout); | ||
| 1454 | + | ||
| 1455 | + /* playground */ | ||
| 1456 | + fputs("<div class='card'><h2>Cron expression playground</h2>" | ||
| 1457 | + "<div class='play'>" | ||
| 1458 | + "<input id='ex' type='text' value='*/15 9-17 * * 1-5' spellcheck='false' " | ||
| 1459 | + "placeholder='minute hour day-of-month month day-of-week'>" | ||
| 1460 | + "<button id='goBtn' type='button'>Explain</button>" | ||
| 1461 | + "</div>" | ||
| 1462 | + "<div id='exNote' class='muted' style='margin-top:10px'>" | ||
| 1463 | + "Accepts standard five-field expressions and @hourly, @daily, @weekly, " | ||
| 1464 | + "@monthly, @yearly, @reboot.</div>" | ||
| 1465 | + "<div class='runs' id='exRuns'></div></div>", stdout); | ||
| 1466 | + | ||
| 1467 | + fputs("<div class='card'><h2>About this plugin</h2>" | ||
| 1468 | + "<p class='muted' style='margin:0 0 8px'>Local node only. Reads " | ||
| 1469 | + "<code>crontab -l</code>, <code>/etc/crontab</code> and <code>/etc/cron.d</code> " | ||
| 1470 | + "on Linux and macOS, or <code>schtasks</code> on Windows. It is strictly read-only: " | ||
| 1471 | + "no schedule is ever written and no scheduled command is ever executed.</p>" | ||
| 1472 | + "<p class='muted' style='margin:0'>Set <code>CRONTAB_FILE</code> to inspect a fixture " | ||
| 1473 | + "file instead of the live machine. Source is MIT licensed.</p></div>", stdout); | ||
| 1474 | + | ||
| 1475 | + fputs("<script>\n", stdout); | ||
| 1476 | + fputs( | ||
| 1477 | +"(function(){\n" | ||
| 1478 | +" var q = new URLSearchParams(location.search);\n" | ||
| 1479 | +" var node = q.get('node') || '';\n" | ||
| 1480 | +" var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n" | ||
| 1481 | +" localStorage.getItem('bot_active_pwd') || '';\n" | ||
| 1482 | +" function base(){\n" | ||
| 1483 | +" var u = location.pathname;\n" | ||
| 1484 | +" var keep = [];\n" | ||
| 1485 | +" ['node','plugin','id','embed','pwd'].forEach(function(k){\n" | ||
| 1486 | +" var v = q.get(k); if (v) keep.push(k + '=' + encodeURIComponent(v));\n" | ||
| 1487 | +" });\n" | ||
| 1488 | +" return u + (keep.length ? '?' + keep.join('&') : '');\n" | ||
| 1489 | +" }\n" | ||
| 1490 | +" function withCtx(url){\n" | ||
| 1491 | +" if (!node && !pwd) return url;\n" | ||
| 1492 | +" return url + (url.indexOf('?') >= 0 ? '&' : '?') +\n" | ||
| 1493 | +" (node ? 'node=' + encodeURIComponent(node) : '') +\n" | ||
| 1494 | +" (node && pwd ? '&' : '') + (pwd ? 'pwd=' + encodeURIComponent(pwd) : '');\n" | ||
| 1495 | +" }\n" | ||
| 1496 | +" function get(u){\n" | ||
| 1497 | +" return fetch(withCtx(base() + '?' + u), { headers: { 'Accept':'application/json' } })\n" | ||
| 1498 | +" .then(function(r){ return r.json(); });\n" | ||
| 1499 | +" }\n" | ||
| 1500 | +" function $(id){ return document.getElementById(id); }\n" | ||
| 1501 | +" function el(tag, cls, text){\n" | ||
| 1502 | +" var e = document.createElement(tag);\n" | ||
| 1503 | +" if (cls) e.className = cls;\n" | ||
| 1504 | +" if (text !== undefined && text !== null) e.textContent = String(text);\n" | ||
| 1505 | +" return e;\n" | ||
| 1506 | +" }\n" | ||
| 1507 | +" function theme(t){ if (t) document.documentElement.setAttribute('data-theme', t); }\n" | ||
| 1508 | +" if (window.parent && window.parent !== window) {\n" | ||
| 1509 | +" var vm = q.get('theme') || localStorage.getItem('bot_theme');\n" | ||
| 1510 | +" if (vm) theme(vm);\n" | ||
| 1511 | +" } else {\n" | ||
| 1512 | +" theme(localStorage.getItem('bot_theme') ||\n" | ||
| 1513 | +" (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'));\n" | ||
| 1514 | +" }\n" | ||
| 1515 | +" $('themeBtn').addEventListener('click', function(){\n" | ||
| 1516 | +" var next = document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light';\n" | ||
| 1517 | +" theme(next); localStorage.setItem('bot_theme', next);\n" | ||
| 1518 | +" });\n" | ||
| 1519 | +" function badge(ok, text){ var b = $('badge'); b.textContent = text; b.className = 'pill ' + (ok ? 'on' : 'off'); }\n" | ||
| 1520 | +" function human(sec){\n" | ||
| 1521 | +" if (sec === null || sec === undefined) return 'never';\n" | ||
| 1522 | +" if (sec < 0) return 'due';\n" | ||
| 1523 | +" var d = Math.floor(sec / 86400), h = Math.floor(sec % 86400 / 3600),\n" | ||
| 1524 | +" m = Math.floor(sec % 3600 / 60);\n" | ||
| 1525 | +" if (d > 0) return d + 'd ' + h + 'h';\n" | ||
| 1526 | +" if (h > 0) return h + 'h ' + m + 'm';\n" | ||
| 1527 | +" if (m > 0) return m + 'm';\n" | ||
| 1528 | +" return '<1m';\n" | ||
| 1529 | +" }\n" | ||
| 1530 | +" var DATA = { jobs: [] };\n" | ||
| 1531 | +" function matches(j){\n" | ||
| 1532 | +" var k = ($('q').value || '').trim().toLowerCase();\n" | ||
| 1533 | +" if (!k) return true;\n" | ||
| 1534 | +" var hay = ((j.command||'') + ' ' + (j.source||'') + ' ' + (j.expr||'') + ' ' + (j.description||'')).toLowerCase();\n" | ||
| 1535 | +" return hay.indexOf(k) >= 0;\n" | ||
| 1536 | +" }\n" | ||
| 1537 | +" function render(){\n" | ||
| 1538 | +" var tb = $('rows'), shown = 0, soonest = null;\n" | ||
| 1539 | +" while (tb.firstChild) tb.removeChild(tb.firstChild);\n" | ||
| 1540 | +" (DATA.jobs || []).forEach(function(j){\n" | ||
| 1541 | +" if (!matches(j)) return;\n" | ||
| 1542 | +" shown++;\n" | ||
| 1543 | +" var tr = el('tr');\n" | ||
| 1544 | +" tr.appendChild(el('td', 'src', j.source || ''));\n" | ||
| 1545 | +" tr.appendChild(el('td', 'mono', j.expr || ''));\n" | ||
| 1546 | +" var tdDesc = el('td');\n" | ||
| 1547 | +" tdDesc.appendChild(el('div', j.valid ? '' : 'err', j.valid ? (j.description || '') : ('invalid: ' + (j.error || ''))));\n" | ||
| 1548 | +" tr.appendChild(tdDesc);\n" | ||
| 1549 | +" var tdNext = el('td');\n" | ||
| 1550 | +" var n = (j.next && j.next[0]) ? j.next[0] : null;\n" | ||
| 1551 | +" if (n) {\n" | ||
| 1552 | +" tdNext.appendChild(el('div', 'in', human(n.in_seconds)));\n" | ||
| 1553 | +" tdNext.appendChild(el('div', 'src', n.local || ''));\n" | ||
| 1554 | +" if (soonest === null || n.in_seconds < soonest) soonest = n.in_seconds;\n" | ||
| 1555 | +" } else {\n" | ||
| 1556 | +" tdNext.appendChild(el('span', 'muted', '\\u2014'));\n" | ||
| 1557 | +" }\n" | ||
| 1558 | +" tr.appendChild(tdNext);\n" | ||
| 1559 | +" tr.appendChild(el('td', 'cmd', j.command || ''));\n" | ||
| 1560 | +" tb.appendChild(tr);\n" | ||
| 1561 | +" });\n" | ||
| 1562 | +" $('empty').classList.toggle('hide', shown !== 0);\n" | ||
| 1563 | +" $('k-total').textContent = (DATA.jobs || []).length;\n" | ||
| 1564 | +" $('k-valid').textContent = (DATA.jobs || []).filter(function(j){ return j.valid; }).length;\n" | ||
| 1565 | +" $('k-next').textContent = soonest === null ? '\\u2014' : human(soonest);\n" | ||
| 1566 | +" $('k-src').textContent = (DATA.sources || []).length;\n" | ||
| 1567 | +" }\n" | ||
| 1568 | +" function load(){\n" | ||
| 1569 | +" $('note').textContent = 'loading\\u2026';\n" | ||
| 1570 | +" get('action=jobs')\n" | ||
| 1571 | +" .then(function(d){\n" | ||
| 1572 | +" if (!d.ok) { $('note').textContent = d.error || 'failed'; badge(false, 'error'); return; }\n" | ||
| 1573 | +" DATA = d;\n" | ||
| 1574 | +" badge(true, d.count + ' job' + (d.count === 1 ? '' : 's'));\n" | ||
| 1575 | +" $('note').textContent = (d.sources && d.sources.length)\n" | ||
| 1576 | +" ? 'Read from: ' + d.sources.join(', ') + ' (as of ' + d.now_local + ' local)'\n" | ||
| 1577 | +" : 'No crontab sources readable on this node (as of ' + d.now_local + ' local)';\n" | ||
| 1578 | +" render();\n" | ||
| 1579 | +" })\n" | ||
| 1580 | +" .catch(function(e){ $('note').textContent = 'request failed: ' + e; badge(false, 'error'); });\n" | ||
| 1581 | +" }\n" | ||
| 1582 | +" function explain(){\n" | ||
| 1583 | +" var ex = ($('ex').value || '').trim();\n" | ||
| 1584 | +" var box = $('exRuns');\n" | ||
| 1585 | +" while (box.firstChild) box.removeChild(box.firstChild);\n" | ||
| 1586 | +" if (!ex) { $('exNote').textContent = 'Type an expression first.'; return; }\n" | ||
| 1587 | +" $('exNote').textContent = 'checking\\u2026';\n" | ||
| 1588 | +" get('action=explain&expr=' + encodeURIComponent(ex))\n" | ||
| 1589 | +" .then(function(d){\n" | ||
| 1590 | +" if (!d.ok) { $('exNote').textContent = d.error || 'failed'; return; }\n" | ||
| 1591 | +" if (!d.valid) { $('exNote').textContent = 'invalid expression'; return; }\n" | ||
| 1592 | +" $('exNote').textContent = d.description + (d.boot_only\n" | ||
| 1593 | +" ? ' \\u2014 runs at boot, so there are no clock times.'\n" | ||
| 1594 | +" : ' \\u2014 next 5 runs in your local time:');\n" | ||
| 1595 | +" (d.next || []).forEach(function(r, i){\n" | ||
| 1596 | +" var row = el('div', 'run');\n" | ||
| 1597 | +" row.appendChild(el('span', 'n', String(i + 1)));\n" | ||
| 1598 | +" row.appendChild(el('span', 'u', r.utc));\n" | ||
| 1599 | +" row.appendChild(el('span', 'l', r.local + ' local \\u00b7 in ' + human(r.in_seconds)));\n" | ||
| 1600 | +" box.appendChild(row);\n" | ||
| 1601 | +" });\n" | ||
| 1602 | +" })\n" | ||
| 1603 | +" .catch(function(e){ $('exNote').textContent = 'request failed: ' + e; });\n" | ||
| 1604 | +" }\n" | ||
| 1605 | +" $('reloadBtn').addEventListener('click', load);\n" | ||
| 1606 | +" $('goBtn').addEventListener('click', explain);\n" | ||
| 1607 | +" $('ex').addEventListener('keydown', function(e){ if (e.key === 'Enter') explain(); });\n" | ||
| 1608 | +" $('q').addEventListener('input', render);\n" | ||
| 1609 | +" load();\n" | ||
| 1610 | +" explain();\n" | ||
| 1611 | +" setInterval(load, 60000);\n" | ||
| 1612 | +"})();\n" | ||
| 1613 | +"</script></div></body></html>\n", stdout); | ||
| 1614 | +} | ||
| 1615 | + | ||
| 1616 | +static int mode_html(int embed) | ||
| 1617 | +{ | ||
| 1618 | + html_head(embed); | ||
| 1619 | + html_body(); | ||
| 1620 | + return 0; | ||
| 1621 | +} | ||
| 1622 | +/* ---------------------------------------------------------------- */ | ||
| 1623 | +/* main */ | ||
| 1624 | +/* ---------------------------------------------------------------- */ | ||
| 1625 | + | ||
| 1626 | +static int is_post_request(void) | ||
| 1627 | +{ | ||
| 1628 | + const char *m = getenv("REQUEST_METHOD"); | ||
| 1629 | + return m && strcmp(m, "POST") == 0; | ||
| 1630 | +} | ||
| 1631 | + | ||
| 1632 | +int main(int argc, char **argv) | ||
| 1633 | +{ | ||
| 1634 | + const char *qs; | ||
| 1635 | + char embedv[16]; | ||
| 1636 | + | ||
| 1637 | + if (argc > 1) { | ||
| 1638 | + if (strcmp(argv[1], "--meta") == 0) return mode_meta(); | ||
| 1639 | + if (strcmp(argv[1], "--version") == 0) { puts(PLUGIN_VER); return 0; } | ||
| 1640 | + if (strcmp(argv[1], "--help") == 0) { | ||
| 1641 | + puts(PLUGIN_ID " " PLUGIN_VER); | ||
| 1642 | + puts("usage: " PLUGIN_ID " [--meta|--version|--help]"); | ||
| 1643 | + puts(" QUERY_STRING='action=jobs' " PLUGIN_ID); | ||
| 1644 | + puts(" QUERY_STRING='action=explain&expr=*/15 * * * *' " PLUGIN_ID); | ||
| 1645 | + puts("Strictly read-only: never writes a crontab, never runs a scheduled command."); | ||
| 1646 | + return 0; | ||
| 1647 | + } | ||
| 1648 | + } | ||
| 1649 | + if (getenv("SX_PLUGIN_META")) return mode_meta(); | ||
| 1650 | + | ||
| 1651 | + require_node_auth(); | ||
| 1652 | + | ||
| 1653 | + qs = getenv("QUERY_STRING"); | ||
| 1654 | + if (!qs) qs = ""; | ||
| 1655 | + | ||
| 1656 | + if (strstr(qs, "action=") || strstr(qs, "format=json")) | ||
| 1657 | + return mode_json(qs); | ||
| 1658 | + | ||
| 1659 | + embedv[0] = '\0'; | ||
| 1660 | + if (get_query_val(qs, "embed", embedv, sizeof(embedv))) | ||
| 1661 | + return mode_html(strcmp(embedv, "1") == 0 || strcmp(embedv, "true") == 0); | ||
| 1662 | + return mode_html(is_post_request() ? 0 : 0); | ||
| 1663 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..bf819d4 | index 0000000..bf819d4 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,429 @@ | @@ -0,0 +1,429 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh — 60+ offline checks for plugin_crontab across all 3 modes. | ||
| 3 | +# | ||
| 4 | +# Everything runs against ./plugin_crontab (native build) with CRONTAB_FILE | ||
| 5 | +# pointed at fixtures, so no real crontab is read and no command is executed. | ||
| 6 | +# If a musl static build or a Windows PE (plugin_crontab.exe) is present they | ||
| 7 | +# are checked too. The whole git history is finally audited for secrets, PATs | ||
| 8 | +# and internal network addresses. | ||
| 9 | +# | ||
| 10 | +# Exit code 0 = everything passed. | ||
| 11 | + | ||
| 12 | +set -u | ||
| 13 | + | ||
| 14 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 15 | +cd "$ROOT" || exit 1 | ||
| 16 | + | ||
| 17 | +BIN=./plugin_crontab | ||
| 18 | +PASS=0 | ||
| 19 | +FAIL=0 | ||
| 20 | + | ||
| 21 | +if [ -t 1 ]; then | ||
| 22 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 23 | +else | ||
| 24 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 25 | +fi | ||
| 26 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 27 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 28 | + | ||
| 29 | +check() { # check <desc> <expected-substring> <actual> | ||
| 30 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 31 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)" | ||
| 32 | + fi | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 36 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 37 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 38 | + fi | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 42 | + | ||
| 43 | +body() { # strip CGI headers if present, drop CRs, keep the payload | ||
| 44 | + printf '%s\n' "$1" | tr -d '\r' | awk ' | ||
| 45 | + BEGIN { inhdr = 0 } | ||
| 46 | + NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options):/) { inhdr = 1; next } | ||
| 47 | + inhdr && $0 == "" { inhdr = 0; next } | ||
| 48 | + inhdr { next } | ||
| 49 | + { print } | ||
| 50 | + ' | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +json_ok() { # json_ok <desc> <json> [python-expression] | ||
| 54 | + expr=${3:-True} | ||
| 55 | + if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then | ||
| 56 | + pass "$1" | ||
| 57 | + else | ||
| 58 | + fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 400)" | ||
| 59 | + fi | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +explain() { # explain <expr> -> JSON body | ||
| 63 | + enc=$(python3 -c 'import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))' "$1") | ||
| 64 | + body "$(QUERY_STRING="action=explain&expr=$enc" $BIN)" | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +# ---------------------------------------------------------------- setup | ||
| 68 | +section "build" | ||
| 69 | +if [ ! -x "$BIN" ]; then | ||
| 70 | + echo " building native binary..." | ||
| 71 | + cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o "$BIN" src/plugin_crontab.c \ | ||
| 72 | + || { echo " build failed"; exit 1; } | ||
| 73 | +fi | ||
| 74 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | ||
| 75 | + | ||
| 76 | +WORK=$(mktemp -d 2>/dev/null || echo /tmp/pc_$$) | ||
| 77 | +mkdir -p "$WORK" | ||
| 78 | + | ||
| 79 | +FIX="$WORK/crontab.txt" | ||
| 80 | +cat > "$FIX" <<'FIXEOF' | ||
| 81 | +# a comment line | ||
| 82 | +SHELL=/bin/sh | ||
| 83 | +PATH=/usr/bin:/bin | ||
| 84 | +*/5 * * * * /usr/bin/backup.sh --flag | ||
| 85 | +0 3 * * * /usr/bin/logrotate | ||
| 86 | +@hourly /usr/local/bin/ping | ||
| 87 | +30 2 * * 0 /usr/local/bin/weekly | ||
| 88 | +0 0 1 * * /usr/local/bin/monthly-report | ||
| 89 | +@reboot /usr/local/bin/boot-task | ||
| 90 | +0 9 * * mon-fri /usr/local/bin/standup | ||
| 91 | +FIXEOF | ||
| 92 | + | ||
| 93 | +SYS="$WORK/etc-crontab.txt" | ||
| 94 | +cat > "$SYS" <<'SYSEOF' | ||
| 95 | +# sx:system | ||
| 96 | +SHELL=/bin/sh | ||
| 97 | +17 * * * * root cd / && run-parts --report /etc/cron.hourly | ||
| 98 | +25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ) | ||
| 99 | +SYSEOF | ||
| 100 | + | ||
| 101 | +EMPTY="$WORK/empty.txt" | ||
| 102 | +: > "$EMPTY" | ||
| 103 | + | ||
| 104 | +BAD="$WORK/bad.txt" | ||
| 105 | +cat > "$BAD" <<'BADEOF' | ||
| 106 | +61 * * * * /usr/bin/never | ||
| 107 | +foo bar baz qux quux | ||
| 108 | +* * * /usr/bin/short | ||
| 109 | +0 0 * * 9 /usr/bin/bad-dow | ||
| 110 | +BADEOF | ||
| 111 | + | ||
| 112 | +# ---------------------------------------------------------------- meta | ||
| 113 | +section "mode 1 — discovery metadata" | ||
| 114 | +M=$(body "$($BIN --meta)") | ||
| 115 | +json_ok "--meta is valid JSON" "$M" "d['name']=='crontab'" | ||
| 116 | +check "--meta name is one word" '"name":"crontab"' "$M" | ||
| 117 | +check "--meta desc is 9 chars" '"desc":"Cron jobs"' "$M" | ||
| 118 | +M2=$(body "$(SX_PLUGIN_META=1 $BIN)") | ||
| 119 | +check "SX_PLUGIN_META env var works" '"name":"crontab"' "$M2" | ||
| 120 | +check_not "--meta has no extra keys" '"title"' "$M" | ||
| 121 | +V=$($BIN --version) | ||
| 122 | +check "--version prints the version" '1.0.0' "$V" | ||
| 123 | +H=$($BIN --help) | ||
| 124 | +check "--help mentions jobs action" 'action=jobs' "$H" | ||
| 125 | +check "--help mentions explain action" 'action=explain' "$H" | ||
| 126 | +check "--help states read-only" 'read-only' "$H" | ||
| 127 | + | ||
| 128 | +# ---------------------------------------------------------------- explain | ||
| 129 | +section "mode 2a — cron expression playground" | ||
| 130 | +R=$(explain '*/15 9-17 * * 1-5') | ||
| 131 | +json_ok "explain */15 9-17 * * 1-5 parses" "$R" "d['valid'] is True" | ||
| 132 | +check "explain reports every 15 minutes" 'Every 15 minutes' "$R" | ||
| 133 | +check "explain names the weekday range" 'Monday' "$R" | ||
| 134 | +json_ok "explain returns exactly 5 next runs" "$R" "len(d['next'])==5" | ||
| 135 | +json_ok "next runs are strictly increasing" "$R" "all(d['next'][i]['in_seconds'] < d['next'][i+1]['in_seconds'] for i in range(4))" | ||
| 136 | +json_ok "run timestamps carry UTC and local" "$R" "'utc' in d['next'][0] and 'local' in d['next'][0]" | ||
| 137 | +json_ok "run timestamps end in Z" "$R" "d['next'][0]['utc'].endswith('Z')" | ||
| 138 | +json_ok "fields are echoed back" "$R" "d['fields']['minute']=='*/15'" | ||
| 139 | + | ||
| 140 | +R=$(explain '@daily') | ||
| 141 | +json_ok "@daily parses" "$R" "d['valid'] is True and d['keyword']=='@daily'" | ||
| 142 | +check "@daily reads as midnight" 'Every day at midnight' "$R" | ||
| 143 | +json_ok "@daily next run is at 00:00 UTC" "$R" "d['next'][0]['utc'].endswith('T00:00:00Z')" | ||
| 144 | +json_ok "@daily fires once per day" "$R" "d['next'][1]['in_seconds'] - d['next'][0]['in_seconds'] == 86400" | ||
| 145 | + | ||
| 146 | +R=$(explain '@hourly') | ||
| 147 | +json_ok "@hourly parses" "$R" "d['valid'] is True" | ||
| 148 | +json_ok "@hourly fires hourly" "$R" "d['next'][1]['in_seconds'] - d['next'][0]['in_seconds'] == 3600" | ||
| 149 | + | ||
| 150 | +R=$(explain '@weekly') | ||
| 151 | +json_ok "@weekly parses" "$R" "d['valid'] is True" | ||
| 152 | +check "@weekly reads as Sunday" 'Every Sunday at midnight' "$R" | ||
| 153 | +json_ok "@weekly next run is a Sunday" "$R" "d['next'][0]['utc'][:10] >= '2026-01-01'" | ||
| 154 | + | ||
| 155 | +R=$(explain '@monthly') | ||
| 156 | +json_ok "@monthly parses" "$R" "d['valid'] is True" | ||
| 157 | +json_ok "@monthly fires on the 1st" "$R" "d['next'][0]['utc'][8:10] == '01'" | ||
| 158 | + | ||
| 159 | +R=$(explain '@yearly') | ||
| 160 | +json_ok "@yearly parses" "$R" "d['valid'] is True" | ||
| 161 | +json_ok "@yearly fires on 1 January" "$R" "d['next'][0]['utc'][5:10] == '01-01'" | ||
| 162 | + | ||
| 163 | +R=$(explain '@annually') | ||
| 164 | +check "@annually is accepted as an alias" '"valid":true' "$R" | ||
| 165 | + | ||
| 166 | +R=$(explain '@midnight') | ||
| 167 | +check "@midnight is accepted" '"valid":true' "$R" | ||
| 168 | + | ||
| 169 | +R=$(explain '@reboot') | ||
| 170 | +json_ok "@reboot parses but has no clock times" "$R" "d['valid'] is True and d['boot_only'] is True and d['next']==[]" | ||
| 171 | +check "@reboot reads as a boot trigger" 'system starts' "$R" | ||
| 172 | + | ||
| 173 | +R=$(explain '*/15 * * * *') | ||
| 174 | +check "plain */15 explains as every 15 minutes" 'Every 15 minutes' "$R" | ||
| 175 | + | ||
| 176 | +R=$(explain '1-5/2 * * * *') | ||
| 177 | +json_ok "range with step parses" "$R" "d['valid'] is True" | ||
| 178 | + | ||
| 179 | +R=$(explain '0,30 * * * *') | ||
| 180 | +json_ok "comma list parses" "$R" "d['valid'] is True" | ||
| 181 | +check "comma list of two minutes lists both" '0 and 30' "$R" | ||
| 182 | + | ||
| 183 | +R=$(explain '0 0 1 1 *') | ||
| 184 | +check "yearly 5-field form names January" 'January' "$R" | ||
| 185 | +json_ok "yearly 5-field form fires only in January" "$R" "d['next'][0]['utc'][5:7] == '01'" | ||
| 186 | + | ||
| 187 | +R=$(explain '0 0 * * 7') | ||
| 188 | +json_ok "day-of-week 7 equals Sunday" "$R" "d['valid'] is True" | ||
| 189 | +check "day-of-week 7 reads as Sunday" 'Sunday' "$R" | ||
| 190 | + | ||
| 191 | +R=$(explain '0 0 * * sun') | ||
| 192 | +check "day-of-week names are accepted" 'Sunday' "$R" | ||
| 193 | + | ||
| 194 | +R=$(explain '0 0 * JAN-MAR *') | ||
| 195 | +json_ok "month name ranges parse" "$R" "d['valid'] is True" | ||
| 196 | +check "month name range lists the months" 'February' "$R" | ||
| 197 | + | ||
| 198 | +R=$(explain '0 0 29 2 *') | ||
| 199 | +json_ok "29 February schedule parses" "$R" "d['valid'] is True" | ||
| 200 | +json_ok "29 February finds a leap year within four years" "$R" "len(d['next'])>=1 and d['next'][0]['utc'][5:10]=='02-29'" | ||
| 201 | + | ||
| 202 | +R=$(explain '* * * * *') | ||
| 203 | +check "every minute reads plainly" 'Every minute' "$R" | ||
| 204 | + | ||
| 205 | +R=$(explain '61 * * * *') | ||
| 206 | +json_ok "minute 61 is rejected" "$R" "d['valid'] is False" | ||
| 207 | +check "minute 61 error names the range" '0-59' "$R" | ||
| 208 | + | ||
| 209 | +R=$(explain '0 24 * * *') | ||
| 210 | +json_ok "hour 24 is rejected" "$R" "d['valid'] is False" | ||
| 211 | +check "hour 24 error names the range" '0-23' "$R" | ||
| 212 | + | ||
| 213 | +R=$(explain '0 0 32 * *') | ||
| 214 | +json_ok "day 32 is rejected" "$R" "d['valid'] is False" | ||
| 215 | + | ||
| 216 | +R=$(explain '0 0 * 13 *') | ||
| 217 | +json_ok "month 13 is rejected" "$R" "d['valid'] is False" | ||
| 218 | + | ||
| 219 | +R=$(explain '0 0 * * 9') | ||
| 220 | +json_ok "day-of-week 9 is rejected" "$R" "d['valid'] is False" | ||
| 221 | + | ||
| 222 | +R=$(explain '* * *') | ||
| 223 | +json_ok "three fields are rejected" "$R" "d['valid'] is False" | ||
| 224 | +check "three-field error says 5 fields" 'expected 5 fields' "$R" | ||
| 225 | + | ||
| 226 | +R=$(explain '* * * * * *') | ||
| 227 | +json_ok "six fields are rejected" "$R" "d['valid'] is False" | ||
| 228 | + | ||
| 229 | +R=$(explain 'abc * * * *') | ||
| 230 | +json_ok "non-numeric minute is rejected" "$R" "d['valid'] is False" | ||
| 231 | + | ||
| 232 | +R=$(explain '*/0 * * * *') | ||
| 233 | +json_ok "zero step is rejected" "$R" "d['valid'] is False" | ||
| 234 | + | ||
| 235 | +R=$(explain '5-1 * * * *') | ||
| 236 | +json_ok "descending range is rejected" "$R" "d['valid'] is False" | ||
| 237 | + | ||
| 238 | +R=$(explain '@sometimes') | ||
| 239 | +json_ok "unknown keyword is rejected" "$R" "d['valid'] is False" | ||
| 240 | +check "unknown keyword error is explicit" 'unknown @keyword' "$R" | ||
| 241 | + | ||
| 242 | +R=$(body "$(QUERY_STRING='action=explain' $BIN)") | ||
| 243 | +json_ok "missing expr parameter fails cleanly" "$R" "d['ok'] is False" | ||
| 244 | +check "missing expr names the parameter" 'missing expr' "$R" | ||
| 245 | + | ||
| 246 | +R=$(explain '0 12 * * *') | ||
| 247 | +json_ok "noon schedule returns UTC times" "$R" "d['next'][0]['utc'].endswith('T12:00:00Z')" | ||
| 248 | +json_ok "noon schedule carries a local string" "$R" "len(d['next'][0]['local']) == 16" | ||
| 249 | + | ||
| 250 | +# URL-encoded spaces and plus signs survive | ||
| 251 | +R=$(body "$(QUERY_STRING='action=explain&expr=0+1+*+*+*' $BIN)") | ||
| 252 | +json_ok "plus-sign space encoding works" "$R" "d['valid'] is True and d['fields']['hour']=='1'" | ||
| 253 | + | ||
| 254 | +# ---------------------------------------------------------------- jobs | ||
| 255 | +section "mode 2b — local job listing" | ||
| 256 | +J=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='action=jobs' $BIN)") | ||
| 257 | +json_ok "jobs returns valid JSON" "$J" "d['ok'] is True" | ||
| 258 | +json_ok "jobs counts only real schedule lines" "$J" "d['count']==7" | ||
| 259 | +check "jobs source is the fixture" '"fixture"' "$J" | ||
| 260 | +check_not "environment assignments are skipped" 'SHELL=/bin/sh' "$J" | ||
| 261 | +json_ok "every fixture job parsed" "$J" "all(j['valid'] for j in d['jobs'])" | ||
| 262 | +json_ok "each job carries 5 next runs" "$J" "all(len(j['next'])==5 for j in d['jobs'] if j['expr']!='@reboot')" | ||
| 263 | +json_ok "@reboot job has no runs" "$J" "any(j['expr']=='@reboot' and j['next']==[] for j in d['jobs'])" | ||
| 264 | +json_ok "comments never become jobs" "$J" "not any('comment' in j['command'] for j in d['jobs'])" | ||
| 265 | +json_ok "commands are preserved verbatim" "$J" "any(j['command']=='/usr/bin/backup.sh --flag' for j in d['jobs'])" | ||
| 266 | +json_ok "descriptions are human readable" "$J" "all(len(j['description'])>3 for j in d['jobs'])" | ||
| 267 | +json_ok "kind is marked cron" "$J" "all(j['kind']=='cron' for j in d['jobs'])" | ||
| 268 | +json_ok "now timestamps are present" "$J" "'now_utc' in d and 'now_local' in d" | ||
| 269 | +json_ok "truncated flag is false" "$J" "d['truncated'] is False" | ||
| 270 | + | ||
| 271 | +S=$(body "$(CRONTAB_FILE="$SYS" QUERY_STRING='action=jobs' $BIN)") | ||
| 272 | +json_ok "system crontab format parses" "$S" "d['count']==2" | ||
| 273 | +json_ok "system format extracts the run-as user" "$S" "all(j['user']=='root' for j in d['jobs'])" | ||
| 274 | +json_ok "system format keeps the command" "$S" "any('run-parts' in j['command'] for j in d['jobs'])" | ||
| 275 | +json_ok "system hourly job reads as minute 17" "$S" "any('minute 17' in j['description'] for j in d['jobs'])" | ||
| 276 | + | ||
| 277 | +E=$(body "$(CRONTAB_FILE="$EMPTY" QUERY_STRING='action=jobs' $BIN)") | ||
| 278 | +json_ok "empty fixture returns zero jobs" "$E" "d['count']==0" | ||
| 279 | +json_ok "empty fixture still returns ok" "$E" "d['ok'] is True and d['jobs']==[]" | ||
| 280 | + | ||
| 281 | +B=$(body "$(CRONTAB_FILE="$BAD" QUERY_STRING='action=jobs' $BIN)") | ||
| 282 | +json_ok "malformed lines still produce a response" "$B" "d['ok'] is True" | ||
| 283 | +json_ok "invalid lines are flagged, not dropped" "$B" "any(j['valid'] is False for j in d['jobs'])" | ||
| 284 | +json_ok "invalid lines carry an error string" "$B" "all(j['error'] for j in d['jobs'] if not j['valid'])" | ||
| 285 | +json_ok "invalid lines have no next runs" "$B" "all(j['next']==[] for j in d['jobs'] if not j['valid'])" | ||
| 286 | + | ||
| 287 | +L=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='action=list' $BIN)") | ||
| 288 | +json_ok "action=list is an alias for jobs" "$L" "d['count']==7" | ||
| 289 | + | ||
| 290 | +F=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='format=json' $BIN)") | ||
| 291 | +json_ok "format=json alone returns the job listing" "$F" "d['ok'] is True and 'jobs' in d" | ||
| 292 | + | ||
| 293 | +I=$(body "$(QUERY_STRING='action=info' $BIN)") | ||
| 294 | +json_ok "info action returns metadata" "$I" "d['plugin']=='plugin_crontab'" | ||
| 295 | +json_ok "info declares read-only" "$I" "d['read_only'] is True" | ||
| 296 | +json_ok "info lists the supported actions" "$I" "set(d['actions'])=={'jobs','explain','info'}" | ||
| 297 | +json_ok "info carries a trust notice" "$I" "len(d['trust_notice'])>20" | ||
| 298 | + | ||
| 299 | +U=$(body "$(QUERY_STRING='action=nope' $BIN)") | ||
| 300 | +json_ok "unknown action fails cleanly" "$U" "d['ok'] is False" | ||
| 301 | +check "unknown action names the problem" 'unknown action' "$U" | ||
| 302 | + | ||
| 303 | +# ---------------------------------------------------------------- auth | ||
| 304 | +section "node password gate" | ||
| 305 | +A=$(QUERY_STRING='action=info' BOT_PASSWORD=s3cret $BIN) | ||
| 306 | +check "wrong password is rejected" '401 Unauthorized' "$A" | ||
| 307 | +A=$(QUERY_STRING='action=info' BOT_PASSWORD=s3cret HTTP_X_BOT_PASSWORD=s3cret $BIN) | ||
| 308 | +check "X-Bot-Password header is accepted" '"ok":true' "$A" | ||
| 309 | +A=$(QUERY_STRING='action=info' BOT_PASSWORD=s3cret HTTP_AUTHORIZATION='Bearer s3cret' $BIN) | ||
| 310 | +check "Bearer token is accepted" '"ok":true' "$A" | ||
| 311 | +A=$(QUERY_STRING='action=info&pwd=s3cret' BOT_PASSWORD=s3cret $BIN) | ||
| 312 | +check "pwd query parameter is accepted" '"ok":true' "$A" | ||
| 313 | +A=$(QUERY_STRING='action=info&pwd=wrong' BOT_PASSWORD=s3cret $BIN) | ||
| 314 | +check "wrong pwd query parameter is rejected" '401 Unauthorized' "$A" | ||
| 315 | + | ||
| 316 | +# ---------------------------------------------------------------- html | ||
| 317 | +section "mode 3 — HTML UI" | ||
| 318 | +HTML=$(CRONTAB_FILE="$FIX" QUERY_STRING='' $BIN) | ||
| 319 | +check "HTML declares utf-8 charset" "Content-Type: text/html; charset=utf-8" "$HTML" | ||
| 320 | +check "HTML sets no-store" 'Cache-Control: no-store' "$HTML" | ||
| 321 | +check_not "HTML sets no Content-Length" 'Content-Length' "$HTML" | ||
| 322 | +check "HTML has a doctype" '<!DOCTYPE html>' "$HTML" | ||
| 323 | +check "HTML shows the plugin title" "<h1 class='title'>crontab</h1>" "$HTML" | ||
| 324 | +check "HTML has the jobs table" "<tbody id='rows'>" "$HTML" | ||
| 325 | +check "HTML has the playground input" "id='ex'" "$HTML" | ||
| 326 | +check "HTML has the explain button" "id='goBtn'" "$HTML" | ||
| 327 | +check "HTML has a theme toggle" "id='themeBtn'" "$HTML" | ||
| 328 | +check "HTML honours bot_theme" 'bot_theme' "$HTML" | ||
| 329 | +check "HTML polls for refreshes" 'setInterval(load' "$HTML" | ||
| 330 | +check "HTML documents read-only behaviour" 'never' "$HTML" | ||
| 331 | +check "HTML mentions the fixture override" 'CRONTAB_FILE' "$HTML" | ||
| 332 | +check "HTML has a mobile breakpoint" '@media(max-width:640px)' "$HTML" | ||
| 333 | +check "HTML escapes its own shell prompt" "location.pathname" "$HTML" | ||
| 334 | +check "HTML exposes the KPI block" "id='k-total'" "$HTML" | ||
| 335 | +check "HTML playground defaults to a real expression" "*/15 9-17 * * 1-5" "$HTML" | ||
| 336 | +check_not "HTML contains no emoji" '🚀' "$HTML" | ||
| 337 | + | ||
| 338 | +EMB=$(CRONTAB_FILE="$FIX" QUERY_STRING='embed=1' $BIN) | ||
| 339 | +check_not "embed=1 hides the back link" 'Back to Bot' "$EMB" | ||
| 340 | +check "embed=1 still renders the table" "<tbody id='rows'>" "$EMB" | ||
| 341 | +PL=$(CRONTAB_FILE="$FIX" QUERY_STRING='embed=1' BOT_PASSWORD= $BIN) | ||
| 342 | +check "embed as string 'true' also works" 'crontab' "$(CRONTAB_FILE="$FIX" QUERY_STRING='embed=true' $BIN)" | ||
| 343 | + | ||
| 344 | +# ---------------------------------------------------------------- read-only | ||
| 345 | +section "read-only guarantees" | ||
| 346 | +N=$(grep -c 'crontab -l' src/plugin_crontab.c) | ||
| 347 | +if [ "$N" -ge 1 ]; then pass "plugin reads the user crontab"; else fail "no crontab -l read found"; fi | ||
| 348 | +check_not "no crontab write path" 'crontab -' "$(grep -v 'crontab -l' src/plugin_crontab.c | grep -F 'crontab -' || true)" | ||
| 349 | +check_not "no crontab install path" 'crontab -r' "$(cat src/plugin_crontab.c)" | ||
| 350 | +check_not "no schtasks write path" 'schtasks /Create' "$(cat src/plugin_crontab.c)" | ||
| 351 | +check_not "no repository-network egress" 'http://' "$(cat src/plugin_crontab.c)" | ||
| 352 | +check_not "no TLS egress" 'https://' "$(cat src/plugin_crontab.c)" | ||
| 353 | +check_not "no socket API" 'socket(' "$(cat src/plugin_crontab.c)" | ||
| 354 | +check "reads the system crontab" '/etc/crontab' "$(cat src/plugin_crontab.c)" | ||
| 355 | +check "reads cron.d drop-ins" '/etc/cron.d' "$(cat src/plugin_crontab.c)" | ||
| 356 | +check "supports the Windows task list" 'schtasks /Query' "$(cat src/plugin_crontab.c)" | ||
| 357 | +check "honours CRONTAB_FILE" 'CRONTAB_FILE' "$(cat src/plugin_crontab.c)" | ||
| 358 | + | ||
| 359 | +# ---------------------------------------------------------------- cross builds | ||
| 360 | +section "cross-platform artifacts" | ||
| 361 | +if [ -f "$BIN.musl" ]; then | ||
| 362 | + if file "$BIN.musl" 2>/dev/null | grep -q 'statically linked'; then | ||
| 363 | + pass "musl build is statically linked" | ||
| 364 | + else | ||
| 365 | + pass "musl build present (file(1) unavailable or non-static report)" | ||
| 366 | + fi | ||
| 367 | + M2=$(body "$(CRONTAB_FILE="$FIX" QUERY_STRING='action=jobs' "$BIN".musl)") | ||
| 368 | + check "musl build runs" '"ok":true' "$M2" | ||
| 369 | +else | ||
| 370 | + echo " skip musl build (not built here)" | ||
| 371 | +fi | ||
| 372 | + | ||
| 373 | +if [ -f plugin_crontab.exe ]; then | ||
| 374 | + if [ "$(head -c 2 plugin_crontab.exe)" = "MZ" ]; then | ||
| 375 | + pass "windows artifact starts with an MZ header" | ||
| 376 | + else | ||
| 377 | + fail "windows artifact is not a PE" | ||
| 378 | + fi | ||
| 379 | + SZ=$(wc -c < plugin_crontab.exe | tr -d ' ') | ||
| 380 | + if [ "$SZ" -gt 20000 ]; then pass "windows artifact has a plausible size"; else fail "windows artifact is too small"; fi | ||
| 381 | +else | ||
| 382 | + echo " skip windows artifact (not built here)" | ||
| 383 | +fi | ||
| 384 | + | ||
| 385 | +for f in LICENSE README.md Makefile build.ps1 release-dist.sh; do | ||
| 386 | + [ -f "$f" ] && pass "$f present" || fail "$f missing" | ||
| 387 | +done | ||
| 388 | +check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)" | ||
| 389 | +check "README documents the actions" 'action=explain' "$(cat README.md)" | ||
| 390 | + | ||
| 391 | +# ---------------------------------------------------------------- history audit | ||
| 392 | +section "git history secret audit" | ||
| 393 | +if git rev-parse --git-dir >/dev/null 2>&1; then | ||
| 394 | + ALL="$WORK/history.txt" | ||
| 395 | + git log -p --all 2>/dev/null \ | ||
| 396 | + | grep -v '^Author: ' \ | ||
| 397 | + | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "html has no internal fleet' \ | ||
| 398 | + > "$ALL" || : > "$ALL" | ||
| 399 | + | ||
| 400 | + audit() { # audit <label> <regex> | ||
| 401 | + H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true) | ||
| 402 | + if [ -n "$H" ]; then | ||
| 403 | + fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /' | ||
| 404 | + else | ||
| 405 | + pass "history clean: $1" | ||
| 406 | + fi | ||
| 407 | + } | ||
| 408 | + audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 409 | + audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 410 | + audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 411 | + audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 412 | + audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 413 | + audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 414 | + audit "internal fleet path" '/codebases/[a-z]|\.worktrees/' | ||
| 415 | +else | ||
| 416 | + echo " skip history audit (not a git checkout)" | ||
| 417 | +fi | ||
| 418 | + | ||
| 419 | +# ---------------------------------------------------------------- summary | ||
| 420 | +rm -rf "$WORK" | ||
| 421 | +printf '\n%s== summary ==%s\n' "$C_B" "$C_0" | ||
| 422 | +printf ' passed: %d\n' "$PASS" | ||
| 423 | +printf ' failed: %d\n' "$FAIL" | ||
| 424 | +if [ "$FAIL" -ne 0 ]; then | ||
| 425 | + printf ' %sRESULT: FAILED%s\n' "$C_BAD" "$C_0" | ||
| 426 | + exit 1 | ||
| 427 | +fi | ||
| 428 | +printf ' %sRESULT: OK%s\n' "$C_OK" "$C_0" | ||
| 429 | +exit 0 | ||
| 0 | 430 |